在Java中使用BigInteger查找析因? [英] Find factorials using BigInteger in java?
本文介绍了在Java中使用BigInteger查找析因?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试查找t个数的阶乘,并且每个n的输入都由用户提供.约束是;
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
我的代码是:
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.
推荐答案
在这一行:
a[i].subtract(BigInteger.valueOf(1));
因为 BigInteger
是不可变, BigInteger
.您需要存储结果,否则将陷入无尽的循环.更改为
Since BigInteger
s 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);
这篇关于在Java中使用BigInteger查找析因?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文