Made my program on perfect numbers in python and not sure if I should use (1,1000) or (2, n + 1) in the range

I was doing labs on perfect numbers in python, it worked fine and prints the numbers I need. But not sure if I need to put (1, 1000) in a range or (2, n + 1) ok? My commission is to ask me

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

What is the ideal number:

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

When I run my program, it gives 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
+5
source share
5 answers

n . range(2, n/2 + 1), if sum(factors) == n - 1. range(2, 10001) (.. n ). : 1 , .

for n in range(2, 10001):
    if sum(i for i in range(2, n/2 + 1) if n % i == 0) == n - 1:
        print n
+2

- : (1,n), , , 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

:

6
28
496
8128

:

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]
+3

, , .

, range(2,n). , n% n 0, n. , n, 2 * n ( 2 * n, n ).

, range(2, int(math.sqrt(n))). a n, n/a. , ([i, n/i]) i. import math '.

+1

[1.. n], n, (2, n + 1). :

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

, - , , , , - ( , n + 1, ) == 2 * n; = [1], = [] (1, n).:)

I would write the same thing (or even delete the list to get rid of python newbie consciousness):

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

The same conclusion.

0
source

All Articles