Reputation: 25
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)
Upvotes: 3
Views: 96
Reputation: 2287
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)){
Upvotes: 1
Reputation: 46841
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:
<=0
instead of <0
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
Upvotes: 1