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>Your screenshot code, which is the better of the two, is broken in a couple of ways: your <code>k = k + 1</code> expression should be <code>k = k + i</code> as you want to sum the factors, not count them; you <code>print(i)</code> when your should print <code>j</code> or <code>k</code>:</p>

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

counter = 0
j = 2

while counter &lt; Mynum:
    k = 0

    for i in range (1, j):

        if (j % i) == 0:
            k += i

    if k == j:
        counter += 1

        print(j)

    j += 1
</code></pre>

<p>However, in the bigger picture, this is the wrong approach for looking for perfect numbers -- using this method you're not likely to find more than the first four:</p>

<pre><code>How many perfect numbers do you want?: 5
6
28
496
8128
</code></pre>

<p>so you might as well just go for those and forget about asking how many the user wants.</p>

<p>An example better approach would be to search for Mersenne primes using a <a href="https://en.wikipedia.org/wiki/Lucas%E2%80%93Lehmer_primality_test" rel="nofollow">Lucas-Lehmer primality test</a> and when you find one, compute the <a href="https://en.wikipedia.org/wiki/Mersenne_prime#Perfect_numbers" rel="nofollow">companion perfect number</a> from that.  This doesn't take too much code and will leap frog your current approach.</p>

python perfect-numbers