Home > Software engineering >  Print all perfect numbers less than N
Print all perfect numbers less than N

Time:04-30

I am trying to print all perfect numbers lesser than an integer, but I am not sure how to do it. Could you help me, please? When I execute the code, it writes ValueError: invalid literal for int() with base 10.

My code:

n = input() 
w = int(n) - 1
i = 0
a = 0
z = 0
list = []
for w in range(w, 1):
    for i in range(w, 2):
        if w % i == 0:
            a = int(w / i)
            z = z   a
    if z == w:
        list.append(w)
print(list)

What is a perfect number?

In number theory, a perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself.

CodePudding user response:

Here's how you can do it:

n = input('Enter the integer:') 
w = int(n) - 1
l = [] # creating an empty list 'l'
for i in range(w, 0, -1): # Runs the loop for all integers below n and greater than 0. 
  s = 0 # Set the sum to 0. 
  for j in range(i,0, -1): # Runs the loop till 0 to check for all divisors
    if i % j == 0 and j!= i: # If the number is a divisor of 'i' and not equal to the 'i' itself. 
      s = s   j # Then add the divisor to the sum
  if s == i: # If sum is equal to the number 'i'
    l.append(i) # Then add the number 'i' to the list 'l'
print(l)

Output:

Enter the integer:10000
[8128, 496, 28, 6]

What you were doing wrong?

  1. Naming a list by a Python keyword is a bad practice and should be avoided! You named the list by the name list which is a keyword in Python.
  2. You were using the same variable names for different tasks such as w for denoting integer less than n and also range in for loop. This should be avoided too!
  3. Idk, why you were using the variable a but there's no need to initialize variables with 0 if you are using as range in for loop.
  4. You were running the for loop till 1 instead should run it 0.
  5. You were not setting the sum to zero at every integer.

CodePudding user response:

Here is a very simple implementation of the perfect numbers algorithm:

def isperfect(n: int) -> int:
    """Test if a number is perfect."""
    sum_ = sum(i for i in range(1, n) if not n % i)
    return 1 if sum_ == n else 0

n = int(input('Enter a positive integer: '))
p = [i for i in range(1, n) if isperfect(i)]

Output:

Enter a positive integer: 10000

print('Perfect numbers:', *p)
Perfect numbers:  6 28 496 8128

Explanation:

  1. The isperfect function is used to test whether n is perfect. If yes, 1 is returned, otherwise 0.
  2. Capture the user's requested integer.
  3. Using list comprehension, iterate the range of values (N-1) and test if each is perfect.
  4. The perfect numbers are captured and stored into the p variable as a list.
  • Related