This recursive function calculates the nth power of 2 by using the formula 2^n. It takes in a single parameter, n, which represents the exponent.
The function starts with a base case that checks if n is equal to 0. If n is 0, then the function returns 1 as any number raised to the power of 0 is always 1.
If n is not 0, then the function recursively calls itself with n - 1 as the argument. This means that the function will calculate the (n-1)th power of 2 and multiply it by 2 to get the nth power of 2.
The function keeps recursively calling itself with decreasing values of n until it reaches the base case (n = 0). The function then starts returning the calculated values back in reverse order until it ultimately returns the final result for the original value of n.
The following recursive function will print the nth power of 2.
def powerOf2(n):
if n == 0:
return 1
else:
return (2 * powerOf2(n - 1))
1 answer