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:
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.