First 100 prime numbers

别等时光非礼了梦想. 提交于 2019-12-13 05:23:09

问题


I am a beginner in Python and I have a question regarding finding 100 prime numbers. I know there are a number of ways to do it but please help me in my approach. I find the value of count to be increasing but for some reason the while loop condition doesn't apply.

from __future__ import print_function
count = 0

while(count <= 20):
    for i in range(2,20):
        for j in range(2,i):
            if i < j:
                print("The number",i,"is prime")
            elif i % j == 0:
                break
        else:
            print("The number",i,"is prime")
            count = count + 1
            print(count)

回答1:


You could use Sieve of Eratosthenes to find the first n prime numbers:

def primes_upto(limit):
    prime = [True] * limit
    for n in range(2, limit):
        if prime[n]:
            yield n # n is a prime
            for c in range(n*n, limit, n):
                prime[c] = False # mark composites

To get the first 100 primes:

>>> list(primes_upto(542))
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, ... ,
 499, 503, 509, 521, 523, 541]

To find the first n primes, you could estimate n-th prime (to pass the upper bound as the limit) or use an infinite prime number generator and get as many numbers as you need e.g., using list(itertools.islice(gen, 100)).




回答2:


If one is looking for a mix of efficiency and simple code, Numpy is worth a try. With some fancy indexing, the following code does the job of implementing the sieve of Eratosthenes.

import numpy as np

ns = np.array(range(2,N))
primes = []
last_prime=2
while last_prime:
    primes.append(last_prime)
    ns = ns[ns%last_prime != 0]
    last_prime = ns[0] if len(ns) > 0 else None
print(primes[:100])

Then just adjust N until you do have 100 primes. A good first guess is something in the order of 100*log(100) ~ 460 (coming from the prime number theorem). This will give 88 primes. Increasing N to the value of 600, you will have enough primes.



来源:https://stackoverflow.com/questions/33006472/first-100-prime-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!