Let’s say we need to compute the exact value of for a large .
- Such problems occur in primality testing for cryptography
- Issues of numerical precision prevent us from using
The simplest algorithm, where we just do would perform multiplications. We can do better by observing that .
- If is even, then
- If is odd, then
In either case, we have halved the size of our exponent, at the cost of 2 multiplications at most. Thus, multiplications suffice to compute the final value.
In Python:
def power(a,n):
if n == 0:
return 1
x = power(a, n // 2) # Floor division
if n % 2 == 0: # n is even
return x**2
else: # n is odd
return a * x**2
This simple algorithm illustrates an important principle of divide and conquer. When is not a power of two, the problem cannot always be divided perfectly evenly, but a difference of one element between the two sides as shown here cannot cause any serious imbalance.