0

-46 modulo 7 is 3, but I get -4. Why?

int sa=-46;
int p=7;
System.out.println(sa);//-46
sa=sa%p;
System.out.println(sa);//-4

Edit:

This is how I solved it

(sa) % p + p) % p;

George Irimiciuc
  • 4,573
  • 8
  • 44
  • 88

1 Answers1

1

Java definition of % (remainder operator)

The Java programming language provides operators that perform addition, subtraction, multiplication, and division. There's a good chance you'll recognize them by their counterparts in basic mathematics. The only symbol that might look new to you is "%", which divides one operand by another and returns the remainder as its result.

(see source of reference here)

If you want to create a modulo function that returns only numbers in the range [0, n) when you ask for modulo n you will have to write it (simple).

ErstwhileIII
  • 4,829
  • 2
  • 23
  • 37