Give a recursive algorithm to compute the sum of the cubes of the first n positive integers. The input to the algorithm is a positive integer n. The output is ∑j=1nj3. The algorithm should be recursive, it should not compute the sum using a closed form expression or a loop.

Respuesta :

Answer:

def sum_cubes(n):

   if n == 1:

       return 1

   else:

       return n * n * n + sum_cubes(n-1)

print(sum_cubes(3))

Explanation:

Create a function called sum_cubes that takes one parameter, n

If n is equal to 1, return 1. Otherwise, calculate the cube of n, and add it to the sum_cubes function with parameter n-1

If we want to calculate the cubes of the first 3 numbers:

sum_cubes(3) = 3*3*3 + sum_cubes(2)

sum_cubes(2) = 2*2*2 + sum_cubes(1)

sum_cubes(1) = 1

If you substitute the values from the bottom, you get 27+8+1 = 36

fichoh

Recursive algorithms are programs which calls its self within a function. The recursive program which computes the sum of cubes of the first n positive integers written in python 3 goes thus :

def cube_sum(n) :

#initialize a function called cube sum which takes a single parameter

if n == 1:

#checks of the value of n is 1

return 1

# return 1 if it is and the function terminates

else :

#if otherwise

return n**3 + cube_sum(n-1)

#take the cube of n and add the value of the function again, this time, with n being the initial value - 1 ; this repeats until the value of n ==1.

Sample run :

print(cube_sum(5))

Learn more : https://brainly.com/question/13246781?referrer=searchResults

Ver imagen fichoh