Home > Mobile >  Repeatedly adding digits of a number until the output has a single digit
Repeatedly adding digits of a number until the output has a single digit

Time:01-06

I have a two digits number (e.g. 29) ) and wish to further reduce it to a single digit. How can I do such in python? Shall I use the function inside the while loop ? e.g.

29 -> 11 -> 2

result: [29,11,2]

x=input('Input digit: ')

result=0

box=[]


def add_two(x):
    bz=[]
    for i in str(x):
        bz.append(int(i))
        s=sum(bz)
        
    return s


box=[]    
a=0

while len(str(x))>1:

CodePudding user response:

import math

dob_d = 29
while not (0 <= dob_d <= 9):
    n = 0
    for i in range(math.ceil(math.log10(dob_d))):
        n  = int(dob_d / (10 ** i) % 10)
    dob_d = n

print(dob_d)

CodePudding user response:

IIUC, you want to reduce a two digit number (29) into a single digit number by performing addition of the tens and units, repeatedly until the number is smaller than 10.

NB. I am using integers here, if you start from a string, first convert to int: x = int(x)

Let's use divmod by 10 to get the two components:

divmod(29, 10)
# 2, 9

and sum them:

sum(divmod(29, 10))
# 11

Now that we have the logic, let's repeat it:

x = 29
def reduce(x):
    return sum(divmod(x,10))

while x>9:
    x = reduce(x)
    
print(x)
# 2   # 2 9 -> 11 ; 1 1 -> 2
as a single function
def reduce_until(x):
    while x>9:
        x = sum(divmod(x,10))
    return x

reduce_until(29)
# 2
generic function for an input of any size:
def reduce_until(x):
    while x>9:
        total = 0
        while x>0:
            x,r = divmod(x, 10)
            total  = r
        x = total
    return x

reduce_until(56789)
# 56789 -> 35 -> 8

reduce_until(99999999999992)
# 99999999999992 -> 119 -> 11 -> 2
  •  Tags:  
  • Related