I am computing sum of digits of a number recursively, until sum is less than 10. For example;
99999->45->9
Since final sum of digits is 9, then we stop. I am aware of following recursive approach which works fine, in my knowledge;
First Approach
def sumdigits(n):
if n//10==0:
return n
q,r=divmod(n,10)
return sumdigits(q+r)
But I am trying to write it using two recursive functions, in order to learn a different approach. Here is my second approach;
Second Approach
def digitalRoot(n):
def sumdigits(n):
if n==0:
return 0
q,r=divmod(n,10)
return r+sumdigits(q)
s=sumdigits(n)
if s//10==0:
return s
q,r=divmod(s,10)
return r+sumdigits(q)
As seen, I am trying to write a separate check whether sum of digit is less than 10. It is working for situations where the level of calculation is at most 2.
For example n=99999 gives the sum as 99999->45->9.
But if we have case like n=27640, the correct output she be 1, since 27640->19->10->1. But my code is stopping at second level and giving answer as 10. Can I get some help to modify my second code so as to fix the issue? Thanks in advance.
def digitalRoot(n): return n % 9.