133k views
1 vote
This problem considers several ways to compute xn for some n >= 0.

(a) Write an iterative function power1 to compute xn for n >= 0.
(b) Write a recursive function power2 to compute xn by using the following recursive formulation:
x0 = 1
xn = x * xn-1 if n > 0
(c) Write a recursive function power3 to compute xn by using the following recursive formulation:
x0 = 1
xn = (xn/2)2 if n > 0 and n is even
xn = x * (xn/2)2 if n > 0 and n is odd

User Marcgg
by
8.2k points

1 Answer

3 votes

Final answer:

The question involves writing iterative and recursive functions to compute the power of a number xn for n ≥ 0. Functions have been provided for an iterative approach (power1), a simple recursive approach (power2), and an optimized recursive approach using squaring (power3).

Step-by-step explanation:

Iterative and Recursive Functions to Compute xn

To compute xn for n ≥ 0, there are different approaches one can take programmatically. Below are iterative and recursive solutions to calculate the power of a number.

Part A: Iterative Function (power1)

An iterative function to compute xn can be written as follows:

def power1(x, n):
result = 1
for i in range(n):
result *= x
return result

This function uses a loop that multiplies the base x to the result for n times.

Part B: Recursive Function (power2)

A recursive function to compute xn using the given formulation is:

def power2(x, n):
if n == 0:
return 1
else:
return x * power2(x, n-1)

This is a direct implementation of the recursive formula provided where the function calls itself with a decremented value of n until n is zero.

Part C: Recursive Function Optimized (power3)

The following is a more optimized recursive function which uses the fact that powers can be reduced by squaring the number when the exponent is even:

def power3(x, n):
if n == 0:
return 1
elif n % 2 == 0:
half_power = power3(x, n // 2)
return half_power * half_power
else:
half_power = power3(x, (n-1) // 2)
return x * half_power * half_power

This function checks if n is even or odd and applies the recursive formulation accordingly to reduce the number of multiplications required, which can be vastly more efficient, especially for large values of n.

User Fourat Ben Driaa
by
9.1k points