Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading