~/problems / Number theory / Modular arithmetic

Pow(x, n)

easy ~15 min

Write my_pow(x: float, n: int) -> float that returns x raised to the integer power n. Don't use **, pow or math.pow: the tests can't stop you, but computing the power yourself is the point of the drill.

n can be as large as about 2·10^9 in absolute value, so multiplying x by itself n times is far too slow. Aim for O(log |n|) multiplications.

Handle negative exponents with x^(-n) = 1 / x^n (x is never 0 when n < 0). Careful in languages with fixed-width ints: negating -2^31 overflows. Python doesn't have that problem, but keep it in mind.

my_pow(3.0, 4)      # 81.0
my_pow(1.5, -2)     # 0.444444...
my_pow(-2.0, 3)     # -8.0
my_pow(7.0, 0)      # 1.0

Constraints: -100 < x < 100, -2^31 ≤ n ≤ 2^31 - 1, and the true answer lies within ±10^5 (or underflows toward 0). Answers are checked with a relative tolerance of 1e-9.

Show hint

x^n = (x^2)^(n/2) when n is even, with one extra factor of x when n is odd; halving the exponent each step gives the logarithmic count. (The same square-and-multiply loop is what computes modular powers.)

Topic: Modular arithmetic. Fast exponentiation, Fermat inverses, nCr mod p with factorial tables.

0:00
Ctrl ' run · Ctrl ↵ submit
esc