简体   繁体   中英

calculating arithmetic progression with recursion

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

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM