1. Negative exponent
A negative power is the reciprocal of the positive power.
if (n < 0) return 1 / fastPower(x, -n)Typorithm · medium
Step 1 of 8 · intro card
Divide & Conquer
Compute x^n in O(log n) by squaring x^(n/2), with one extra multiply for odd exponents.
Naive exponentiation multiplies x by itself n times, which is O(n).
Halving the exponent and squaring the result turns it into O(log n) multiplications.
An odd exponent needs one extra factor of x because integer division drops the remainder.
Compute x^(n/2) once, then square.
Odd n adds one extra x.
O(log n) multiplications.
function fastPower(x, n) {
if (n < 0) return 1 / fastPower(x, -n);
if (n === 0) return 1;
const half = fastPower(x, Math.floor(n / 2));
if (n % 2 === 0) {
return half * half;
}
return half * half * x;
}Connect each part of the code to the concept before you type.
A negative power is the reciprocal of the positive power.
if (n < 0) return 1 / fastPower(x, -n)Any value raised to the zero power is one.
if (n === 0) return 1Compute x to the n/2 once and reuse it.
const half = fastPower(x, Math.floor(n / 2))For even n, x^n is the square of x^(n/2).
return half * halfFor odd n, multiply one extra x to account for the dropped remainder.
return half * half * xRead the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
InputBase 2 · exponent 5
Follow temporary values, local state and supporting structures at this step.
Live recursive calls, including their arguments. Returning releases the top frame.
Local state · indices and saved values
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state