Recursive function that returns the sum of the divisors of a number

Asked

Viewed 515 times

0

As an exercise I had to create a recursive function that returns the sum of the divisors of a number.

I made the following code, but is giving maximum recursion error:

def somadiv(n, i = 1, s= 0):
   if i <= n:
       return somadiv(s)
   else:
       if n%i==0:
           return somadiv(s+i)
       else:
           return somadiv(i+1)

print(somadiv(8))

I tried this code too, but now it returns None:

def somadiv(n, i = 1, s= 0):
   if n == i:
        return somadiv(i)
    else:
        if n < i:
            if n%i==0:
                return somadiv(i+1, s+i)
print(somadiv(8))

Now ta giving wrong result ta returning the number before n

def somadiv(n, i = 1, s = 0):
    if n == i:
        return s
    else:
        if n < i:
            if n%i==0:
                return somadiv(n,i+1, s+i)
            else:
                return somadiv(n,i+1,s)


print(somadiv(8))
  • To avoid long discussions in the comments; the conversation was moved to the chat and may continue there in the event of new doubts/pending

1 answer

0

Final solution

def somadiv(n, i = 1, s = 0):
    if n == i:
        return s+i
    else:
        if i <= n:
            if n%i==0:
                return somadiv(n,i+1, s+i)
            else:
                return somadiv(n,i+1,s)


print(somadiv(8))
  • When I edited once, they said I couldn’t, because I would change the question.

  • From what I understand this is an answer, because it is working - missed to put an explanatory text, saying what solved and how did to find out

  • @nosklo The first version of this reply was not, see the edit history

Browser other questions tagged

You are not signed in. Login or sign up in order to post.