Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modulo operator with negative values [duplicate]

Tags:

c++

Why do such operations:

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

give different results?

-1 1 
like image 856
scdmb Avatar asked Sep 29 '11 08:09

scdmb


2 Answers

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)

like image 117
PlasmaHH Avatar answered Sep 17 '22 15:09

PlasmaHH


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 
like image 37
Kto To Avatar answered Sep 18 '22 15:09

Kto To