Simple Modulo expression

74 views Asked by At

I understand that a mod operator finds the remainder of two numbers. However, I am having trouble understanding the concept when the numbers are reversed. Meaning, a smaller number comes first in the operation.

    int x = 4 % 3 ; // prints out 1

However, can someone explain this to me:

     int y = 1 % 4 ; //  prints out 1
     int z = 2 % 3 ; // prints out 2

Thanks in advance!

2

There are 2 answers

0
Corbac On

Are you sure about the int y that prints out 2?

The int z though seems normal : 2= 0*3 + 2

int y = 1 % 4 should print 1 because: 1=0*4 + 1

It works the same as when a bigger number comes first, you just take the remainder of the division of the first one by the second one.

0
MadConan On

Whether the left-hand side of the operator is larger than the right is irrelevant. There is always a remainder for any division operation, it's just that sometimes it's 0.

So 5 % 2 returns 1, just like 4 % 3 returns 1.

The value of any modulo operation of the form x % n will be 0 to n - 1 inclusive, for positive x. It will be -1(n-1) to 0 inclusive for negative x.