3

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.

2 Answers 2

6

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Java calculations definitely overflow in this case.
3

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);
}

2 Comments

This will still not work. int * int gives result in int and then assign it to long so still you would get answer with affection of integer overflow. If you want to do same with integer you can do as 1L * (x+y-1) * (x+y-2) this will now do multiplication operation in long.
You are wrong here. Implicit casting will be done after multiplication operation and multiplication will be done in integer data type which will cause an overflow and give you wrong answer. You can check by running your snippet.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.