Last Updated: February 25, 2016
·
506
· dionysios

The sign of a modulo expression

In mathematics, the remainder of Euclidean division is always positive, regardless of the sign of the dividend or the divisor. This is not the case in programming, however.

In python, the sign of the remainder is always the sign of the divisor:

print   7 % 3          # 1
print   7 % -3          # -2
print   -7 % 3          # 2
print   -7 % -3          # -1

In C++, up until C++11 it is up to the implementation. For example in clang++ 4.2, the sign of the remainder is the sign of the dividend.

std::cout <<   7 % 3   << std::endl;          //1
std::cout <<   7 % -3   << std::endl;          //1
std::cout <<   -7 % 3   << std::endl;          //-1
std::cout <<   -7 % -3   << std::endl;          //-1

C++11 defines the remainder to be always positive, following its mathematical definition.