The modulo operator returns the remainder of a division. But things get a little more tricky when you throw negative numbers into the mix.      259

Modulo of Negative Numbers

submited by
Style Pass
2023-01-25 09:30:06

The modulo operator returns the remainder of a division. But things get a little more tricky when you throw negative numbers into the mix. 259

The modulo or often referred to as “mod” represents the remainder of a division. In 1801 Gauss published a book covering modular arithmetics. Later a widely accepted mathematical definition was given by Donald Knuth mod(a, n) = a - n * floor(a / n)

Doing an integer division and then multiplying it again means finding the biggest number smaller than a that is dividable by n without a remainder. Subtracting this from a yields the remainder of the division and by that the modulo.

In programming, the modulo operator (% or sometimes mod) often is used to restrict an index to the bounds of an array or length limited data structure. values = [ 3, 4, 5 ] index = 5 value_at_index = values[ index % values.length ]

For the above example this means 5 mod 3 = 2 following the definition is 5 - floor(5/3)*3 = 2. This means that no matter the value index has, the array bounds are met.

Leave a Comment