Mechanics of 'x % y != 0' in C++

829 views Asked by At

Can someone please explain the under-the-hood mechanics of x % y !=0 in C++? It evaluates to 0 if there is no remainder in integer division and it evaluates to 1 if there is any remainder of any amount. I find this to be quite useful, but I'd like to understand what is taking place, as the syntax is not intuitive to me.

I discovered this in a separate thread, which I do not have permissions to comment in:

Fast ceiling of an integer division in C / C++

Thank you.

(Please forgive any formatting faux pas; this is my first go here)

3

There are 3 answers

2
Keith Thompson On BEST ANSWER

% is the integer remainder operator. For example:

  • 21 % 7 == 0
  • 22 % 7 == 1
  • 25 % 7 == 4
  • 27 % 7 == 6
  • 28 % 7 == 0

x % y != 0 is true if the integer division yields a non-zero remainder, false if it doesn't. x % y is simply that remainder; x % y != 0 tests whether that remainder is non-zero.

(Note that x % y != 0 can also be written as (x % y) != 0.)

It's slightly complicated when you consider negative operands.

0
franji1 On

The result of the expression is a Boolean (via the "not-equal-to" binary operator). So if the result of the modulus is non-zero, the full expression result is 1 (true). If the result of the modulus is zero, the full expression result is 0 (false)

1
JackV On

Well it seems your problem is the modulo operater (%). So what this operator does is give you the remainder after we divide two numbers.

EX. 5 % 2 = 1 Because when we take 5/2 in integer division we get 2 however we clearly have 1 as a remainder. Another example is 22 % 4 = 2 Because 22/4 = 5 with 2 remainder.

Now that we understand this we can clearly see that if we get a non zero number the expression x % y != 0 will return true so we have two integers that dont divide each other. If we get this as false then we get two numbers that do divide each other. So you actually have it backwards because if the integer division is successful with no remainder x % y == 0 so 0 != 0 will be false.