N! BigInteger做了一个循环

时间:2014-07-27 13:50:16

标签: java loops biginteger

我写了这个小程序来找到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);

现在我正在尝试使用BigInteger重写此程序。我写了这个:

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

    }
}

但是这个带有BigInteger的程序会产生一个循环,我无法理解为什么。我希望有人可以帮助我。非常感谢你 ;)。 (nb。忽略输入类,它只是我创建的用于更快输入输入的类)

2 个答案:

答案 0 :(得分:1)

这应该是这样的,因为i.add(BigInteger.ONE)不会更新变量i

for (; i.compareTo(big) <= 0; i=i.add(BigInteger.ONE)) {
    tot = tot.multiply(i);
}

有两处变化:

  1. 应该是<=0而不是<0
  2. 将其分配回i进行更新。
  3. 如何确认?

    BigInteger i = new BigInteger("2");
    System.out.println(i.add(BigInteger.ONE));   // print 3
    System.out.println(i);                       // print 2
    

答案 1 :(得分:1)

BigInteger是不可变的,因此除非使用=运算符为其设置新值,否则其值不会更改。因此,每次在循环中调用i.add(BigInteger.ONE)时,计算机都会计算i + 1,然后丢弃结果。相反,尝试:

for (; i.compareTo(big) < 0; i=i.add(BigInteger.ONE)){