-5

This algorithm, which is attached and written below, is printing the result multiple times. It is an algorithm to find out if the received number is a perfect number, that is, if the sum of the divisors of that number results in the number itself, then it is a perfect number. Example: the divisors of 6 are: 3, 2 and 1. Adding 3 + 2 + 1 = 6. Therefore, 6 is a perfect number. The algorithm in Python is this:

number = (int(input("Please, type a number to check if this is a perfect number: ")))
test = 0
for i in range(1, number):
    if(number % i == 0):
        test = test + i
    if test == n:
        print(n, "is a perfect number")
    else:
        print(n, " is not a perfect number")

The error is in the attached file, inside the red rectangle. Please, how to correct this code, so that the correct result is printed?

enter image description here

John
  • 49
  • 7

2 Answers2

1

Your code is trying to print a result before it's finished summing all of the divisors. Each number is either perfect or it isn't, so you shouldn't be printing a result on each iteration of the loop -- you need to let the loop finish, and then print/return your result based on the final sum you calculated.

A simple way to write this check would be to just do a sum of the divisors/factors, e.g.:

>>> def is_perfect(n):
...     return n == sum(i for i in range(1, n) if n % i == 0)
...
>>> is_perfect(6)
True
>>> is_perfect(5)
False
Samwise
  • 68,105
  • 3
  • 30
  • 44
0

Becuase you are printing inside for loop and each time when one of your conditions are true it will print the answer.

You should put if and else conditions outside of for loop, like this:

number = (int(input("Please, type a number to check if this is a perfect number: ")))
test = 0
for i in range(1, number):
    if(number % i == 0):
        test = test + i

if test == number:
    print(number, "is a perfect number")
else:
    print(number, " is not a perfect number")
John
  • 49
  • 7
bagli
  • 34
  • 4