an unusual equivalence

Here's an interesting equation: ( x + x k 1 ) mod k = x mod ( k 1 )

It says that if you take a number x, divide it by some constant k−1, add the floored result back to x, and take the remainder mod k, that's the same as taking x mod (k−1).

Note that mod here is an operator which returns a remainder, not a clause which applies to the whole equation (as it would in modular arithmetic). And the equals operator is a true equality, not a congruence.

The interesting thing to me is that this equation relates two things with different moduli. That's unusual. Normally you're relating things with the same modulus.

We can extend it to larger gaps as well – for example, here's k−2: ( x + 2 x k 2 ) mod k = x mod ( k 2 )

Or, for arbitrary integers a and b with a ≥ b: ( x + ( a b ) x b ) mod a = x mod b

Essentially, this lets you "change the basis" of a mod operation at the cost of a division. Useful? idk. Could possibly help when analyzing nested mod expressions. Probably not useful as an optimization – not on its own, anyway, since now you're doing two divisions instead of one – but maybe there's some clever application where you combine it with a division or shift somewhere else.

Why does it work?

Well, let's look at an example. We're going to take x+⌊x/k⌋ mod k+1 and break it down into pieces. (This is our first equation but i'm using k and k+1 instead of k-1 and k. Just a variable relabeling to make the explanation sightly cleaner.)

First, let's take just the floor part, f(x) = ⌊x/k⌋. This is a stairstep function which is 0 when 0≤x<k, 1 when k≤x<2k, 2 when 2k≤x<3k, etc. For every k units in the x direction, f(x) increases by one. Here it is plotted along with f(x)=x.

[plot of x and ⌊x/k⌋]

Adding the stairstep function to x gives us f(x) = x + ⌊x/k⌋, breaking what had been a continuous line into segments of length k (in the x direction), and separated by one unit in the y direction. The "bottom" of each segment starts at a multiple of k+1.

[plot of f(x)=x+⌊x/k⌋]

Finally, taking f(x) mod k+1 removes multiples of k+1 from f(x), making the segments all align at y=0.

[plot of f(x) = x + ⌊x/k⌋ mod k+1]

Which is x mod k!