Math Fundamentals18 sections · 814 units
Open in Course

Power Modulo - Algorithm

Iterative approach

Instead of recursion, you can use an iterative approach. Start with result=1result = 1 and process each bit of nn from right to left.

If the current bit is 1, multiply resultresult by the current power of xx. Then square xx and move to the next bit.

This works because any exponent nn can be written in binary. For example, 13=8+4+1=23+22+2013 = 8 + 4 + 1 = 2^3 + 2^2 + 2^0, so x13=x8×x4×x1x^{13} = x^8 \times x^4 \times x^1.