简体   繁体   中英

Recursive function that returns sum of all odd numbers within a range

I've been trying to create a recursive function that, as the title says, returns the value of the sum of all the odd numbers included in that range. I tried the following:

def addOdds(A,B):
    for i in range (A,B):
        if i % 2 == 0:
            return addOdds(A,B-1)
        elif i % 2 != 0:
            return (i+addOdds(A,B-1))

print(addOdds(2, 125))

with that input, my output should be 3968 but instead I'm getting None and if i print i i get 0. Any clues on what I'm doing wrong?

Since B decreases in recursion, there's no need for the for-loop. Then to ensure the recursion ends, you need to specify what to return when B becomes equal to A.

def addOdds(A,B):
    if A == B:
        return 0
    else:
        if B % 2 == 0:
            return addOdds(A, B-1)
        else:
            return B + addOdds(A, B-1)

print(addOdds(2, 125))
# 3968

Here's the python code to do this in a simple manner

def addOdds(A, B, total):  #pass the range with 0 as total Ex: 1,5,0
    if (A <= B):
        if (A % 2 != 0):  #check if A is odd
            total += A    
        return(addOdds(A+1, B, total))   #pass the new range with total Ex: 2,5,1
       
    return total


ans = addOdds(2, 125, 0)

print(ans)


output:

3968

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