Find factorials using BigInteger in java?

不羁岁月 提交于 2019-12-13 02:06:38

问题


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);


来源:https://stackoverflow.com/questions/24854456/find-factorials-using-biginteger-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!