In this tutorial, we will be computing a
raised to the power n
in a few different ways. Let’s look at one method after another step by step.
Also read: Python pow() method
Method 1: Basic Approach
The very basic method to compute a^n
is to multiply the number a, n times again and again. This approach is pretty slow and not at all efficient.
Still, the code for the approach is mentioned below.
def basic_approach(a,n):
ans = 1
for i in range(n):
ans *= a
return ans
print(basic_approach(2,5))
The output we receive from the code mentioned above is 32 which is the correct output. Now let’s move to the next approach.
Method 2: Normal Recursive Approach
We will be approaching this method through Recursion. If you want to know more about Recursion you can read the tutorial mentioned below.
Read more about Recursion: Recursion in Python
Here the basic concept is that fun(a,n) = a * fun(a,n-1). So recursion can be used for computing a raised to the power n.
The code is mentioned below. Comments are added for your reference.
def normal_recursion(a,n):
# If power is 0 : a^0 = 1
if(n==0):
return 1
# If power is 1 : a^1 = a
elif(n==1):
return a
# For n>=2 : a^n = a* (a^(n-1))
term = normal_recursion(a,n-1)
term = a * term
# Return the answer
return term
print(normal_recursion(2,5))
The output we received from the code above is 32 which is the accurate and correct output. Let’s move to the next approach which uses recursion only but in a better way.
Method 3: Fast Recursive Approach
Earlier we used a linear recursive approach but to compute a raise to the power of n can also be computed on the basis of the value of n ( power value).
- If n is even then fun(a,n) = [ fun(a,n/2) ] ^ 2
- If n is odd then fun(a,n) = a * ( [ fun(a,n/2) ] ^ 2)
This will be a more efficient approach and will reduce the time taken by the program to a great extent. The code of the same approach is mentioned below.
def fast_recursion(a,n):
# If power is 0 : a^0 = 1
if(n==0):
return 1
# If power is 1 : a^1 = a
elif(n==1):
return a
# For n>=2 : n can be even or odd
# If n is even : a^n = (a^(n/2))^2
# if n is odd : a^n = a * ((a^(n/2))^2)
# In both the cases we have the calculate the n/2 term
term = fast_recursion(a,int(n/2))
term *= term
# Now lets check if n is even or odd
if(n%2==0):
return term
else:
return a*term
print(fast_recursion(2,5))
The output of this code is 32 as well which is correct. This approach takes up half of the time when compared to the previous approaches.
Conclusion
So in this tutorial, we learned how to compute a raised to the power n using various methods some involving recursion and some not. You can go ahead with any of the methods but it’s always better to go for the most efficient one.
Thank you for reading! Happy coding! 👩💻