The 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 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 and the exponent value is , we represent this as follows:
The following illustration demonstrates this concept further.
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 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 recursive, since it makes a recursive call to itself.
In recursion, the final solution comprises the solutions to its subtasks.
For example:
...