Different for the same function in Java vs Python
I have a formula to evaluate
((x+y-1)*(x+y-2))/2 + x
and get a string representation. Therefore, in Java 1.7 I write
public static void main(String[] args)
{
int x = 99999;
int y = 99999;
int answer = ((x+y-1)*(x+y-2))/2 + x;
String s = Integer.toString(answer);
System.out.println(s);
}
and in Python 2.7
def answer(x, y):
z = ((x+y-1)*(x+y-2))/2 + x
return str(z);
print(answer(99999,99999))
Java gave me a message 672047173
while Python gave me 19999400005
and it seems that the value from Python is correct. What is the reason for this difference.
source to share
19999400005
is too large for variables int
, so Java computations will overflow.
Use long
variables instead :
public static void main(String[] args)
{
long x = 99999;
long y = 99999;
long answer = ((x+y-1)*(x+y-2))/2 + x;
String s = Long.toString(answer);
System.out.println(s);
}
Output:
19999400005
Also note that you can print answer
directly and don't need to explicitly convert it to String
:
System.out.println(answer);
source to share
Because integer range in java is minimum -2147,483,648 and maximum value 2,147,483,647.
int answer = ((x + y-1) * (x + y-2)) / 2 + x;
On this line, you are assigning a larger range value to an integer. It causes an integer overflow on arithmetic operation. This is why you are getting the wrong value to get the correct value you should be using the Long data type.
public static void main(String[] args)
{
int x = 99999;
int y = 99999;
long answer = (((x+y-1)*1l)*((x+y-2)*1l))/2 + x;
String s = Long.toString(answer);
System.out.println(s);
}
source to share