Power Calculator - Problem

Calculate the result of raising a base to an exponent using a loop (no built-in power function). Your solution must handle both positive and negative exponents.

For positive exponents, multiply the base by itself exponent times. For negative exponents, calculate the positive power first, then return 1.0 / result.

Note: Return the result as a floating-point number to handle negative exponents properly.

Input & Output

Example 1 — Positive Exponent
$ Input: base = 2, exponent = 3
Output: 8.0
💡 Note: 2^3 = 2 × 2 × 2 = 8
Example 2 — Negative Exponent
$ Input: base = 2, exponent = -3
Output: 0.125
💡 Note: 2^(-3) = 1/(2^3) = 1/8 = 0.125
Example 3 — Zero Exponent
$ Input: base = 5, exponent = 0
Output: 1.0
💡 Note: Any number raised to power 0 equals 1

Constraints

  • -100 ≤ base ≤ 100
  • -30 ≤ exponent ≤ 30
  • base ≠ 0 when exponent < 0

Visualization

Tap to expand
INPUTALGORITHMRESULT2base3exponentCalculate: 2^31Initialize result = 1.02Loop 3 times: result *= base (2)31.0 → 2.0 → 4.0 → 8.04Return result (positive exp)8.02³ = 8Floating-point resultKey Insight:A simple loop multiplying base by itself exponent times gives us the power, handling negatives with reciprocals.TutorialsPoint - Power Calculator | Iterative Multiplication
Asked in
Microsoft 15 Apple 12 Facebook 8
23.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen