noircc
noircc

Reputation: 640

Why is -7 mod 3 = 2 in Ruby?

I am coming from Java to Ruby and this -7 mod 3 = 2 puzzles me

Upvotes: 2

Views: 1463

Answers (3)

weston
weston

Reputation: 54781

The mod function gives the remainder above the greatest multiple less than the first parameter.

If it were 7 mod 3, then 6 is the greatest multiple less than 7, so 1 is the answer (7-6)

As it is -7, then -9 is the greatest mulitiple less than -7, so 2 is the answer (-7- -9, or -7+9)

Upvotes: 1

ioreskovic
ioreskovic

Reputation: 5699

Imagine a number wheel with elements {0, 1, 2} going clockwise.

You start at 0, and move 7 places counter-clockwise because you have -7 (If you had +5 mod 3, you'd move 5 places clockwise).

So, let's see where does that take us:

Current Number:  0 -1 -2 -3 -4 -5 -6 -7
Wheel Number:    0  2  1  0  2  1  0  2

Upvotes: 1

Amber
Amber

Reputation: 526563

Because -7 minus 2 is a multiple of 3.

More specifically, the implementation of modulus used in that case happens to choose the positive modulus. Some implementations choose the modulus with the same sign as the first operand, others always choose positive, etc.

Upvotes: 8

Related Questions