The task of finding the power of a number in Python involves calculating the result of raising a base number to an exponent. For example, if we have a base 2 and an exponent 3, the result is
Using ** operator
This is the simplest and most Pythonic way to calculate the power of a number. The ** operator is internally optimized and is the preferred choice for most situations.
N, X = 2, 3
res = N ** X
print(res)
Output
8
Explanation: The expression res = N ** X is used to calculate the power of N raised to X using Python's exponentiation operator ** . This evaluates to
Table of Content
Using pow()
pow() function is another efficient built-in method. It performs the same task as **, with the added advantage of supporting modular arithmetic for advanced use cases.
N, X = 2, 3
res = pow(N, X)
print(res)
Output
8
Explanation: pow() function in res = pow(N, X) computes 2^3 =8, raising N to the power X.
Using recursion
This approach uses recursion to divide the exponent into halves and reduce the number of operations. It is an elegant solution but involves a function call stack, which increases space complexity.
def power(N, X):
if X == 0:
return 1 # base case
half = power(N, X // 2) # recursive call to get half power
if X % 2 == 0:
return half * half # if even, multiply half powers
else:
return half * half * N # if odd, multiply extra N
N, X = 2, 3 # initialize base (N) and exponent (X)
print(power(N, X))
Output
8
Explanation: This program defines a recursive function power(N, X) to calculate
Using loop
This is the most straightforward method, using a loop to multiply the base N repeatedly X times. While easy to understand, it is inefficient for large exponents.
N, X = 2, 3
P = 1 # initialize result
for i in range(X): # loop X times
P = P * N
print(P)
Output
8
Explanation: for loop runs X times (3 times), and in each iteration, P is multiplied by N. This results in 2×2×2=8.