Int 和 BigInteger,有什么区别?

Int to BigInteger, what's the difference?

我把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;       
}

带整数的函数:

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;
}

函数是计算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 ...

最明显的区别就是intBigInteger的区别。

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

BigInteger 更适合处理大数字,并且会防止 运行 出现溢出最大 int 值的问题,Java 支持。

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

在 java 中,int 可以从 -2^31 计数到 2^31-1,因为 int 编码超过 4 个字节,但 long 可以从 -2^63 计数到 2^63-1,因为long 编码超过 8 个字节。

在第二种方法中:

return (int) c;

您可能会丢失数据(第 4 个字节)

这可以解释为什么您的结果不同,因为 BigInteger 的编码比 long 多得多