Python Program for Sieve of Eratosthenes (original) (raw)

Given a number n, the task is to find and print all the prime numbers smaller than or equal to n. A prime number is a number greater than 1 that is divisible only by 1 and itself. For example:

**Input: n = 20
**Output: 2, 3, 5, 7, 11, 13, 17, 19

Let’s explore different methods to find all prime numbers up to a given number in Python.

Using Sieve of Eratosthenes

In this method, we start by assuming all numbers are prime and progressively mark the multiples of each prime as non-prime. This efficiently eliminates composites using a boolean list.

Python `

import math n = 30 prime = [True for _ in range(n + 1)] prime[0], prime[1] = False, False

for p in range(2, int(math.sqrt(n)) + 1): if prime[p]: for i in range(p * p, n + 1, p): prime[i] = False

for i in range(2, n + 1): if prime[i]: print(i, end=" ")

`

Output

2 3 5 7 11 13 17 19 23 29

**Explanation:

Using NumPy for Vectorized Sieve

Here, we use NumPy arrays to speed up marking non-prime numbers with vectorized operations. It’s faster for large n due to optimized array handling.

Python `

import numpy as np import math

n = 30 prime = np.ones(n + 1, dtype=bool) prime[0:2] = False

for p in range(2, int(math.sqrt(n)) + 1): if prime[p]: prime[p*p:n+1:p] = False

print(np.nonzero(prime)[0].tolist())

`

Output

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

**Explanation:

Using List Comprehension

In this concise method, list comprehension checks each number’s divisibility by all numbers up to its square root and keeps only primes. It’s compact but slower than the sieve methods.

Python `

import math n = 30 p = [x for x in range(2, n + 1) if all(x % i != 0 for i in range(2, int(math.sqrt(x)) + 1))] print(p)

`

Output

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

**Explanation:

Simple Iterative Check

This method checks divisibility for each number up to n. Though simple and easy to understand, it’s computationally expensive for large numbers.

Python `

n = 30 for num in range(2, n + 1): for i in range(2, num): if num % i == 0: break else: print(num, end=" ")

`

Output

2 3 5 7 11 13 17 19 23 29

**Explanation:

Please refer complete article on Sieve of Eratosthenes for more details!