I just heard about that x mod (2^32-1) and x / (2^32-1) would be easy, but how?
to calculate the formula:
xn = (xn-1 + xn-1 / b)mod b.
For b = 2^32, its easy, x%(2^32) == x & (2^32-1); and x / (2^32) == x >> 32. (the ^ here is not XOR). How to do that when b = 2^32 – 1.
In the page https://en.wikipedia.org/wiki/Multiply-with-carry. They say “arithmetic for modulus 2^32 − 1 requires only a simple adjustment from that for 2^32“. So what is the “simple adjustment”?
(This answer only handles the
modcase.)I’ll assume that the datatype of
xis more than 32 bits (this answer will actually work with any positive integer) and that it is positive (the negative case is just-(-x mod 2^32-1)), since if it at most 32 bits, the question can be answered byWe can write
xin base 2^32, with digitsx0,x1, …,xn. SoThis makes the answer clearer when we do the modulus, since
2^32 == 1 mod 2^32-1. That isx mod 2^32-1is the same as the sum of the base 2^32 digits! (we can’t drop the mod 2^32-1 yet). We have two cases now, either the sum is between 0 and 2^32-1 or it is greater. In the former, we are done; in the later, we can just recur until we get between 0 and 2^32-1. Getting the digits in base 2^32 is fast, since we can use bitwise operations. In Python (this doesn’t handle negative numbers):(This is extremely easy to generalise to
x mod 2^n-1, in fact you just replace any occurance of 32 withnin this answer.)(EDIT: added the
elifclause to avoid an infinite loop onmod_2to32sub1(2**32-1). EDIT2: replaced^with**… oops.)