# 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)
``````

``````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)).

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

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

python-3.x  primes