How to add digits from a number to "1" digit?

Asked

Viewed 157 times

-5

I need to sum all the digits of a number until the result of this sum is a number of only "1" digit, that is to say, where the digit number of a given number is greater than 1, I must add their digits. This way, when the number of digits is equal to 1 the sum must be closed, displaying the result.

Example:

Insert the number 155. Add your digits (1 + 5 + 5), obtaining the result 11. Like the number 11 is formed by two digits, then it is added again its digits (1 + 1), obtaining the value 2. So as the value 2 has only 1 digit, the sum will be closed, thus displaying the value 2.

I even set up a line but it’s not working:

n1 = int(input("Pessoa 1: digite um numero:"))

soma1 = 0

while((n1//10) != 0):

    while(n1 != 0):

        resto = n1 % 10

        n1 = n1//10

        soma1 = soma1 + resto

    n1 = soma1

print("Sua soma é:", soma1)
  • Choose one of the solutions of this question and keep repeating this until the sum is less than 10

  • That’s exactly what I did, but the first while doesn’t work.

3 answers

3

On the algorithm to sum the digits, you can choose any one from here.

Having this, just go calculating the sum, until it is less than 10 (which is when it has only one digit). Something like this:

n = int(input("Pessoa 1: digite um numero:"))

# ajuste para o caso do número digitado ser negativo
# também inicializa a soma, para o caso do número já ser inicialmente menor que 10 (pois aí não entra no while)
soma = n = abs(n)

# enquanto o número for maior ou igual a 10 (ou seja, com mais que um dígito), continua
while n >= 10:
    # calcula a soma dos dígitos
    soma = 0
    while n > 0:
        n, d = divmod(n, 10)
        soma += d

    # atualiza o número com o valor da soma
    n = soma

print(f'valor final: {soma}')

That is, while the number is greater than or equal to 10 (it has more than one digit), I continue the loop.

It is also worth noting that the soma has to be initialized with zero within of loop, since you want to calculate the sum of the digits of the current value of the number. The way you did, the sum is accumulated and the value of it increases, and so never leaves the while.

2

Another interesting way to resolve this issue is to associate Assignment expressions along with Generating expressions.

In this case the code would be:

x = input("Digite um número: ")

while (s := sum(int(i) for i in x)) > 9:
    x = str(s)
print(f'O resultado é: {s}')

Note that this code captures digits in the string format. Next, the generating expression will be responsible for calculating the sum of all digits of the converted integer string. Later, the block while check whether the outcome of the expression of assignment associated with the variable s is greater than 9. If yes, the value of x will be updated as the s and the generating expression will be executed again, only this time with the new value - which is the string of s.

Note that while the value assigned to the assignment expression is greater than 9, calculations will be redone. Otherwise, the repeat loop while is closed and the value will be displayed.

Testing the code:

Imagine that when executing the respective code we typed the value:

155

The code would be executed and provide us with the value 11. For...

1 + 5 + 5 = 11

Now, how 11 is greater than 9, the generating expression will be executed again, producing as a result the value 2. For...

1 + 1 = 2

Since 2 is less than or equal to 9, the loop is closed by displaying the value as a result 2.


Another interesting way to resolve this issue is to apply the concepts of Proof of the Nine Out, performing a SUBTLE amendment to the final reply. This amendment replaces the final result with 9, if the same is 0.

Why this amendment?

The proof of the nine out is nothing more than the rest of the entire division of an "n" number by 9. Thus, if an "n" number is a multiple of 9, soon the rest of the division will be 0. Only by the logic of your code, answers will only be allowed between 1 and 9. So if the result of the nine out is 0 we should replace it with 9.

OBSERVING: If the entered value is None - empty - the program must return the value 0.

With this logic we can implement the following code:

def digital_root(n):
    return 0 if not n else 9 if (r := n % 9) == 0 else r


if __name__ == '__main__':
    number = int(input())
    resp = digital_root(number)

    print(resp)

Note that this code captures the entered value and checks whether it is None. Positive case, returns 0. If not, calculate the rest of your division by 9. If the value of the assignment expression assigned to the variable r be it 0 the value will be replaced by 9. Otherwise, the variable value r will be shown.

NOTE:

THIS ISSUE WAS MADE AVAILABLE BY CODEWARS PLATFORM, whose link is: Sum of Digits / Digital Root

-1

To solve this problem we can use the following program

def sum (n): # Realiza a soma 
    s = 0
    for i in n: # Percorre toda a string
        s += int(i)
    # Converte cada posição para um tipo inteiro e soma
    return str(s)

n = input()

while True:
    # Se n ainda tiver mais de um dígito ele continuará somando seus algarismos
    if len(n) > 1:
        n = sum(n)
    else:
        break
        
print(n)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.