Search code examples
javabigintegermodulo

modulo gives wrong result for big number in Java


look at the below Java Code :

        long a = (long) 10e9+7;
        long b = (a * a);

        System.out.println("b is " + b);
        System.out.println("b%a is " + (b%a));

        System.out.println();


        BigInteger A = BigInteger.valueOf((long) 10e9+7);
        BigInteger B = A.multiply(A);


        System.out.println("B is " + B.longValue());
        System.out.println("B.mod(A) is " + B.mod(A));

Output:

b is 7766279771452241969
b%a is 6015846137   ///->> why ?? overflow 

B is 7766279771452241969 //// -> should not overflow 
B.mod(A) is 0

I was expecting % to give 0 in above case. But it gives some other numbers for the %


Solution

  • a * a overflows the value of Long.MAX_VALUE. As Benoit suggested in his comment, you're printing b twice. The value of B is not 7766279771452241969 but 100000000140000000049.