C# Program to Print Prime Numbers in Range
for and if conditions; for example, use for (int i = start; i <= end; i++) and check if i is prime before printing.Examples
How to Think About It
Algorithm
Code
using System; class Program { static bool IsPrime(int n) { if (n <= 1) return false; for (int i = 2; i * i <= n; i++) { if (n % i == 0) return false; } return true; } static void Main() { int start = 1, end = 20; for (int i = start; i <= end; i++) { if (IsPrime(i)) Console.Write(i + " "); } } }
Dry Run
Let's trace the program for the range 1 to 10 through the code.
Start loop from 1 to 10
i = 1
Check if 1 is prime
1 <= 1, so not prime
Increment i to 2 and check prime
2 > 1, check divisors from 2 to sqrt(2) (which is ~1.4), no divisors found, prime
Print 2
Output: '2 '
Repeat for i=3 to 10
3,5,7 are prime; 4,6,8,9,10 are not
| Number | Is Prime? |
|---|---|
| 1 | No |
| 2 | Yes |
| 3 | Yes |
| 4 | No |
| 5 | Yes |
| 6 | No |
| 7 | Yes |
| 8 | No |
| 9 | No |
| 10 | No |
Why This Works
Step 1: Check numbers greater than 1
Numbers less than or equal to 1 are not prime, so we skip them.
Step 2: Test divisibility up to square root
We only check divisors up to the square root of the number because if a number has a divisor larger than its square root, it must have a smaller one too.
Step 3: Print prime numbers
If no divisor is found, the number is prime and printed.
Alternative Approaches
using System; class Program { static void Main() { int start = 1, end = 20; bool[] prime = new bool[end + 1]; for (int i = 2; i <= end; i++) prime[i] = true; for (int p = 2; p * p <= end; p++) { if (prime[p]) { for (int i = p * p; i <= end; i += p) prime[i] = false; } } for (int i = start; i <= end; i++) { if (prime[i]) Console.Write(i + " "); } } }
using System; using System.Collections.Generic; class Program { static void Main() { int start = 1, end = 20; List<int> primes = new List<int>(); for (int i = start; i <= end; i++) { if (i > 1) { bool isPrime = true; foreach (int p in primes) { if (p * p > i) break; if (i % p == 0) { isPrime = false; break; } } if (isPrime) { primes.Add(i); Console.Write(i + " "); } } } } }
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 a few variables.
Which Approach is Fastest?
The Sieve of Eratosthenes is faster for large ranges with O(n log log n) time but uses O(n) space, while the simple check is easier and uses less memory.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Simple divisibility check | O(n * sqrt(n)) | O(1) | Small to medium ranges |
| Sieve of Eratosthenes | O(n log log n) | O(n) | Large ranges |
| Check divisibility by primes only | Better than simple, depends on primes found | O(n) | Medium ranges with optimization |