Search code examples
python-3.xmathperfect-numbers

Python Perfect Number Search


so I wanted to code a program that finds perfect numbers. I made a draft however it prints irrelevant numbers. Please let me know how to fix this program.

f = []

p = []

for i in range(2, 100):
    for k in range(1, i):
        if i % k == 0:
            f.append(k)
    if sum(f) == i:
        p.append(i)

print(p)

Solution

  • You have clean f every time and don't include the last number.

    p = []
    
    for i in range(2, 500):
        f = [] #clean f
        for k in range(1, i): 
            if i % k == 0:
                f.append(k)
        if sum(f) == i:
            p.append(i)
    
    print(p)