Int 到 BigInteger,有什么区别?

Ste*_*hen 2 java math biginteger

我把modExp函数从int转为BigInteger,结果不一样,这两个函数有什么区别?

谢谢!!!

带有 BigInteger 的函数,结果始终为 1:

public static BigInteger modExp(BigInteger a, BigInteger b, BigInteger n) {
    BigInteger two = new BigInteger("2");       
    if (b == BigInteger.ZERO)
        return BigInteger.ONE;
    BigInteger t = modExp (a, b.divide(two), n);
    BigInteger c = (t.pow(2)).mod(n);
    if (b.mod(two) == BigInteger.ONE)
        c = (c.multiply(a)).mod(n);
    return c;       
}
Run Code Online (Sandbox Code Playgroud)

带int的函数:

public static int modexp(int a, int b, int n) {
    if (b == 0) return 1;
    long t = modexp(a, b/2, n);  // use long for intermediate computations to eliminate overflow
    long c = (t * t) % n;
    if (b % 2 == 1)
       c = (c * a) % n;
    return (int) c;
}
Run Code Online (Sandbox Code Playgroud)

功能是计算a^b mod p,例如:

a=4 b=6 p=11  result1 = 1  result2 = 4
a=9 b=2 p=11  result1 = 1  result2 = 4
a=5 b=6 p=23  result1 = 1  result2 = 8 ...
Run Code Online (Sandbox Code Playgroud)

Dan*_*iev 8

最明显的区别是之间的差异intBigInteger

一个区别是它int是原始类型和BigInteger引用类型。因此,在比较BigIntegers时最好使用 equals() 。所以b == BigInteger.ZERO应该是BigInteger.ZERO.equals(b)

BigInteger 更适合处理大数字,并且可以防止您遇到intJava 支持的最大值溢出问题。

溢出可能是您从这两个函数中得到不同结果的原因。发生这种情况时,不会引发任何异常,但ints的值会混乱。