我將modExp函數從int傳遞給BigInteger,但結果不同,這兩個函數有什麼不同?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 ...
結果有什麼不同?他們在計算中的什麼時候分歧? –
它是否返回1,因爲b == 0 if語句? –
使用'compareTo'而不是'=='。 – Bubletan