Ctrl K

Fast Exponentiation

Medium
You are given a real number base and an integer exponent. Return base raised to the power exponent. The exponent may be negative, in which case the result is one divided by base to the power |exponent|. Do not use built-in exponentiation. The exponent can be around two billion, so multiplying |exponent| times will be too slow. Answers within a relative error of 10⁻⁵ are accepted.
Example 1
base=3.0, exponent=4 → 81.0

3 · 3 · 3 · 3 = 81.

Example 2
base=-2.0, exponent=-3 → -0.125

(−2)⁻³ = 1 / (−2)³ = 1 / (−8) = −0.125.

Example 3
base=0.5, exponent=-2 → 4.0
Constraints
  • -100 < base < 100
  • -2³¹ ≤ exponent ≤ 2³¹ − 1
  • If base = 0, then exponent > 0
  • -10⁴ ≤ base^exponent ≤ 10⁴
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsAdding Digit Lists MediumEvery Bracketing Result MediumLast One After the Sweeps MediumDuel for the End Cards MediumDoubling Rows of Bits Medium
loading Python…
Input
base=3.0, exponent=4
Expected
81.0

Run checks the first 3 tests in your browser. Submit checks all 66 tests on the server, hidden ones included.