Modulo operator with negative values

C++

C++ Problem Overview


Why do such operations:

std::cout << (-7 % 3) << std::endl;
std::cout << (7 % -3) << std::endl;

give different results?

-1
1

C++ Solutions


Solution 1 - C++

From ISO14882:2011(e) 5.6-4:

> The binary / operator yields the quotient, and the binary % operator > yields the remainder from the division of the first expression by the > second. If the second operand of / or % is zero the behavior is > undefined. For integral operands the / operator yields the algebraic quotient with any fractional part discarded; if the quotient a/b is > representable in the type of the result, (a/b)*b + a%b is equal to a.

The rest is basic math:

(-7/3) => -2
-2 * 3 => -6
so a%b => -1

(7/-3) => -2
-2 * -3 => 6
so a%b => 1

Note that

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

from ISO14882:2003(e) is no longer present in ISO14882:2011(e)

Solution 2 - C++

a % b

in c++ default:

(-7/3) => -2
-2 * 3 => -6
so a%b => -1

(7/-3) => -2
-2 * -3 => 6
so a%b => 1

in python:

-7 % 3 => 2
7 % -3 => -2

in c++ to python:

(b + (a%b)) % b

Solution 3 - C++

The sign in such cases (i.e when one or both operands are negative) is implementation-defined. The spec says in §5.6/4 (C++03),

>The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined; otherwise (a/b)*b + a%b is equal to a. If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined.

That is all the language has to say, as far as C++03 is concerned.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionscdmbView Question on Stackoverflow
Solution 1 - C++PlasmaHHView Answer on Stackoverflow
Solution 2 - C++Kto ToView Answer on Stackoverflow
Solution 3 - C++NawazView Answer on Stackoverflow