gpt4 book ai didi

java - 阶乘表的问题

转载 作者:行者123 更新时间:2023-12-02 06:29:49 25 4
gpt4 key购买 nike

我必须为作业制作一个阶乘表,但我的逻辑在某个地方不正确。这是我到目前为止所拥有的。

public static void factors(int n) {
int r = 1; //starts r as zero, as a basis for multiplication
int t = n;
int q; //allows original number to be shown
while(n > 1) { // factorial calculation
r= r * n;
n = n- 1;
}
while(t>0) {
table(t,r);
t=t-1;
}
}

public static void table(int t, int r){
// while(n>0)
System.out.println(t+ "\t"+r);
// n=n-1;

}

这是输出。

15  1409286144
14 1409286144
13 1409286144
12 1409286144
11 1409286144
10 1409286144
9 1409286144
8 1409286144
7 1409286144
6 1409286144
5 1409286144
4 1409286144
3 1409286144
2 1409286144
1 1409286144

最佳答案

首先获取一个阶乘,然后再考虑表格。

名称很重要:“factors”对于阶乘方法来说并不是一个好名称。

这是一个天真的、非常低效的实现:

public class Factorial {

private static Map<Integer, Long> memo = new ConcurrentHashMap<Integer, Long>();

public static void main(String[] args) {
for (int i = 0; i < 11; ++i) {
System.out.println(String.format("n: %d n!: %d", i, factorial(i)));
}
}
public static long factorial(int n) {
long value = 1L;
if (n > 1) {
if (memo.containsKey(n)) {
value = memo.get(n);
} else {
for (int i = 1; i <= n; ++i) {
value *= i;
}
memo.put(n, value);
}
}
return value;
}
}

关于java - 阶乘表的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20166308/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com