I need to work out a very large power modulo (2^32), i.e. I want the result of:
y = (p^n) mod (2^32)
p is a prime number
n is a large integer
Is there a trick to doing this efficiently in Java?
Or am I stuck with doing it in a loop with n iterations?
The simple way to mod 2^32 is to use
& 0xFFFFFFFFL. Also, there happens to be a type which naturally keeps the lowest 32-bit calledint😉 If you use that you don’t even need to perform the&until you have the result (so the answer is unsigned) For this reason you only need to keep the last 32 bit of the answer. To speed up the^nyou can calculate the square, it’s square and it’s square etc, e.g if n is 0b11111 then you need to multiply p^16 * p^8 * p^4 * p^2 * p.In short, you can use plain
intas you only need 32-bit of accuracy and values with a cost of O(ln n) wherenis the power.prints finally