AlgoMaster Logo

Pow(x, n)

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Iterative Multiplication

Intuition:

The simplest way to calculate x^n is to multiply x by itself n times. While this approach is straightforward, it's very inefficient for large values of n due to its linear complexity. Also, handling negative powers involves taking the reciprocal of positive power results.

Code:

2. Recursive Approach with Divide and Conquer

Intuition:

The key observation is that x^n can be broken down recursively:

  • If n is even, x^n = x^(n/2) * x^(n/2)
  • If n is odd, x^n = x * x^(n//2) * x^(n//2)

This approach divides the problem size by half at each step, leading to a more efficient solution.

Code:

3. Iterative Binary Exponentiation (Optimal)

Intuition:

The iterative method of binary exponentiation is similar to the recursive method, but it avoids the overhead of recursion. We use bit manipulation to quickly determine if the current power n is odd and needs additional multiplication by x. This results in efficient exponentiation with reduced time complexity.

Code: