Đề bài
Compute base to the power exponent with recursion: x⁰ = 1, and xⁿ = (x^(n/2))² for even n or x × (x^((n−1)/2))² for odd n. This uses far fewer multiplications than a simple loop.
Implement recursive_power(base, exponent).
Input
base: The base. exponent: The exponent (zero or positive).
Output
Return base raised to exponent.
Ràng buộc
-10 ≤ base ≤ 10; 0 ≤ exponent ≤ 18
Ví dụ
Đầu vào:
base = 3
exponent = 5
Kết quả mong đợi:
expected = 243
Đầu vào:
long long base = 3;
long long exponent = 5;
Kết quả mong đợi:
long long expected = 243;
Đầu vào:
long base = 3;
long exponent = 5;
Kết quả mong đợi:
long expected = 243;
Giải thích
3⁵ = 3 × (3²)² = 3 × 81 = 243.
Đầu vào:
base = 7
exponent = 0
Kết quả mong đợi:
expected = 1
Đầu vào:
long long base = 7;
long long exponent = 0;
Kết quả mong đợi:
long long expected = 1;
Đầu vào:
long base = 7;
long exponent = 0;
Kết quả mong đợi:
long expected = 1;
Giải thích
The base case: anything to the power 0 is 1.
Hướng tiếp cận
Hãy tự thử trước, sau đó mở từng gợi ý một.
Gợi ý 1
Use the exponent’s parity to shrink the problem size quickly.
Gợi ý 2
Recursive squaring avoids repeating work and cuts the number of multiplications drastically.
Gợi ý 3
Be careful with the zero exponent and the base case for tiny exponents.
Độ phức tạp mong đợi
O(log exponent) time, O(log exponent) extra space
Tham khảo
Thử thách này đã được điều chỉnh cho CodeUtility. Hãy làm theo đề bài và các ràng buộc ở trên.