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

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 it 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 also tried this code, 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 it is giving wrong result is returning the previous number to 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))
    
asked by anonymous 09.12.2018 / 23:46

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))
    
10.12.2018 / 00:40