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

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

Jon Skeet
people
quotationmark

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.

people

See more on this question at Stackoverflow