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

Time:05-28

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?

CodePudding user response:

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

CodePudding user response:

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
  • Related