简体   繁体   中英

n! BigInteger makes a loop

I've written this little program to find 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. 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. 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)

This should be like this because i.add(BigInteger.ONE) doesn't update the variable i .

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

There are two changes:

  1. It should be <=0 instead of <0
  2. Assign it back to i to update it.

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. Thus, each time in the loop that you call i.add(BigInteger.ONE) , the computer calculates i+1 and then throws away the result. Instead, try:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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