Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different out for same function in Java against Python

Tags:

java

python

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.

like image 503
Isham Mohamed Avatar asked Dec 09 '25 12:12

Isham Mohamed


2 Answers

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);
like image 191
Eran Avatar answered Dec 12 '25 02:12

Eran


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);
}
like image 22
Ankur Avatar answered Dec 12 '25 02:12

Ankur



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!