因数为100的数字

时间:2015-03-27 03:57:03

标签: java

该程序保持返回"因子100为0"每100个数字作为输出。 问题出在哪里?

public class Factorial4 {
    public static void main(String[] args) {
        for (int i=1; i<=100; i++){
            System.out.println("Factorial of " + i + " is " + factorial(i));
        }
    }

    public static int factorial(int n){ 
        int result = 1;
        for (int i=1; i<=100; i++){
            result *= i;
        }
        return result;
    }
}

4 个答案:

答案 0 :(得分:2)

此代码有多个问题:

  1. 你总是创建100的阶乘(循环运行到100)。
  2. factorial将创建远远大于Integer.MAX_VALUE的值。您必须使用BigInteger代替。 0只是大量溢出的结果。

答案 1 :(得分:2)

n不是100

public static int factorial (int n){
    int result = 1;
    for (int i = 2; i <= n; i++) { // <-- n, not 100.also, x*1=x
        result *= i;
    }
    return result;
}

值得注意的是,int100!溢出,因此您可以使用BigInteger之类的

public static BigInteger factorial(int n) {
    BigInteger result = BigInteger.ONE;
    for (int i = 2; i <= n; i++) { // <-- n, not 100.also, x*1=x
        result = result.multiply(BigInteger.valueOf(i));
    }
    return result;
}

答案 2 :(得分:0)

正确的逻辑是

public static BigInteger factorial(int n){ 
    BigInteger result = 1;
    for (int c=1; c<=n; c++){
        result =result.multiply(BigInteger.valueOf(c));
    }
    return result;
}

使用BigInteger会有意义,因为result会超过int范围

答案 3 :(得分:0)

整数范围问题...对于小'n',你可以使用long(对于'result'),对于较大的'n',可以使用double。

相关问题