Search code examples
pythonlistconditional-statements

Python prime number calculator


prime = [2]
while len(prime) <= 1000:
    i=3
    a = 0
    for number in prime:
        testlist= []
        testlist.append(i%number)
    if 0 in testlist:
        i=i+1
    else:
        prime.append(i)
        i=i+1
print(prime[999])

Trying to make a program that computes primes for online course. This program never ends, but I can't see an infinite loop in my code.

A prime number is a number that can only be divided by exclusively one and itself.

My logic is that if a number can be divided by prime numbers preceding it then it is not prime.


Solution

  • As the comments to your question pointed out, there is several errors in your code.

    Here is a version of your code working fine.

    prime = [2]
    i = 3
    while len(prime) <= 1000:
        testlist = []
        for number in prime:
            testlist.append(i % number)
        if 0 not in testlist:
            prime.append(i)
        i = i + 1
    print prime