Python Program to Print Prime Numbers in Range
for num in range(start, end+1): and if all(num % i != 0 for i in range(2, int(num**0.5)+1)) to test primality.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 example with start=10 and end=15 through the code
Start loop with num=10
Check if 10 > 1: yes Check divisors from 2 to 3 10 % 2 == 0 (divisible), so break, not prime
Next num=11
11 > 1: yes Check divisors 2 to 3 11 % 2 != 0, 11 % 3 != 0 No divisor found, print 11
Next num=12
12 > 1: yes 12 % 2 == 0, break, not prime
Next num=13
13 > 1: yes Check divisors 2 to 3 13 % 2 != 0, 13 % 3 != 0 No divisor found, print 13
Next num=14
14 > 1: yes 14 % 2 == 0, break, not prime
Next num=15
15 > 1: yes Check divisors 2 to 3 15 % 2 != 0, 15 % 3 == 0, break, not prime
| Number | Divisible by any from 2 to sqrt(num)? | Prime? |
|---|---|---|
| 10 | Yes (2) | No |
| 11 | No | Yes |
| 12 | Yes (2) | No |
| 13 | No | Yes |
| 14 | Yes (2) | No |
| 15 | Yes (3) | No |
Why This Works
Step 1: Check numbers greater than 1
Prime numbers are greater than 1, so numbers less than or equal to 1 are skipped.
Step 2: Test divisibility up to square root
Checking divisibility up to the square root is enough because if a number has a factor larger than its square root, it must have a smaller corresponding factor.
Step 3: Use loop with else for prime detection
If the loop completes without finding a divisor, the else block runs, confirming 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 primes = [num for num in range(start, end + 1) if num > 1 and all(num % i != 0 for i in range(2, int(num ** 0.5) + 1))] print(*primes)
Complexity: O(n * sqrt(n)) time, O(1) space
Time Complexity
For each number in the range (n), we check divisibility up to its square root (sqrt(n)), resulting in O(n * sqrt(n)) time.
Space Complexity
The program uses constant extra space O(1) as it only stores loop variables and prints results directly.
Which Approach is Fastest?
Using a function or list comprehension does not change time complexity but can improve readability or conciseness. For very large ranges, advanced methods like the Sieve of Eratosthenes are faster.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Loop with divisibility check | O(n * sqrt(n)) | O(1) | Simple and clear for small ranges |
| Function-based check | O(n * sqrt(n)) | O(1) | Reusable and clearer code |
| List comprehension | O(n * sqrt(n)) | O(n) | Concise code, less beginner-friendly |