Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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);
        System.out.println("B.mod(A) is " + B.mod(A));

Output:

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

B is 7766279771452241969
B.mod(A) is 0

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading