Find factorials using BigInteger in java?

2019-07-27 07:22发布

问题:

I am trying to find the factorial of t numbers and input for each number n is provided by the user.The constraints are;

1 < t <= 100
1 < n <= 100

My code is :

import java.util.Scanner;
import java.math.BigInteger;

public class fact {
    public static void main(String args[]) {
        int t = 0, i = 0;
         BigInteger result = BigInteger.valueOf(1);
         BigInteger x1 = BigInteger.ONE;
         Scanner sc = new Scanner(System.in);
         t = sc.nextInt();
         BigInteger a[] = new BigInteger[t];

        for(i = 0; i < t; i++) {
           a[i] = BigInteger.valueOf(sc.nextInt());
        }

        for(i = 0; i < t; i++) {
            while(!a[i].equals(x1)) {
               result = result.multiply(a[i]);
               a[i].subtract(BigInteger.valueOf(1));
            }
            System.out.println(result);
            result = x1;
        }
    }
}

I am receiving no errors for the above code it compiles fine and when I execute it just keeps on getting input and no output is printed.

回答1:

On this line:

a[i].subtract(BigInteger.valueOf(1));

Since BigIntegers are immutable, subtract() returns a new BigInteger. You need to store the result, or you will get an endless loop. Change to

a[i] = a[i].subtract(BigInteger.ONE);