data-structures · intermediate · ~15 min
Compute a power in O(log exp) by squaring.
Implement:
long long fast_pow(int base, int exp);
Return base raised to exp (exp >= 0) using recursive exponentiation by squaring. The result fits in long long.
base, exp >= 0.
base^exp.
Halve the exponent each call.
#include <stddef.h>
/* base raised to exp (exp>=0) via recursive fast exponentiation (exponentiation by squaring). Result fits long long. */
long long fast_pow(int base,int exp){ (void)base;(void)exp; return 1; }
Recomputing the recursive half twice instead of once; mishandling odd exponents.
exp==0 returns 1 for any base.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.