Back to challenges
Easy 0 solved 0% acceptance

Power by Repeated Multiplication

Raise a number to a power with a loop.

What you'll learn

  • Multiply repeatedly in a loop
  • Handle an exponent of zero
  • Compare with the built-in power

Problem

Compute base to the power exponent by multiplying base by itself exponent times in a loop. Any number to the power 0 is 1.

Implement power(base, exponent).

Input

base: The base. exponent: The exponent (zero or positive).

Output

Return base raised to exponent.

Constraints

-10 ≤ base ≤ 10; 0 ≤ exponent ≤ 18

Examples

Example 1
Input:
base = 2
exponent = 10

Expected output:
expected = 1024
Input:
long long base = 2;
long long exponent = 10;

Expected output:
long long expected = 1024;
Input:
long base = 2;
long exponent = 10;

Expected output:
long expected = 1024;

Explanation

2 multiplied by itself 10 times is 1024.

Example 2
Input:
base = 5
exponent = 0

Expected output:
expected = 1
Input:
long long base = 5;
long long exponent = 0;

Expected output:
long long expected = 1;
Input:
long base = 5;
long exponent = 0;

Expected output:
long expected = 1;

Explanation

Anything to the power 0 is 1.

How to approach it

Try on your own first, then open one hint at a time.

Hint 1

The exponent tells you how many times to keep multiplying the base into an accumulating result.

Hint 2

Start from the neutral value for multiplication so the zero-exponent case works naturally.

Hint 3

Watch for the edge case where the exponent is zero, since no looping should still give a valid answer.

Expected complexity

O(exponent) time, O(1) extra space

References

This challenge is adapted for CodeUtility. Follow the statement and constraints above.

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.