使用for循环的Java阶乘代码未显示确切输出

时间:2019-01-12 14:05:26

标签: java factorial

我的代码未显示使用for循环生成数字阶乘的确切输出,而是将所有数字的所有值显示为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;
}
}

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

您的代码至少可以工作到一定数量的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