Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make loop repeat until the sum is a single digit?

Tags:

python

Prompt: Write a program that adds all the digits in an integer. If the resulting sum is more than one digit, keep repeating until the sum is one digit. For example, the number 2345 has the sum 2+3+4+5 = 14 which is not a single digit so repeat with 1+4 = 5 which is a single digit.

This is the code I have so far. It works out for the first part, but I can't figure out how to make it repeat until the sum is a single digit. I'm pretty sure I'm supposed to nest the code I already have with another while statement

n = int(input("Input an integer:"))
sum_int=0  
while float(n)/10 >= .1:   
    r= n%10
    sum_int += r
    n= n//10   
    if float(n)/10 > .1: print(r,  end= " + ") 
    else: print(r,"=",sum_int)

this is a sample output of the code

Input an integer: 98765678912398

8 + 9 + 3 + 2 + 1 + 9 + 8 + 7 + 6 + 5 + 6 + 7 + 8 + 9 = 88

8 + 8 = 16

1 + 6 = 7

like image 312
James G Avatar asked Dec 06 '22 16:12

James G


1 Answers

This should work, no division involved.

n = int(input("Input an integer:"))
while n > 9:
    n = sum(map(int, str(n)))
print(n)

It basically converts the integer to a string, then sums over the digits using a list comprehension and continues until the number is no greater than 9.

like image 56
Jawad Avatar answered Dec 17 '22 20:12

Jawad