I have a formula to evaluate
((x+y-1)*(x+y-2))/2 + x
and get the string representation of it. So 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 the out put of 672047173 while Python gave me 19999400005 and seems the value from Python is correct. What is the reason behind this difference.
19999400005 is a too large value for int variables, so the Java calculations would 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 is:
19999400005
Also note that you can print answer directly and don't have to convert it to String explicitly:
System.out.println(answer);
Because integer range in java is minimum -2,147,483,648 and a maximum value of 2,147,483,647.
int answer = ((x+y-1)*(x+y-2))/2 + x;
In this line you are assigning higher range value to integer. It causes integer overflow on the arithmetic operation. So that is why you are getting incorrect value to get correct value you have to use 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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With