0

I was writing a code (I knew the output,In Java) , after compiling it giving the input i got a weird value.

Code Snippet -

    long a,b,c;
    a=-245436499;
    b=992;
    c=(a+b);
    System.out.print(c%b);

And the Output it gave me was

-819

But when i calculated it on calculator, it was

173 \\why?

Proof:
Calculators output
Compiler's output

NamyaPa
  • 19
  • 3

1 Answers1

5

There are two ways of calculating modulo of a negative number:

  1. Java (as per the JLS) uses the "preserve sign" method; ie if the first operand is negative, non-zero results are negative
  2. Results are (made) positive by adding (if necessary) the second operand to the result of method 1

Your calculator clearly uses method 2 (-819 + 992 = 173)

Bohemian
  • 412,405
  • 93
  • 575
  • 722