找到你要的答案

Q:First 100 prime numbers in Python

Q:第一100个素数在Python

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. Thanks for your patience and help

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)

我在Python初学者和我有一个关于发现100素数问题。我知道有很多方法可以做到这一点,但请帮助我在我的方法。我发现计数的值在增加,但由于某种原因,while循环条件不适用。谢谢你的耐心和帮助

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)
answer1: 回答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)).

你可以用筛埃拉托色尼找到第n个素数:

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

第一个获得100个:

>>> 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]

找到第n个素数,你可以估计n个素数(通过上限的限制)或使用无限素数生成器和获得尽可能多的数量,你需要如使用列表(itertools。伊斯利采(创,100))。

python-3.x  primes