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 needs to be multiplied by itself. It is written as a small number to the right 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 explains the concept.

Power of a number
Power of a number

To code this problem recursively we need to break it down. In each step, we are multiplying the number with itself.

Implementation

Let’s have 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 a recursive function as it makes a recursive call to another instance of itself.

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

For example:

23=2222^3 = 2 * 2^2

23=2(221)2^3 = 2 * (2 * 2^1)

Therefore we can generalize this as follows:

xa=x(x)a1x^a = x * (x)^{a-1}

(x)a1=x(x)a2(x)^{a-1} = x * (x)^{a-2}

(x)a2=x(x)a3(x)^{a-2} = x * (x)^{a-3}

.

.

(x)aa=1(x)^{a-a} = 1

This can then be mapped as a recursive function. The last condition (x)aa=(x)0=1(x)^{a-a} = (x)^{0} = 1 will be our base case. While all the rest can be written in the generic format: xa=x(x)a1x^a = x * (x)^{a-1}

Let’s have a look at an illustration to better visualize what is going on in the code.


In the next lesson, we will have a look at another example of solving problem with recursion.