Example output
The Sieve of Eratosthenes is a highly efficient way to generate a list of prime numbers up to a given number \( N \). The algorithm works by iteratively marking the multiples of each prime number starting from 2. The prime numbers are the numbers that have not been marked as multiples.
Here's how we can implement this in Python:
1. Create a Boolean Array: We start by initializing a boolean array of length \( N+1 \) (since we want to include \( N \) itself), setting all elements to `True`. This array represents whether each number is prime (`True` means it is potentially prime).
2. Sieve Process: We iterate from 2 to \(\sqrt{N}\) (since any non-prime number must have a factor less than or equal to its square root). For each number \( i \), if it is marked as `True` in our array, we mark all multiples of \( i \) (from \( i^2 \) to \( N \)) as `False`, indicating they are not prime.
3. Collect Primes: At the end of this process, the indices of the array that are still `True` represent prime numbers.
4. Optimizations: We can make a few optimizations:
- Start marking multiples from \( i^2 \) as all smaller multiples of \( i \) would have already been marked by smaller primes.
- Use memory efficiently by avoiding even numbers.
Here is the Python code implementing the Sieve of Eratosthenes:
def sieve_of_eratosthenes(n):
# Boolean array, initialized to True. `prime[p]` will finally be False if p is Not a prime.
prime = [True for _ in range(n+1)]
p = 2
while (p * p <= n):
# If prime[p] is not changed, then it is a prime
if prime[p] == True:
# Marking all multiples of p as not prime
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
# Collecting all prime numbers
prime_numbers = []
for p in range(2, n+1):
if prime[p]:
prime_numbers.append(p)
return prime_numbers
# Example usage
N = 100
print(sieve_of_eratosthenes(N))