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
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.
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.
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