计算阶乘,我哪里出错了?

时间:2016-10-09 03:29:21

标签: java

这是我的任务的一部分,并被要求计算5和7的阶乘。

我完成如下:

 import java.util.Scanner;
    public class Factorial {
        public static void main(String [] args)
        {
            System.out.println("Please enter a number: ");
            Scanner input=new Scanner(System.in);
            int number=input.nextInt();
            int i,fact=1;  

              for(i=1;i<=number;i++){    
                  fact=fact*i;    
              }    
              System.out.println("Factorial of " + number + " is: " + fact);          
        }
    }

它适用于5和7(产生120和5040)。 但我的教授过来用20和987654321测试它,结果返回-2102132736和0。

为什么?

P.S。我想到了987654321的情况,结果会破坏应用程序或返回错误,因为它会很大。

3 个答案:

答案 0 :(得分:2)

此代码可以解决您的问题。 It is taken from here

class BigFactorial
{
    static void factorial(int n)
    {
        int res[] = new int[300];

        // Initialize result
        res[0] = 1;
        int res_size = 1;

        // Apply simple factorial formula n! = 1 * 2 * 3 * 4...*n
        for (int x=2; x<=n; x++)
            res_size = multiply(x, res, res_size);

        System.out.println("Factorial of given number is: ");
        for (int i=res_size-1; i>=0; i--)
            System.out.print(res[i]);
    }

    // This function multiplies x with the number represented by res[].
    // res_size is size of res[] or number of digits in the number represented
    // by res[]. This function uses simple school mathematics for multiplication.
    // This function may value of res_size and returns the new value of res_size
    static int multiply(int x, int res[], int res_size)
    {
        int carry = 0;  // Initialize carry

        // One by one multiply n with individual digits of res[]
        for (int i=0; i<res_size; i++)
        {
            int prod = res[i] * x + carry;
            res[i] = prod % 10;  // Store last digit of 'prod' in res[]
            carry  = prod/10;    // Put rest in carry
        }

        // Put carry in res and increase result size
        while (carry!=0)
        {
            res[res_size] = carry%10;
            carry = carry/10;
            res_size++;
        }
        return res_size;
    }

    // Driver program
    public static void main(String []args)
    {
        factorial(100);

    }

}

答案 1 :(得分:1)

因为5040!非常更大的数字(甚至long溢出)。使用BigInteger之类的

System.out.println("Please enter a number: ");
Scanner input = new Scanner(System.in);
int number = input.nextInt();
BigInteger fact = BigInteger.ONE;
for (int i = 2; i <= number; i++) { // <-- x * 1 = x
    fact = fact.multiply(BigInteger.valueOf(i));
}
System.out.println("Factorial of " + number + " is: " + fact);

答案 2 :(得分:1)

这是因为您用于存储和打印结果的容器没有容纳这么大的整数(我的意思是20的因子)。所以,你需要一个更大的容器。正如其他人已经建议的那样,你可以使用BIGINTEGER。