Print splitters in Python, with their sum in the output

Asked

Viewed 286 times

-1

I need to create a program that shows the sum of all the divisors of a number, except this number itself.

Ex: the sum of the divisors of number 66 is 1 + 2 + 3 + 6 + 11 + 22 + 33 = 78

In case, I need to print only the 78, as output.

My program, however, is printing all divisors. How to change this, please? Follow my code below:

divisor = 1

numero = int(input('Informe um número inteiro e positivo: '))
if numero < 0:
    numero = int(input('O número não pode ser negativo.\n Digite um número inteiro e positivo: '))
for divisor in range(divisor, numero):
    if numero % divisor == 0:
        print(divisor)

My code above returns, for example, if I type 66, the following:

1
2
3
6
11
22
33
  • Related: https://answall.com/q/456301/112052

  • 2
  • Thank you. So it is that in fact hkotsubo had posted a simpler form containing functions and resources that I have studied so far. But his post is gone...

  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful to you. You can also vote on any question or answer you find useful on the entire site

1 answer

1

The biggest reason for the error is that you are not adding up. Programming is interpreting the problem. In its description clearly has a sum, in the code there is no, so the problem is this. Making the sum works.

Of course you should print only the sum once at the end, not in the loop because the problem does not ask to print the accumulated in each step, in fact, from what I understand, nor the dividers ask, but it may be only because a statement is not good, if you need just put that impression on the loop.

The validation is weird because if the person type a wrong time he does not let, but if he does it on Monday, then the correct is to have a loop there that only comes out when a suitable value was typed.

I haven’t seen it all yet, it can make a mistake if the person type something that is not even a number, sure to treat it too, see how to do in an answer from me or The program is not recognizing whole number as such

while True:
    numero = int(input('Digite um número inteiro e positivo: '))
    if numero >= 0:
        break
    print('O número não pode ser negativo.')
divisor = 1
soma = 0
for divisor in range(divisor, numero):
    if numero % divisor == 0:
        soma += divisor
print(soma)

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Browser other questions tagged

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