Python Program to Print All Prime Numbers in Range
for num in range(start, end+1): and inside it checking if num is prime by testing divisors from 2 to int(num**0.5)+1.Examples
How to Think About It
Algorithm
Code
start = 1 end = 20 for num in range(start, end + 1): if num > 1: for i in range(2, int(num ** 0.5) + 1): if num % i == 0: break else: print(num, end=' ')
Dry Run
Let's trace the program for the range 1 to 10.
Start loop with num=1
num=1 is not greater than 1, so skip.
num=2 check
Check divisors from 2 to sqrt(2)=1.4 (no divisors to check). No divisor found, print 2.
num=3 check
Check divisors 2 to sqrt(3)=1.7 (no divisors to check). No divisor found, print 3.
num=4 check
Check divisors 2 to 2. 4 % 2 == 0, break, do not print.
num=5 check
Check divisors 2 to 3. 5 % 2 != 0, no divisor found, print 5.
| num | divisor checked | divisible? | print? |
|---|---|---|---|
| 1 | N/A | N/A | No |
| 2 | N/A | No | Yes |
| 3 | N/A | No | Yes |
| 4 | 2 | Yes | No |
| 5 | 2,3 | No | Yes |
| 6 | 2 | Yes | No |
| 7 | 2,3 | No | Yes |
| 8 | 2 | Yes | No |
| 9 | 2,3 | Yes (3) | No |
| 10 | 2 | Yes | No |
Why This Works
Step 1: Check numbers greater than 1
Prime numbers are greater than 1, so numbers less than 2 are skipped.
Step 2: Check divisibility up to square root
If a number has a divisor larger than its square root, it must also have a smaller one, so checking up to the square root is enough.
Step 3: Use else with for loop
The else block after the for loop runs only if no break occurs, meaning no divisor was found and the number is prime.
Alternative Approaches
def is_prime(n): if n <= 1: return False for i in range(2, int(n**0.5)+1): if n % i == 0: return False return True start, end = 1, 20 for num in range(start, end+1): if is_prime(num): print(num, end=' ')
start, end = 1, 20 sieve = [True] * (end + 1) sieve[0], sieve[1] = False, False for i in range(2, int(end**0.5) + 1): if sieve[i]: for j in range(i*i, end+1, i): sieve[j] = False for num in range(start, end+1): if sieve[num]: print(num, end=' ')
Complexity: O(n * sqrt(m)) time, O(1) space
Time Complexity
For each number n in the range, we check divisibility up to sqrt(n), so total time is roughly n times sqrt of the max number.
Space Complexity
The program uses constant extra space, only a few variables for loops and checks.
Which Approach is Fastest?
The Sieve of Eratosthenes is faster for large ranges but uses more memory, while the simple check is easier and uses less space.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Simple divisibility check | O(n * sqrt(m)) | O(1) | Small to medium ranges |
| Function-based check | O(n * sqrt(m)) | O(1) | Improved readability, small ranges |
| Sieve of Eratosthenes | O(n log log n) | O(n) | Large ranges, performance critical |