Power of a Number
In this lesson, we will learn how to find the power of a number using recursion.
We'll cover the following
What does “Power of a Number” mean?
The power (or exponent) , of a number represents the number of times 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 and the exponent value is , we represent this as follows:
The following illustration explains the concept.
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:
def power(base, exponent):# Base Caseif exponent == 0 :return 1# Recursive Caseelse :return base * power(base, exponent - 1);# Driver Codeprint(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:
Therefore we can generalize this as follows:
.
.
This can then be mapped as a recursive function. The last condition will be our base case. While all the rest can be written in the generic format:
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.