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 do I do sum_of_digits recursively for large numbers

Currently, I have written a recursive function to do sum_of_digits but it works for smaller numbers, e.g. Less than 6.

But for larger numbers, the calculation messes up for some reason.

def sum_of_digits(i):
    if i == 0 :
        return i
    else:
        return i % 10 + sum_of_digits(i / 10)

sum_of_digits(228475) 
# returns 31.111111111111107 
# should be returning 28 instead

What am I doing wrong here?

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

>Solution :

You should use "integer division (operator //)" instead of normal division (operator /) in the 5th line.

...
        return i % 10 + sum_of_digits(i // 10)
...

Integer division return the largest integer smaller than the result of normal division.
For example,

5/2 = 2.5  =>  5//2 = 2
-5/2 = -2.5  =>  -5//2 = -3
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