Home > Enterprise >  How can i calculate and print the sum of first N elements of below sequence using recursive function
How can i calculate and print the sum of first N elements of below sequence using recursive function

Time:12-11

How can i calculate and print the sum of first N elements of below sequence using recursive function

Example: Sample Input N: 4

Sample Output: 7 12 17 22 = 48

I did did some part of the code but it gives wrong result and i dont know where im making mistakes. Thats why i need help!

def recur_sum(n):
  if n <= 1:
      return n
  else:
      for i in range(7,n 1):
          return i   recur_sum(i-1)
      

num = int(input("Enter a number: "))

if num < 0:
  print("Enter a positive number")
else:
  print("The sum is",recur_sum(num))

CodePudding user response:

As far as I understand your question, you want the sum of a sequence which each element of this sequence is increased by a step (such as 5), and it has an initial value (like 7), and you want the sum of first N (like 4) elements of this sequence.

At each recursion level, we add the current value to step , but when n == 1 we only return the current value (which is the Nth item of the sequence).

Do this:

def recur_sum(cur_val, step, n):
    if n == 1:
        return cur_val
    return cur_val   recur_sum(cur_val step,step,n-1)
      

num = int(input("Enter a number: "))
init_val = 7
step = 5

if num < 0:
  print("Enter a positive number")
else:
  print("The sum is",recur_sum(init_val, step, num))

Output:

The sum is 58

CodePudding user response:

this returns a list of all sequential numbers starting at 7 each increment of 5. sum the return array.... change 5 and 2 to change increments for desired jumps/steps, and change the initial return value..

def recur_sum(n):
    if n == 1:
        return [7]
    else:
        return [5*n 2]   recur_sum(n-1) 

num = int(input("Enter a number: "))

res = recur_sum(num)
print(sum(res))
  • Related