Below is a clean, self-contained Python 3 script that:
Asks the user for an upper limit n.
Uses an efficient Sieve of Eratosthenes to compute every prime ≤ n.
Prints the primes and a count.
Can also be imported as a module—primes_up_to(n) returns the list of primes.
python
#!/usr/bin/env python3
"""
prime_sieve.py
Compute prime numbers quickly with a simple Sieve of Eratosthenes.
Run it directly, or import `primes_up_to` in another script.
"""
from math import isqrt
def primes_up_to(n: int) -> list[int]:
"""
Return all prime numbers ≤ n using an optimized sieve.
>>> primes_up_to(20)
[2, 3, 5, 7, 11, 13, 17, 19]
"""
if n < 2:
return []
# True means "assume prime" initially
sieve = bytearray(b"\x01") * (n + 1)
sieve[0:2] = b"\x00\x00" # 0 and 1 are not prime
# Iterate only up to sqrt(n)
for p in range(2, isqrt(n) + 1):
if sieve[p]:
# Start crossing off from p*p, step p
sieve[p*p : n+1 : p] = b"\x00" * ((n - p*p) // p + 1)
# Extract prime indices
return [i for i, is_prime in enumerate(sieve) if is_prime]
def main() -> None:
"""CLI entry point."""
try:
limit = int(input("Find primes up to: "))
except ValueError:
print("Please enter a valid integer.")
return
primes = primes_up_to(limit)
print(f"\nPrimes ≤ {limit}:")
print(primes)
print(f"\nTotal primes found: {len(primes)}")
if __name__ == "__main__":
main()