0
0
CsharpProgramBeginner · 2 min read

C# Program to Print Prime Numbers in Range

Use a loop to check each number in the range and print it if it is prime by testing divisibility with for and if conditions; for example, use for (int i = start; i <= end; i++) and check if i is prime before printing.
📋

Examples

Inputstart=1, end=10
Output2 3 5 7
Inputstart=10, end=20
Output11 13 17 19
Inputstart=22, end=22
Output
🧠

How to Think About It

To print prime numbers in a range, start from the lower bound and go up to the upper bound. For each number, check if it is greater than 1 and not divisible by any number other than 1 and itself. If it passes this test, print it as a prime number.
📐

Algorithm

1
Get the start and end values of the range.
2
For each number from start to end, do the following:
3
Check if the number is prime by testing divisibility from 2 up to the square root of the number.
4
If the number is prime, print it.
5
Repeat until all numbers in the range are checked.
💻

Code

csharp
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 + " ");
        }
    }
}
Output
2 3 5 7 11 13 17 19
🔍

Dry Run

Let's trace the program for the range 1 to 10 through the code.

1

Start loop from 1 to 10

i = 1

2

Check if 1 is prime

1 <= 1, so not prime

3

Increment i to 2 and check prime

2 > 1, check divisors from 2 to sqrt(2) (which is ~1.4), no divisors found, prime

4

Print 2

Output: '2 '

5

Repeat for i=3 to 10

3,5,7 are prime; 4,6,8,9,10 are not

NumberIs Prime?
1No
2Yes
3Yes
4No
5Yes
6No
7Yes
8No
9No
10No
💡

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 Sieve of Eratosthenes
csharp
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 + " ");
        }
    }
}
This method is faster for large ranges but uses extra memory.
Check divisibility only by primes found so far
csharp
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 + " ");
                }
            }
        }
    }
}
This reduces checks but is more complex to implement.

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.

ApproachTimeSpaceBest For
Simple divisibility checkO(n * sqrt(n))O(1)Small to medium ranges
Sieve of EratosthenesO(n log log n)O(n)Large ranges
Check divisibility by primes onlyBetter than simple, depends on primes foundO(n)Medium ranges with optimization
💡
Check divisibility only up to the square root of the number to save time.
⚠️
Checking divisibility up to the number itself instead of its square root wastes time.