Tutorialspoint
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
Variables and Data TypesFunctions / MethodsHCL TechnologiesDropbox
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 (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.

Steps to solve by this approach:

 Step 1: Handle edge cases: n = 0 returns 1, x = 0 returns 0.
 Step 2: Handle special case for Integer.MIN_VALUE to avoid overflow when converting to positive.
 Step 3: For negative exponents, convert n to positive and x to 1/x.
 Step 4: Use binary exponentiation to calculate x^n efficiently.
 Step 5: For each recursive step, compute half = x^(n/2).
 Step 6: If n is even, return half * half; if n is odd, return x * half * half.
 Step 7: The recursive approach has O(log n) time complexity.

Submitted Code :