繁体   English   中英

N! BigInteger做了一个循环

[英]n! BigInteger makes a loop

我写了这个小程序来找到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。忽略输入类,它只是我创建的用于更快输入输入的类)

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

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

有两个变化:

  1. 它应该<=0而不是<0
  2. 将其分配回i以进行更新。

怎么确认?

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM