Question

The following function finds the power of two described by the number being passed to the recursive function “double”.

def double(n):
if n == 0:
return 1
else:
return double(n - 1) + double(n - 1)
print(double(4))
Hence the result of the above code would be 24=16
. How could the code be modified to find the power of three?

(1 point)
Responses

def double(n):
if n == 0:
return 1
else:
return double(n - 1) + double(n - 1)
print(double(3))
def double(n): if n == 0: return 1 else: return double(n - 1) + double(n - 1) print(double(3))

def triple(n):
if n == 0:
return 1
else:
return triple(n - 1) + triple(n - 1)
print(triple(4))
def triple(n): if n == 0: return 1 else: return triple(n - 1) + triple(n - 1) print(triple(4))

def double(n):
if n == 0:
return 1
else:
return 3 * double(n - 1) + 3 * double(n - 1)
print(double(4))
def double(n): if n == 0: return 1 else: return 3 * double(n - 1) + 3 * double(n - 1) print(double(4))

def double(n):
if n == 0:
return 1
else:
return double(n - 1) + double(n - 1) + double(n - 1)
print(double(4))
def double(n): if n == 0: return 1 else: return double(n - 1) + double(n - 1) + double(n - 1) print(double(4))
Remaining Attempts : 3

1 answer

To modify the code in order to find the power of three instead of two, you should create a new function (or modify the existing one) such that it correctly recurses three times instead of twice. The goal is to return \(3^n\) where \(n\) is the input to the function.

Here is how you can do it:

def triple(n):
    if n == 0:
        return 1
    else:
        return triple(n - 1) + triple(n - 1) + triple(n - 1)

print(triple(4))

In this code:

  • The function triple will be called recursively three times for each non-zero n, thereby implementing \(3^n\).

So the correct modification of the existing function would be:

def triple(n):
    if n == 0:
        return 1
    else:
        return triple(n - 1) + triple(n - 1) + triple(n - 1)

print(triple(4))

This function should correctly compute \(3^4\) when called.