Fast Exponentiation
Fast exponentiation
The traditional method for computing takes time, while fast exponentiation takes .
For , four reductions bring the exponent down to 1:
Fast exponentiation
C
#include <stdio.h>
long long fast_exponentiation(long long x, long long n) {
if (n == 0) {
return 1;
}
long long half;
if (n % 2 == 0) {
half = fast_exponentiation(x, n / 2);
return half * half;
} else {
half = fast_exponentiation(x, (n - 1) / 2);
return half * half * x;
}
}
int main() {
printf("%lld\n", fast_exponentiation(2, 18));
return 0;
}INTERACTIVE LAB
Fast exponentiation: one call, reused twice
ACCESSPRO
PRO EXCLUSIVEGo further with Pro
Unlock Pro accessUnlock the complete interactive lab, deeper explanations, and curated reference answers.
KNOWLEDGE QUIZ
QUESTION
Why save half before returning half * half?
KNOWLEDGE QUIZ
QUESTION
For x¹³, half = x⁶. How should the result combine?
KNOWLEDGE QUIZ
QUESTION
What does the sample return when n reaches zero?
HANDS-ON PRACTICE
Trace 3 to the thirteenth power
Use the sample algorithm to compute 3¹³, with nonnegative exponents and the n=0 base case returning 1.
- List the exponents on the recursive descent.
- On the unwind, record n, half, the even/odd branch, and the return value.
- Explain why half is computed only once at each level.