Tutorialspoint
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.
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.
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)
NumberMicrosoftKPMG
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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.

Steps to solve by this approach:

 Step 1: Handle base cases - when n is 0, x is 0, x is 1, or x is -1.
 Step 2: Convert negative exponent to positive by taking reciprocal of base and making exponent positive.
 Step 3: Use long long to handle the edge case where n is INT_MIN to avoid overflow.
 Step 4: Implement binary exponentiation by repeatedly squaring the base and halving the exponent.
 Step 5: If the current exponent is odd, multiply the result by the current power of the base.
 Step 6: Square the current power and divide the exponent by 2 in each iteration.
 Step 7: Return the final result after processing all bits of the exponent.

Submitted Code :