我在12岁以前打印数字时遇到问题!(阶乘).
有人可以帮帮我吗?我甚至不确定我是否正确使用这个课程.
public class Application{
public static int factorial(int n){
int index = n;
int total = 1;
while(index > 0){
total *= index;
index --;
}
return total;
}
public static void print(int n){
int index = n;
while(index > 0){
BigInteger big = BigInteger.valueOf(factorial(index));
System.out.println(index + ": " + big);
index --;
}
}
public static void main(String[] args){
int n = 30;
print(n);
}
}
这是它打印出来的片段:
18: -898433024
17: -288522240
16: 2004189184
15: 2004310016
14: 1278945280
13: 1932053504
12: 479001600
解决方法:
在您的阶乘函数中使用BigInteger,而不是“在完成计算后”.
另请注意,在乘以BigIntegers时,请使用BigInteger.multiply(BigInteger val)
方法而不是*.
这是已更改的方法,它与您的方法完全相同,只是它使用BigInteger而不是int:
public static BigInteger factorial(int n){
int index = n;
BigInteger total = BigInteger.valueOf(1);
while(index > 0){
total = total.multiply(BigInteger.valueOf(index));
index --;
}
return total;
}
请注意,您也不需要将方法的返回值转换为BigInteger,例如做就是了:
BigInteger big = factorial(index);
这是输出:
30: 265252859812191058636308480000000
29: 8841761993739701954543616000000
28: 304888344611713860501504000000
27: 10888869450418352160768000000
26: 403291461126605635584000000
25: 15511210043330985984000000
24: 620448401733239439360000
23: 25852016738884976640000
22: 1124000727777607680000
21: 51090942171709440000
20: 2432902008176640000
19: 121645100408832000
18: 6402373705728000
17: 355687428096000
16: 20922789888000
15: 1307674368000
14: 87178291200
13: 6227020800
12: 479001600
11: 39916800
10: 3628800
9: 362880
8: 40320
7: 5040
6: 720
5: 120
4: 24
3: 6
2: 2
1: 1