我的代码没有显示生成数字阶乘的确切输出,使用for loop.It将所有数字的值显示为0。
public class Factorial {
public static void main(String[] args) {
int NUM_FACTS = 100;
for(int i=1;i<=NUM_FACTS;i++) {
System.out.println("Factorial of "+i+" is "+ `enter code here`factorial(i));
}
}
//getting factorial of a particular number
public static int factorial(int n) {
int result = 1;
for(int i=2; i<n; i++)
result *= i;
return result;
}
}发布于 2019-01-12 22:11:22
100!将具有24 zeros, not counting the numbers in front,并且它不适合int数据类型。要么使用java.util.BigInteger,要么从计算值切换到近似值,例如使用Stirling's approximation公式。
public static BigInteger factorial(int n) {
BigInteger result = BigInteger.ONE;
for (int i = 2; i <= n; i++) {
result = result.multiply(BigInteger.valueOf(i));
}
return result;
}
public static void main(String[] args) {
System.out.println(factorial(100));
}将输出:
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000发布于 2019-01-12 22:11:55
您的代码至少在达到一定数量的i之前有效。在这里,您可以看到其输出的一部分。
Factorial of 1 is 1
Factorial of 2 is 1
Factorial of 3 is 2
Factorial of 4 is 6
...
Factorial of 15 is 1278945280
Factorial of 16 is 2004310016
Factorial of 17 is 2004189184
Factorial of 18 is -288522240
Factorial of 19 is -898433024
Factorial of 20 is 109641728正如您从输出中看到的,符号正从正变为负。这是因为int的范围有限-您会看到溢出。更改为long也无济于事,因为它的范围也不够。考虑使用BigInteger。
https://stackoverflow.com/questions/54160317
复制相似问题