Shimano
Shimano

Reputation: 795

Java and Python codes give different output?

This is the Java code that results 897986030:

import java.util.Arrays;
import java.util.Scanner;

class Algorithm {
    public static void main(String args[]) throws Exception {
        int mod = 1000000007;
        long factor  = 900414279;
        long p1 = 883069911;
        long p2 = 32;
        long val = 560076994;
        val = (val%mod+factor*p1*p2%mod)%mod;
        System.out.println(val);
    }
}

This is the equivalent Python code that outputs 480330031:

factor  = 900414279
p1 = 883069911
p2 = 32;
val = 560076994;
mod = 1000000007;
val = (val%mod+factor*p1*p2%mod)%mod;
print val

Please help. Thanks!

Upvotes: 1

Views: 41

Answers (1)

Curious
Curious

Reputation: 21530

The answer lies in the fact that you are using primitive types in java that are prone to overflows.

Let me explain if you are not aware of this concept already. In java, C, C++ and the likes primitive types have a certain amount of space allocated for them and the variables cannot use any space more than that. This means that there is a maximum number that the long data type can store. This is done for performance reasons.

What might be happening in the code above is that when you multiply two long values the result might become larger than the maximum the long data type can store. And this results in an overflow, causing the data to be narrowed. So the results of the math expression are messed up.

With Python this is not that much of an issue because Python can store numbers of a much larger range. Overflows are rare in Python. And this is why things like cryptographic applications where big numbers are used are easy to write in Python.

Upvotes: 1

Related Questions