This program prints every prime number between a start and an end value. It reuses the is_prime() function from the prime number check page.
The program
python
import math def is_prime(n): if n < 2: return False for i in range(2, math.isqrt(n) + 1): if n % i == 0: return False return True start = int(input("Start: ")) end = int(input("End: ")) primes = [n for n in range(start, end + 1) if is_prime(n)] print(f"Primes from {start} to {end}:", *primes) print("Count:", len(primes))
Typed in this example: 10, 50. Press Run to type your own.
output
Start: 10 End: 50 Primes from 10 to 50: 11 13 17 19 23 29 31 37 41 43 47 Count: 11
How it works
range(start, end + 1)includes the end value, so 50 is checked too.- The list comprehension
[n for n in ... if is_prime(n)]keeps only the numbers for whichis_prime(n)returnsTrue. - A start value below 2 is not a problem:
is_prime()returnsFalsefor 0, 1 and negative numbers.
Another way: the Sieve of Eratosthenes
To find all primes up to a limit, the Sieve of Eratosthenes is much faster than testing each number. It starts by marking every number as possibly prime. Then, for each prime it finds, it crosses out all multiples of that prime.
python
limit = 50 is_prime = [True] * (limit + 1) is_prime[0] = is_prime[1] = False for n in range(2, int(limit ** 0.5) + 1): if is_prime[n]: for multiple in range(n * n, limit + 1, n): is_prime[multiple] = False primes = [n for n in range(limit + 1) if is_prime[n]] print(*primes)
output
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
is_prime[n]isTruewhile the number n has not been crossed out.- Crossing out starts at
n * n, because the smaller multiples (like 2 × 5 when n is 5) were already crossed out by a smaller prime. range(n * n, limit + 1, n)counts up in steps of n, so it gives exactly the multiples of n.