Reputation: 861
I am running a for loop and inside my loop I have the following:
for(int i = 0; i < 12; i = i + 2){
System.out.println("i = " + i);
System.out.print("3 - i % 3 (i is at " + i + ") = " + (3 - i % 3));
System.out.println();
System.out.println("3 - i (" + (i) + ") = " + (3 - i));
}
I do understand how Modulus works normally or with positive numbers, but I do not understand how it works with negative integers? Can anyone explain it to me please?
Many thanks.
Upvotes: 0
Views: 104
Reputation: 33116
a mod b
is very well defined for positive integers a
and b
. What if a
or b
are negative? There are three choices that are consistent with that base definition:
a mod b
is always positive.a mod b
has the same sign as a
.a mod b
has the same sign as b
.Different languages will choose one of these three choices. There is no singular correct answer.
Upvotes: 2
Reputation: 83253
4 % 3 == 1
-4 % 3 == -1
4 % -3 == 1
-4 % -3 == -1
Changing the sign of the first number changes the sign of the result. The sign of the second number doesn't matter.
This is true in many languages (C, C++, Java, Javascript) but not all languages (Python, Ruby).
Upvotes: 1