[英]n! BigInteger makes a loop
I've written this little program to find n!: 我写了这个小程序来找到n!:
public class Fattoriale {
public static void main (String[] args){
int n;
do {
n = Input.readInt("Enter an int number ( int >=0)");
while( n < 0);
long fatt = 1;
for (int i = 2; i <= n; i++){
fatta = fatt * i;
}
System.out.println(n"+!" + " = " + fatt);
Now I'm trying to rewrite this program using BigInteger. 现在我正在尝试使用BigInteger重写这个程序。 I've written this:
我写过:
import jbook.util.*;
import java.math.*;
public class Fattoriale {
public static void main (String[] args){
String s = Input.readString("Enter an int number. ");
BigInteger big = new BigInteger(s);
BigInteger tot = new BigInteger("1");
BigInteger i = new BigInteger("2");
for (; i.compareTo(big) < 0; i.add(BigInteger.ONE)){
tot = tot.multiply(i);
}
System.out.println(tot);
}
}
But this program with BigInteger makes a loop and I can't understand why. 但是BigInteger的这个程序会产生一个循环,我无法理解为什么。 I hope somebody can help me.
我希望有人可以帮助我。 Thank you very much ;).
非常感谢你 ;)。 (nb. ignore Input class, it's only a class that I created to enter input faster)
(nb。忽略输入类,它只是我创建的用于更快输入输入的类)
This should be like this because i.add(BigInteger.ONE)
doesn't update the variable i
. 这应该是这样的,因为
i.add(BigInteger.ONE)
不更新变量i
。
for (; i.compareTo(big) <= 0; i=i.add(BigInteger.ONE)) {
tot = tot.multiply(i);
}
There are two changes: 有两个变化:
<=0
instead of <0
<=0
而不是<0
i
to update it. i
以进行更新。 How to confirm? 怎么确认?
BigInteger i = new BigInteger("2");
System.out.println(i.add(BigInteger.ONE)); // print 3
System.out.println(i); // print 2
BigInteger
is immutable, so unless you set a new value for it using the =
operator, its value doesn't change. BigInteger
是不可变的,因此除非使用=
运算符为其设置新值,否则其值不会更改。 Thus, each time in the loop that you call i.add(BigInteger.ONE)
, the computer calculates i+1 and then throws away the result. 因此,每次在循环中调用
i.add(BigInteger.ONE)
,计算机将计算i + 1,然后丢弃结果。 Instead, try: 相反,尝试:
for (; i.compareTo(big) < 0; i=i.add(BigInteger.ONE)){
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.