def digit_sum(n):
\'\'\'(int)->number
Returns the sum of all the digits in the given integer, n\'\'\'
if n<10:
return n
return n%10 + digit
def droot(a):
while a>=10:
b =int(a/10) #other digit(s)
c =a-(b*10) #the rightmost digit
a =b+c #add together
return a
I have not seen this solution anywhere, so I thought it would be nice to share, i discovered it myself! Just 1 looping structure.
Wikipedia lists a simple O(1) formula for the digital root:
def digit_root(n):
return (n - 1) % 9 + 1
This does not take into account an input less than 1, so you can modify as follows, with the assumption that the input is a whole number:
def digit_root(n):
return (n - 1) % 9 + 1 if n else 0
Examples:
>>> digit_root(1)
1
>>> digit_root(11)
2
>>> digit_root(235)
1
please try the following code:
def dgtl_rt(n):
return n%9 or n and 9
print(dgtl_rt(123))
{def MDR(n):
'''
this function returns multiplicative digital root.
'''
count, mdr = 0, n
while mdr > 9:
m, digitsMul = mdr, 1
while m:
m, md = divmod(m, 10)
digitsMul *= md
mdr = digitsMul
count += 1
return count, mdr}
Try this:
def num(n) :
sum = 0 #provided sum as 0
for i in str(n):
a = int(n) % 10 #taken variable a
sum = sum + a #put the sum.
n = n/10
print(sum)
if sum < 10:
print(str(sum) + "=this is a digital root")
else:
num(sum)
So the idea is that you have to use recursion for the last one as well? In that case, this should do the job:
def digital_root(n):
if n < 10:
return n
return digital_root(digit_sum(n))