
Problem
Solution
Submissions
pow(x, n) efficiently (calculate x raised to power n)
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 10
Write a C# program to implement the pow(x, n) function, which calculates x raised to the power n (i.e., xⁿ). Your implementation should be efficient with a logarithmic time complexity. You need to handle both positive and negative exponents as well as edge cases.
Example 1
- Input: x = 2.00000, n = 10
- Output: 1024.00000
- Explanation:
- 2^10 = 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 = 1024
Example 2
- Input: x = 2.10000, n = 3
- Output: 9.26100
- Explanation:
- 2.1^3 = 2.1 * 2.1 * 2.1 = 9.261
Constraints
- -100.0 < x < 100.0
- -2^31 ≤ n ≤ 2^31-1
- -10^4 ≤ x^n ≤ 10^4
- Time Complexity: O(log n)
- Space Complexity: O(log n) for recursive approach, O(1) for iterative approach
Editorial
My Submissions
All Solutions
| Lang | Status | Date | Code |
|---|---|---|---|
| You do not have any submissions for this problem. | |||
| User | Lang | Status | Date | Code |
|---|---|---|---|---|
| No submissions found. | ||||
Solution Hints
- Use binary exponentiation (also known as exponentiation by squaring).
- Handle negative exponents by computing 1/x^|n|.
- Be careful with edge cases such as n = 0, n = INT_MIN, x = 0.
- Use recursion or iteration to implement the binary exponentiation.
- For even powers, use x^n = (x^(n/2))^2. For odd powers, use x^n = x * (x^(n/2))^2.