Int to BigInteger,有什么区别?

时间:2015-08-21 14:29:01

标签: 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;       
}

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

该函数用于计算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 ...

2 个答案:

答案 0 :(得分:4)

明显的区别在于intBigInteger之间的差异。

一个区别是int是基本类型,BigInteger是引用类型。因此,在比较BigInteger时,最好使用equals()。因此b == BigInteger.ZERO应为BigInteger.ZERO.equals(b)

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

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

答案 1 :(得分:0)

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

在第二种方法中:

return (int) c;

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

这可以解释为什么你的结果不同,因为BigInteger编码的字节多于长