Python prime number calculator

Question:

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.

Asked By: user3743825

||

Answers:

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
Answered By: Xavier V.

I haven’t tested but you can create method like below:

def get_prime_no_upto(number):
  start = 2
  primes = list(range(start,number)).to_a
  for no in range(start,number):
    for num in range(start,no):
      if ( no % num  == 0) and (num != no):
        primes.delete(no)
        break
  primes

and can use it like

print primeno(100)

cheers!

Answered By: Manish Shrivastava
def prime_checker(number):
    stop = False
    prime = True
    n = 2
    while stop == False and n < number:
        if (number) % n == 0:
            prime = False
            stop = True
        n += 1
    if prime == True:
        print("It's a prime number.")
    elif prime == False:
        print("It's not a prime number.")

prime_checker(11)
Answered By: KeesOG
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.