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.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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?
- Naming a list by a Python keyword is a bad practice and should be avoided! You named the list by the name
listwhich is a keyword in Python. - You were using the same variable names for different tasks such as
wfor denoting integer less thannand also range in for loop. This should be avoided too! - Idk, why you were using the variable
abut there’s no need to initialize variables with0if you are using asrange in for loop. - You were running the for loop till
1instead should run it0. - You were not setting the sum to zero at every integer.
Method 2
Here is a very simple implementation of the perfect numbers algorithm:
def isperfect(n: int) -> bool:
"""Test if a number is perfect."""
sum_ = sum(i for i in range(1, n//2+1) if not n % i)
return sum_ == n
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:
- The
isperfectfunction is used to test whethernis perfect. Efficiency is gained by only testing numbers <= n/2. - Capture the user’s requested integer.
- Using list comprehension, iterate the range of values (N-1) and test if each is perfect.
- The perfect numbers are captured and stored into the
pvariable as alist.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0