Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't Mod Zero?

Why is X % 0 an invalid expression?

I always thought X % 0 should equal X. Since you can't divide by zero, shouldn't the answer naturally be the remainder, X (everything left over)?

like image 676
Dasaru Avatar asked Sep 10 '11 06:09

Dasaru


4 Answers

The C++ Standard(2003) says in §5.6/4,

[...] If the second operand of / or % is zero the behavior is undefined; [...]

That is, following expressions invoke undefined-behavior(UB):

X / 0; //UB
X % 0; //UB

Note also that -5 % 2 is NOT equal to -(5 % 2) (as Petar seems to suggest in his comment to his answer). It's implementation-defined. The spec says (§5.6/4),

[...] If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined.

like image 73
Nawaz Avatar answered Oct 19 '22 06:10

Nawaz


This answer is not for the mathematician. This answer attempts to give motivation (at the cost of mathematical precision).

Mathematicians: See here.

Programmers: Remember that division by 0 is undefined. Therefore, mod, which relies on division, is also undefined.


This represents division for positive X and D; it's made up of the integral part and fractional part:

(X / D) =   integer    +  fraction
        = floor(X / D) + (X % D) / D

Rearranging, you get:

(X % D) = D * (X / D) - D * floor(X / D)

Substituting 0 for D:

(X % 0) = 0 * (X / 0) - 0 * floor(X / 0)

Since division by 0 is undefined:

(X % 0) = 0 * undefined - 0 * floor(undefined)
        = undefined - undefined
        = undefined
like image 39
Mateen Ulhaq Avatar answered Oct 19 '22 08:10

Mateen Ulhaq


X % D is by definition a number 0 <= R < D, such that there exists Q so that

X = D*Q + R

So if D = 0, no such number can exists (because 0 <= R < 0)

like image 6
Petar Ivanov Avatar answered Oct 19 '22 07:10

Petar Ivanov


I think because to get the remainder of X % 0 you need to first calculate X / 0 which yields infinity, and trying to calculate the remainder of infinity is not really possible.

However, the best solution in line with your thinking would be to do something like this

REMAIN = Y ? X % Y : X
like image 2
Billy Moon Avatar answered Oct 19 '22 06:10

Billy Moon