Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to print sum of numbers to n recursively?

I have written a function to print of sum of numbers to n.

def sumOfDigits(n):
    sum = 0
    if n < 0:
        print("Enter a positive number")
    else:
        while (n > 0):
            sum = sum + n
            n -= 1
        return sum

print(sumOfDigits(4))

Which prints the result fine but now i am trying to do it recursively.

def sumOfDigits(n):
    assert n >= 0 and int(n) == n, 'The number must be positive integer only'
    if n == 0:
        return 0
    else:
        while n > 0:
            return sumOfDigits(n) + sumOfDigits(n-1)

print(sumOfDigits(3))

But i am getting the following error :-

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

assert n>= 0 and int(n) == n, 'The number must be positive integer only'
   RecursionError: maximum recursion depth exceeded in comparison

Any help will be appreciated. Thank you.

>Solution :

In recursion, all the recursive calls must get you closer to the base case. When you call sumOfDigits(n), it just repeats the same value, so it recurses infinitely.

You just need to add the current value to the recursive result, not two recursive calls. So the line

return sumOfDigits(n) + sumOfDigits(n-1)

should just be

return n + sumOfDigits(n-1)

You also don’t need a while loop. The recursion is the loop.

def sumOfDigits(n):
    assert n >= 0 and int(n) == n, 'The number must be positive integer only'
    if n == 0:
        return 0
    else:
        return n + sumOfDigits(n-1)

Your while loop is infinite because it never changes n.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading