Reputation: 85
I'm trying to make a function that is given the first number in an arithmetic progression, the derivation d and the number of terms in the series which is n and then calculate their sum using recursion I tried the following
def rec_sum(a_1, d, n):
if n == 0:
return 0
return (n*(a_1+rec_sum(a_1,d,n-1)))/2
print rec_sum(2,2,4)
which gives me 18 instead of 20 thanks for the help
Upvotes: 0
Views: 4273
Reputation: 756
There is a simpler way to find the sum of arithmetic progression, but if you need the recursion -
def rec_sum(first_element, step, seq_length):
if seq_length <= 0:
return 0
return first_element + rec_sum(first_element + step, step, seq_length - 1)
Upvotes: 3
Reputation: 2055
Another solution:
def rec_sum(a_1, d, n):
if n == 0:
return 0
return a_1 + rec_sum(a_1 + d, d, n-1)
print rec_sum(2, 2, 4)
output:
20
Upvotes: 1