Search code examples
c++modulusinteger-division

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


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)


Solution

  • % 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.