Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Int to BigInteger, what's the difference?

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 ...
like image 822
Stephen Avatar asked Oct 21 '25 00:10

Stephen


1 Answers

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 BigIntegers. 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 ints get messed up.

like image 160
Danail Alexiev Avatar answered Oct 23 '25 12:10

Danail Alexiev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!