#I have the formula in which the code produces all perfect numbers between 1 and 10,000 and I want the divisors printed out alongside the perfect numbers
n = 1
while n <= 10001:
sum = 0
divisor = 1
while divisor < n:
if not n % divisor:
sum = divisor
divisor = divisor 1
if sum == n:
print(n, "is a perfect number")
n = n 1
#for example, I want the output to look like:
6 - proper divisors: 1, 2, 3
28 - proper divisors: 1, 2, 3, 4, 5, 6, 7
CodePudding user response:
Don't track the sum, track the divisors and check the sum at the end:
for n in range(1, 10001):
divisors = []
for divisor in range(1, n//2 1):
if not n % divisor:
divisors.append( divisor )
if sum(divisors) == n:
divisors.append( n )
print(n, "is a perfect number", divisors)
Output:
6 is a perfect number [1, 2, 3, 6]
28 is a perfect number [1, 2, 4, 7, 14, 28]
496 is a perfect number [1, 2, 4, 8, 16, 31, 62, 124, 248, 496]
8128 is a perfect number [1, 2, 4, 8, 16, 32, 64, 127, 254, 508, 1016, 2032, 4064, 8128]
Obligatory list comprehension solution:
for n in range(1, 10001):
divisors = [divisor for divisor in range(1, n//2 1) if not n % divisor]
if sum(divisors) == n:
divisors.append( n )
print(n, "is a perfect number", divisors)