First 100 Prime Numbers
I know there are a number of ways to find the first 100 prime numbers but please help me in my approach. I find the value of count to be increasing but for some reason the while lo
Solution 1:
You could use Sieve of Eratosthenes to find the first n
prime numbers:
defprimes_upto(limit):
prime = [True] * limit
for n inrange(2, limit):
if prime[n]:
yield n # n is a primefor c inrange(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))
.
Solution 2:
This is a more simpler code. We have looped all the numbers from 0 to the number until we have printed 100 prime numbers.
n=0
i=0while n<100:
i+=1
count=1for j in range(2,i):
if i%j==0:
count=0breakif count==1:
print(i,end=' ')
n+=1
Post a Comment for "First 100 Prime Numbers"