简体   繁体   中英

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.

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

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!

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM