Math Fundamentals18 sections · 814 units
Open in Course

Power - The Insight (Squaring trick)

Halve the exponent

To compute x8x^8, you could multiply xx eight times. But notice: x8=(x4)2=((x2)2)2x^8 = (x^4)^2 = ((x^2)^2)^2. You only need three squaring operations instead of seven multiplications.

When nn is even, use xn=(xn/2)2x^n = (x^{n/2})^2. When nn is odd, use xn=xxn1x^n = x \cdot x^{n-1}. Each step reduces the exponent, moving toward the base case n=0n = 0 (which returns 11).

How many steps does this take? You halve nn each time (roughly), so you need O(logn)O(\log n) steps. This is exponentiation by squaring.