
Problem
Solution
Submissions
Power Function
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 10
Write a C program to implement the power function pow(x, n), which calculates x raised to the power n (i.e., x^n). The algorithm should handle both positive and negative exponents efficiently without using built-in power functions.
Example 1
- Input: x = 2.00000, n = 10
- Output: 1024.00000
- Explanation:
- Step 1: Calculate 2^10 using efficient exponentiation.
- Step 2: 2^10 = 1024.
- Step 3: Return 1024.00000 as the result.
- Step 1: Calculate 2^10 using efficient exponentiation.
Example 2
- Input: x = 2.10000, n = 3
- Output: 9.26100
- Explanation:
- Step 1: Calculate 2.1^3.
- Step 2: 2.1 * 2.1 * 2.1 = 9.261.
- Step 3: Return 9.26100 as the result.
- Step 1: Calculate 2.1^3.
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(1)
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 (exponentiation by squaring) for efficiency.
- Handle negative exponents by calculating 1 / pow(x, -n).
- Use the property: x^n = (x^2)^(n/2) when n is even.
- Use the property: x^n = x * x^(n-1) when n is odd.
- Handle edge cases like n = 0 (result is 1) and x = 0.