简体   繁体   中英

How to use properly BigInteger methods in Java?

I'm trying to do the factorial of a number using this method:

public static BigInteger factorial (long n) {
    BigInteger result = BigInteger.ONE;
    for(BigInteger i = BigInteger.TWO; i.compareTo(BigInteger.valueOf(n)) >= 0; i = i.add(BigInteger.ONE)) {
        result = result.multiply(i);
    }
    return result;
}

and I'm asking why te result stays always 1 (BigInteger.ONE) ?

See the definition of compareTo(T o)

Returns : a negative integer , zero, or a positive integer as this object is less than , equal to, or greater than the specified object.

You are using >= 0 meaning continue looping while i is greater than n .

You probably need <= 0 .

i.compareTo(BigInteger.valueOf(n)) >= 0

是错误的,而是使用

i.compareTo(BigInteger.valueOf(n)) <= 0

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