在 python 中,我如何打印出完美数字及其旁边显示的除数?
How would I print out the perfect numbers along with their divisors shown next to them in python?
#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
不要跟踪和,跟踪除数并在最后检查和:
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)
输出:
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]
强制列表理解解决方案:
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)
#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
不要跟踪和,跟踪除数并在最后检查和:
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)
输出:
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]
强制列表理解解决方案:
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)