LC 50 — Problem

Implement pow(x, n), which calculates x raised to the power n (i.e., x^n).

Input: x = 2.00000, n = 10
Output: 1024.00000
Input: x = 2.10000, n = 3
Output: 9.26100
Input: x = 2.00000, n = -2
Output: 0.25000
Explanation: 2^(-2) = 1/2^2 = 1/4 = 0.25

Constraints: -100.0 < x < 100.0 · -2³¹ ≤ n ≤ 2³¹ - 1 · n is an integer

Computing x^n the obvious way means multiplying x by itself n times. How bad does that get? Drag the slider and find out.

FIG. 1 — A BILLION VS THIRTY
n
n = 1n = 1n = 1B
Naive1multiplications
Fast1multiplications
— drag to watch the race —

Drag the slider to large exponents to feel the gap.