Archive
The modulo operation is not that trivial
Surprise
In Python, -1977 % 100 = 23. In JavaScript, -1977 % 100 = -77. WTF?
Explanation
Modulo in different languages has different meaning! It’s not like the plus (+) operator which means the same thing in every language when applied for two integers, for instance.
In Python:
a % b = a - (b * floor(a / b))
In JavaScript:
a % b = a - (b * truncate(a / b))
For example, if a = -1977 and b = 100, then a / b is -19.77. But! floor(-19.77) is -20, while truncate(-19.77) is -19. Hence the difference!
I tested some languages and got the following result:
Group 1 (languages using floor()): Python, Lua
Group 2 (languages using truncate()): C, C++, D, Java, JavaScript, C#, Go, Rust, Nim, Kotlin, Pascal, Swift
Some more examples in Python and in JavaScript
Python:
>>> 1977 % 100
77
>>> -1977 % 100
23
>>> 1977 % -100
-23
>>> -1977 % -100
-77
JavaScript:
> 1977 % 100
77
> -1977 % 100
-77
> 1977 % -100
77
> -1977 % -100
-77
How to imitate Python?
How to have a Python-like modulo in other languages? Here is a C function:
int modulo(const int a, const int b)
{
return ((a % b) + b) % b;
}