独奏

独奏

道阻且长,行则将至

Negative number modulo

(-7)%10 = ?

There are two answers: -7 or 3

This brings us to the definition of modulo operation in programming languages.

r = a - (a / b) * b

There are two different rounding methods for division a / b, one is rounding towards 0, and the other is rounding towards negative infinity. This leads to two different results for modulo operation.

For example:

-7/10 rounded towards 0 gives a result of 0, while rounding towards negative infinity gives a result of -1. Therefore, if we use rounding towards 0, the result of -7%10 is -7, and if we use rounding towards negative infinity, the result is 3.

Different programming languages have different implementation methods, usually defaulting to rounding towards 0. Python calculates it based on rounding towards negative infinity, and some languages even provide two functions, rem and mod.

What if we really need to use rounding towards negative infinity? We can use the floor function to calculate, which rounds down. Then the modulo operation becomes:

r = a - floor(a / b) * b

References#

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.