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
– Bacco