Prime Sieve Python

import math

n = 20
# 1. Initialize list A from 0 to n
A = [p for p in range(n + 1)]

# 2. Outer loop: iterate from 2 to sqrt(n)
for p in range(2, int(math.sqrt(n)) + 1):
    # 3. If A[p] is not 0, p is a prime
    if A[p] != 0:
        # 4. Mark multiples starting from p*p
        j = p * p
        # 5. Eliminate composite numbers
        while j <= n:
            A[j] = 0
            j = j + p

# Print results (filter out 0 and 1)
primes = [x for x in A if x > 1]
print(f"Primes: {primes}")

 

import math

n = 20
# 1. Initialize all as True (Everyone is innocent)
is_prime = [True] * (n + 1)

# 2. Sieve logic up to sqrt(n)
for p in range(2, int(math.sqrt(n)) + 1):
    if is_prime[p]:
        # 3. Mark multiples as False (Guilty by association)
        for j in range(p * p, n + 1, p):
            is_prime[j] = False

# 4. Filter indices that remained True
primes = [i for i in range(2, n + 1) if is_prime[i]]
print(f"Primes: {primes}")

 

Scroll to Top