The Power of a Number

In this lesson, we will learn how to find the power of a number using recursion.

What does “Power of a Number” mean?

The power (or exponent) aa, of a number xx represents the number of times xx will be multiplied by itself. It is written as a small, superscript number to the right of and above the base number.

For example, if the base number is 22 and the exponent value is 33, we represent this as follows:

23=82^3 = 8

The following illustration demonstrates this concept further.

Power of a number
Power of a number

To recursively code this problem, we must break it down. We multiply the number with itself in each step.

Implementation

Let’s take a look at the code:

Press + to interact
def power(base, exponent):
# Base Case
if exponent == 0 :
return 1
# Recursive Case
else :
return base * power(base, exponent - 1);
# Driver Code
print(power(2, 3))

Explanation

In the code above, the function, power(), is recursive, since it makes a recursive call to itself.

In recursion, the final solution comprises the solutions to its subtasks.

For example:

23=22 ...