Skip to content

Instantly share code, notes, and snippets.

@0xBigBoss
Created January 31, 2025 21:40
Show Gist options
  • Save 0xBigBoss/a29a87cdc772c0598136567e937a2e63 to your computer and use it in GitHub Desktop.
Save 0xBigBoss/a29a87cdc772c0598136567e937a2e63 to your computer and use it in GitHub Desktop.
Sieve of Eratosthenes algorithm
def sieve_of_eratosthenes(n: int) -> list[int]:
"""
Generate all prime numbers up to n using the Sieve of Eratosthenes algorithm.
Args:
n (int): Upper bound for generating prime numbers
Returns:
list[int]: List of all prime numbers up to n
Raises:
ValueError: If n is negative
"""
if n < 0:
raise ValueError("Input must be non-negative")
if n < 2:
return []
sieve = [True] * (n + 1)
sieve[0] = sieve[1] = False
for i in range(2, int(n**0.5) + 1):
if sieve[i]:
for j in range(i * i, n + 1, i):
sieve[j] = False
return [i for i in range(n + 1) if sieve[i]]
if __name__ == "__main__":
n = int(input("Enter a number: "))
try:
print(sieve_of_eratosthenes(n))
except ValueError as e:
print(f"Error: {e}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment