Medium
Power Function (Fast Exponentiation)
- Time limit
- 1 s
- Memory limit
- 128 MB
- Estimated
- 15 min
- Recursion Fundamentals
Description
Write a recursive function power(base, exponent) that computes base raised to the power exponent, where exponent is a non-negative integer.
A naive recursive multiplication (base * power(base, exponent - 1)) works but makes exponent recursive calls. Instead, use recursive fast exponentiation (divide and conquer):
power(base, 0) = 1- if
exponentis even:power(base, exponent) = power(base, exponent / 2) ^ 2 - if
exponentis odd:power(base, exponent) = power(base, exponent / 2) ^ 2 * base(using integer division forexponent / 2)
This reduces the number of recursive calls to O(log(exponent)).
Example: base = 2, exponent = 10 returns 1024.
The constraints are chosen so the true mathematical result always fits safely within a standard 64-bit/double-precision integer range.
Constraints
-20 <= base <= 20, 0 <= exponent <= 12
Sample cases
3Sample 1
Input
base = 2 exponent = 10
Expected output
1024
Sample 2
Input
base = 5 exponent = 0
Expected output
1
Skills and languages
Concepts
- Fast Exponentiation
Patterns
- Divide and Conquer
Languages
- Python 3
Solve this problem
Create a free account to write, run and submit your solution.
- Write Python or Java in the browser, with your draft saved as you type
- Run your code on the examples as often as you like
- Submit to a sandboxed judge and see exactly which case failed
- Ask the AI mentor for a hint without being handed the answer