Example 1
- Input
- x = 2.00000, n = 10
- Output
- 1024.00000
Multiplying 2 by itself ten times yields 1024.
Compute x raised to the integer power n, handling negative exponents through reciprocals and full 32-bit exponents with only logarithmically many multiplications.
Implement pow(x, n): raise the base x to the integer power n and return the result as a floating-point number.
The exponent may be negative, meaning the reciprocal (so ), and n can stretch across the whole 32-bit range, where multiplying x by itself n times is far too slow. Note that negating the smallest 32-bit value overflows it, so widen n before flipping its sign.
n is an integer.x is nonzero or n is positive.Multiplying 2 by itself ten times yields 1024.
Three factors of 2.1 give . Floating-point arithmetic may return a nearby representation.
A negative exponent uses the reciprocal: .
Zero factors form the empty product, one. Neither loop performs any multiplication.
After reciprocating the base, the positive magnitude 2147483648 is even. An even number of factors of -1 gives 1; Java must widen before negating the exponent.
Exponentiation counts equal factors. Example 1 asks for ten factors of 2, but we can form powers 2, 4, 16 and 256 by repeatedly squaring. Since ten equals eight plus two, multiplying 256 by 4 produces 1024. A negative exponent changes the base to its reciprocal first; exponent zero uses the empty product, one.
Reveal Repeated Multiply: intuition, complexity, and code
Halving the exponent while squaring the base converts linear repeated work into logarithmic work, the same idea behind fast modular exponentiation.