32 lines
No EOL
1 KiB
Text
32 lines
No EOL
1 KiB
Text
def sieve_of_eratosthenes(limit):
|
|
"""
|
|
Generate all prime numbers up to the given limit using the Sieve of Eratosthenes algorithm.
|
|
"""
|
|
is_prime = [True] * (limit + 1)
|
|
p = 2
|
|
while (p * p <= limit):
|
|
if (is_prime[p] == True):
|
|
for i in range(p * p, limit + 1, p):
|
|
is_prime[i] = False
|
|
p += 1
|
|
prime_numbers = [p for p in range(2, limit + 1) if is_prime[p]]
|
|
return prime_numbers
|
|
|
|
|
|
def first_n_primes(n):
|
|
"""
|
|
Calculate the first n prime numbers using the Sieve of Eratosthenes algorithm.
|
|
"""
|
|
# Estimate an upper limit for the nth prime number using the approximation n * log(n * log(n))
|
|
# This is a rough estimate and ensures we have a high enough limit to find the first n primes.
|
|
import math
|
|
if n < 6:
|
|
limit = 15
|
|
else:
|
|
limit = int(n * math.log(n * math.log(n)))
|
|
primes = sieve_of_eratosthenes(limit)
|
|
return primes[:n]
|
|
|
|
# Example usage:
|
|
first_1000_primes = first_n_primes(1000)
|
|
print(first_1000_primes) |