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?
- 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. - You were using the same variable names for different tasks such as
w
for denoting integer less thann
and also range in for loop. This should be avoided too! - Idk, why you were using the variable
a
but there's no need to initialize variables with0
if you are using asrange in for loop
. - You were running the for loop till
1
instead should run it0
. - 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:
- The
isperfect
function is used to test whethern
is perfect. If yes, 1 is returned, otherwise 0. - 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
p
variable as alist
.