Python perfect number calculation
<p>I am having issues with calculating perfect numbers in python. Apparently the code is working in VBA so I am sure I am making some mistake in syntax / indentation. Please help!</p>

<p>Here is my code:</p>

<pre><code>Mynum=int(input("How many perfect numbers do you want?: "))

counter=0
k=0
j=2
i=1

while counter&lt;Mynum:
    for i in range (1,j-1):
        if (j%i)==0:
            k=k+1
    if k==j:
        counter=counter+1
        print(i)
    k=0
    j=j+1
</code></pre>

<p>Here's another solution to the perfect number:</p>

<pre><code>import itertools as it

def perfect():
    for n in it.count(1):
        if sum(i for i in range(1, n+1) if n%i == 0) == 2*n:
            yield n

&gt;&gt;&gt; list(it.islice(perfect(), 3))
[6, 28, 496]
100 loops, best of 3: 12.6 ms per loop
</code></pre>

<p>Or you can use factors (for a slightly faster solution):</p>

<pre><code>def factors(n):
    for a in range(1, int(n**0.5)+1):
        if n % a:
            continue
        x = n // a
        yield a
        if a != x:
            yield x

def perfect():
    for n in it.count(1):
        if sum(factors(n))==2*n:
            yield n

&gt;&gt;&gt; list(it.islice(perfect(), 3))
[6, 28, 496]
1000 loops, best of 3: 1.43 ms per loop
</code></pre>

<p>You can improve this even further using a fast prime number version.<br>
Taking a simple prime generator from <a href="http://stackoverflow.com/questions/2211990/how-to-implement-an-efficient-infinite-generator-of-prime-numbers-in-python/3796442#3796442">How to implement an efficient infinite generator of prime numbers in Python?</a>)</p>

<pre><code>import itertools as it
import functools as ft

def primegen():
    yield 2
    D = {}
    for q in it.count(3, 2):
        p = D.pop(q, None)
        if p is None:
            D[q*q] = q
            yield q
        else:
            x = q + 2*p
            while x in D:
                x += 2*p
            D[x] = p

def ll(p):   # Lucas-Lehmer
    if p == 2:
        return True
    m = 2**p - 1
    return ft.reduce(lambda s, _: (s**2 - 2) % m, range(3, p+1), 4) == 0

def perfect():
    for p in primegen():
        if ll(p):
            yield (2**p-1)*(2**(p-1))

&gt;&gt;&gt; list(it.islice(perfect(), 3))
[6, 28, 496]
100000 loops, best of 3: 7.94 Âµs per loop
&gt;&gt;&gt; list(it.islice(perfect(), 10))
[6,
 28,
 496,
 8128,
 33550336,
 8589869056,
 137438691328,
 2305843008139952128,
 2658455991569831744654692615953842176,
 191561942608236107294793378084303638130997321548169216]
1000 loops, best of 3: 613 Âµs per loop
</code></pre>

<p>These get very big very quickly, e.g. the 20th perfect number has 2663 digits.</p>

python perfect-numbers