Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Long unable to accept 12 digit value even though I explicitly declared it to?

Tags:

java

import java.io.*;
import java.util.*;
public class Solution
{
    public static void main(String args[])
    {
            Scanner s=new Scanner(System.in);

            int k=s.nextInt();
            long  value=0L;

            value=(k-(k/2)) * (k/2);

            System.out.println(value);

    }
}

Now, I gave my input as 1856378 for k,
Expected output is 861534819721
but I got -1753606775

Why is giving wrong answer eventhough the value is long

like image 983
unknownerror Avatar asked Dec 14 '22 17:12

unknownerror


2 Answers

In the expression

(k-(k/2)) * (k/2)

There are no long values involved, only int values. As such, no value is promoted to int. We simply have int arithmetic. You're limited with the range of int.

If k would be declared as a long, things would be different

long k = s.nextInt();

Similarly, you could cast or declare one of the values of the expression as a long.

value = (k - (k / 2L)) * (k / 2);

But this may depend on associativity and order of execution. It will work here, but not necessarily in other expressions.

like image 179
Sotirios Delimanolis Avatar answered Dec 17 '22 06:12

Sotirios Delimanolis


You're assigning to a long, but all the arithmetic is being done with int, because every part of the expression (k-(k/2)) * (k/2) is an int.

The simplest fix would be to declare k as a long, e.g.

long k = s.nextInt();
long value = (k-(k/2)) * (k/2);

You could alternatively use 2L for the literal in either of the division operations - it's only the multiplication that you really need to be done using long arithmetic.

It's always worth bearing in mind that the calculation on the right hand side of an assignment operator is completely separate from whatever it happens to be assigned to.

like image 40
Jon Skeet Avatar answered Dec 17 '22 05:12

Jon Skeet