Reputation: 3992
I transfer the modExp function from int to BigInteger, but the result is different, what the different of these two functions?
Thanks!!!
The function with BigInteger, the result always 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;
}
The function with 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;
}
The function is to calculate a^b mod p
, For example:
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 ...
Upvotes: 4
Views: 23947
Reputation: 1003
In java int can count from -2^31 up to 2^31-1 because int are coded over 4 bytes but long can count from -2^63 up to 2^63-1 because long are coded over 8 bytes.
In the second method with this :
return (int) c;
you may loose data (the 4 first byte)
That could explain why your result are different because BigInteger are coded over much more byte than long
Upvotes: 0
Reputation: 7772
The obvious difference is the difference between int
and BigInteger
.
One difference is that int
is a primitive type and BigInteger
is a reference type. As such, it is better to use equals() when comparing BigInteger
s. So b == BigInteger.ZERO
should be BigInteger.ZERO.equals(b)
.
BigInteger is more suited to working with big numbers and will prevent you running into problems with overflowing the max int
value, supported by Java.
Overflowing may be the cause you are getting a different result from the two functions as well. When this occurs, it doesn't cause any exception to be thrown, but the values of the int
s get messed up.
Upvotes: 9