Python – did the program on perfect numbers in python and not sure if i should use (1,1000) or (2, n+1) in range

perfect-numberspython

I did lab on perfect numbers in python it runs fine and prints numbers that I need. But not sure if I need to put (1, 1000) in range or (2, n+1) is fine? My instruction asking me to

"Write a python program to find all the perfect numbers from 1 to 10,000. When a perfect number is found, your logic should print it."

What is a perfect number:

In number theory, a perfect number is a positive integer that is equal to the sum of its proper positive divisors, that is, the sum of its positive divisors excluding the number itself (also known as its aliquot sum). Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself) i.e. σ1(n) = 2n.

When I run my program it prints out 6, 28, 496, and 8128.

 n = 1
 while True:
     factors = [1]
     [factors.append(i) for i in range(2,n+1) if n%i == 0]
     if sum(factors) == 2*n: print n
     n += 1

Best Answer

something like: you can also use a range(1,n) as perfect number is equal to sum of all its divisors except itself, i.e. 6=1+2+3

n = 1
while True:
    factors =(i for i in range(1,n) if n%i == 0) #use a generator expression
    if sum(factors) == n: 
        print n
    n += 1

output:

6
28
496
8128

or a one liner:

In [2]: [x for x in xrange(1,10001) if sum(y for y in xrange(1,x) if x%y==0)==x]
Out[2]: [6, 28, 496, 8128]
Related Topic