AlgoInsight

DSA problem

Pow(x, n)

MediumRecursionPattern: Recursiontop300AmazonGoogleMicrosoftAppleBloombergMeta

Implement pow(x, n), which calculates x raised to the power n (i.e., x^n). You may not use built-in exponentiation routines (such as Math.pow or the ** operator). The exponent n can be negative, in which case the result is 1 / x^|n|.

The naive approach multiplies x by itself |n| times in a loop, which takes O(n) time. For an exponent like n = 10^9 this is prohibitively slow. We need a way to amplify each multiplication so that the work scales with the number of bits in n rather than its magnitude.

The classic trick is exponentiation by squaring. Notice that x^n = (x^(n/2))^2 when n is even, and x^n = x * (x^(n/2))^2 when n is odd. Each recursive call halves the exponent, so the recursion depth is O(log n).

Two edge cases deserve care. First, when n is negative, we compute 1 / pow(x, -n); the only subtlety is that -Integer.MIN_VALUE overflows a 32-bit int, so Java and C++ should cast n to a 64-bit long before negation. Second, when n == 0 the answer is unconditionally 1. With those handled, the algorithm runs in O(log n) time using O(log n) recursion-stack space.

Examples

Example 1
Input: x = 2.00000, n = 10
Output: 1024.00000
Explanation: 2^10 = 1024. Exponentiation by squaring computes 2^5 = 32 first, then squares it to 1024 with only a handful of multiplications.
Example 2
Input: x = 2.10000, n = 3
Output: 9.26100
Explanation: 2.1 * 2.1 * 2.1 = 9.261. The recursion computes (2.1)^1 squared, then multiplies once more for the odd exponent.
Example 3
Input: x = 2.00000, n = -2
Output: 0.25000
Explanation: For negative exponents the result is 1 / x^|n| = 1 / 4 = 0.25. The recursion is applied to the positive exponent and the reciprocal is taken at the end.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

recursionmathdivide-and-conquerfast-power

Browse all DSA problems