Fast exponentiation in C: solved exercise
Fast exponentiation in C: solved exercise
If you searched for a solved fast exponentiation exercise in C, here is binary exponentiation: it computes base^exp in O(log n) multiplications instead of O(n), halving the exponent at each step.
This algorithm is the backbone of modular arithmetic in cryptography (base^exp mod m) and of matrix exponentiation in O(n³ log k).
Problem statement
Implement:
fast_pow(base, exp): iterative version returningbase^expaslong long.fast_pow_mod(base, exp, mod): modular version to avoid overflow.recursive_pow(base, exp): equivalent recursive version.
C solution
Expected output
Common mistakes
- Squaring
basebefore checking whether the exponent is odd: the result can overflow unnecessarily if the modulus is not applied. - Not reducing
base %= modat the start of the modular version: ifbasealready exceedsmod, the first square can overflowlong long. - Confusing
exp & 1withexp % 2: they are equivalent for positive integers, but& 1is clearer in a bit-manipulation context. - Forgetting the base case
exp == 0: any number raised to 0 is 1, including 0^0, which is defined as 1 in combinatorics and algorithms.
Practical use
Fast exponentiation is essential in cryptography (RSA: m^e mod n), in Miller–Rabin primality testing, and in matrix exponentiation for linear recurrences. In competitive programming it is a standard tool for large-modulus problems.
Recommended next exercise
- Fibonacci in C: solved exercise
- Euclidean algorithm (GCD) in C: solved exercise
- Sieve of Eratosthenes in C: solved exercise
- All C exercises
Guided practice and full book
If you want a complete path with progressive difficulty:
FAQ
Why is fast exponentiation O(log n) and not O(n)?
Because in each iteration the exponent is halved (exp >>= 1). To compute 2^1000, only about 10 iterations are needed (log₂ 1000 ≈ 10) instead of 1000. The number of multiplications is proportional to the number of bits in the exponent.
What is the modular version and when is it used?
The modular version computes base^exp mod m by applying % mod at each step to keep values small and avoid overflow. It is used when working with very large numbers in cryptography or number theory, where only the remainder matters.
Does fast exponentiation work with negative exponents?
Not directly with integers: base^(-n) = 1/base^n requires fractional arithmetic. For the modular case, the modular inverse of base^n mod p can be computed as base^(p-2) mod p when p is prime (Fermat’s little theorem).