- How to reuse the
isPrimefunction from assignment 2 inside a loop - How to iterate over an integer range and print filtered results
- How to handle the case where the user enters the endpoints in reverse order
- Why checking primality up to √n matters when you're doing it many times
- How this simple combination relates to the more efficient Sieve of Eratosthenes
From one prime to a range of primes
In assignment 2, you wrote a function isPrime(n) that checks whether a single number is prime. That's useful on its own, but in practice you rarely want to test just one number — you usually want to know which numbers in some range are prime. That's the assignment here: given a lower bound and an upper bound, print every prime in between.
The insight is simple: you already have isPrime, and now you have a loop. Combine them. Iterate n from low to high; for each n, call isPrime(n); if it returns 1, print n. That's the entire algorithm. There's no new math — just a loop around an existing function.
This kind of combination is exactly what functions are for. Once you have a correct, well-tested isPrime, you don't need to re-derive the primality test for a new problem. You call it. If you later optimize isPrime — say, by using the 6k ± 1 optimization — every caller benefits without changing a line of their code. That's the composability that modular code promises, and this assignment is a small demonstration of it.
The interesting edge case is when the user enters the range in reverse order: high low instead of low high. The program should still produce the correct primes. The easiest fix is to swap the two values if low > high, before the loop begins. This is the kind of input handling that turns a textbook example into a robust program — not strictly required for the assignment, but worth having.
💡 In one line: write isPrime(n) once. Then loop n from the smaller bound to the larger bound, printing n whenever isPrime(n) returns 1. That's the whole program.
Designing the solution
The solution has two parts: the isPrime function (which you already wrote in assignment 2) and a loop in main that iterates over the range. Here's the plan:
| Part | Responsibility |
|---|---|
isPrime(n) | Given a single integer n, return 1 if it's prime, 0 otherwise. Uses trial division up to √n. |
main() | Read low and high. Swap if needed. Loop from low to high. Call isPrime(n) for each n. Print n when the result is 1. |
The prototype:
int isPrime(int n);
And the definition — identical to the one from assignment 2:
int isPrime(int n) {
if (n <= 1) return 0;
if (n == 2 || n == 3) return 1;
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) return 0;
}
return 1;
}
The main function is where the range iteration happens:
int main(void) {
int low, high;
printf("Enter the range (low high): ");
scanf("%d %d", &low, &high);
if (low > high) {
int temp = low;
low = high;
high = temp;
}
printf("Prime numbers between %d and %d:\n", low, high);
for (int n = low; n <= high; n++) {
if (isPrime(n)) {
printf("%d ", n);
}
}
printf("\n");
return 0;
}
The swap before the loop is important. Without it, entering high low instead of low high would produce an empty range, and the loop would print nothing. The swap makes the program robust to user input order — a small quality-of-life improvement that costs almost nothing.
🎯 Key idea: reuse isPrime — don't re-derive primality checking inside the loop. The whole point of having the function is that the range-printing code doesn't have to know how primality works. It just calls and prints.
Complete C Program
Program: print all primes in a user-specified range
#include <stdio.h>
/* Function prototype */
int isPrime(int n);
int main(void) {
int low, high;
printf("Enter the range (low high): ");
scanf("%d %d", &low, &high);
/* Normalize the range so low <= high */
if (low > high) {
int temp = low;
low = high;
high = temp;
}
printf("Prime numbers between %d and %d:\n", low, high);
int count = 0;
for (int n = low; n <= high; n++) {
if (isPrime(n)) {
printf("%d ", n);
count++;
}
}
printf("\nTotal primes found: %d\n", count);
return 0;
}
/* Primality test — trial division up to sqrt(n) */
int isPrime(int n) {
if (n <= 1) return 0;
if (n == 2 || n == 3) return 1;
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) return 0;
}
return 1;
}
And here's a variant that prints the primes in a grid, one per line, so you can see the distribution — useful for ranges with hundreds of primes:
Variant: one prime per line
#include <stdio.h>
int isPrime(int n) {
if (n <= 1) return 0;
if (n == 2 || n == 3) return 1;
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) return 0;
}
return 1;
}
int main(void) {
int low, high;
printf("Enter the range: ");
scanf("%d %d", &low, &high);
if (low > high) { int t = low; low = high; high = t; }
printf("Primes in [%d, %d]:\n", low, high);
for (int n = low; n <= high; n++) {
if (isPrime(n)) {
printf("%d\n", n);
}
}
return 0;
}
And a version that uses the 6k ± 1 optimization for faster primality checks — useful for larger ranges:
Variant: 6k ± 1 optimization
#include <stdio.h>
int isPrime(int n) {
if (n <= 1) return 0;
if (n <= 3) return 1;
if (n % 2 == 0 || n % 3 == 0) return 0;
/* All primes > 3 are of the form 6k ± 1 */
for (int i = 5; i * i <= n; i += 6) {
if (n % i == 0 || n % (i + 2) == 0) return 0;
}
return 1;
}
int main(void) {
int low, high;
printf("Enter the range: ");
scanf("%d %d", &low, &high);
if (low > high) { int t = low; low = high; high = t; }
printf("Primes in [%d, %d]:\n", low, high);
for (int n = low; n <= high; n++) {
if (isPrime(n)) printf("%d ", n);
}
printf("\n");
return 0;
}
The 6k ± 1 optimization skips multiples of 2 and 3 before entering the loop, and then steps by 6 in the inner loop, checking i and i+2. This roughly halves the number of iterations for large n, making the whole program about twice as fast as the basic version. For a range like 1 to 100, the difference isn't noticeable; for 1 to 100,000, it's meaningful.
Program Output
A typical run:
Enter the range (low high): 10 50
Prime numbers between 10 and 50:
11 13 17 19 23 29 31 37 41 43 47
Total primes found: 11
With reversed input (high entered before low):
Enter the range (low high): 50 10
Prime numbers between 10 and 50:
11 13 17 19 23 29 31 37 41 43 47
Total primes found: 11
Notice the output is the same — the swap inside main normalizes the range. This is what robust input handling looks like: the program doesn't just fail when the user enters data in an unexpected order, it adapts.
A small range that crosses the boundary of triviality:
Enter the range (low high): 0 20
Prime numbers between 0 and 20:
2 3 5 7 11 13 17 19
Total primes found: 8
Notice that 0 and 1 are correctly excluded — the isPrime function handles them. Without that early check, the loop would start at i = 2 and might incorrectly classify them.
And a larger range that shows the density of primes:
Enter the range (low high): 1 100
Prime numbers between 1 and 100:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Total primes found: 25
25 primes under 100 — that's the well-known value, and a good sanity check. If your output differs, something in isPrime is off.
Step-by-Step Explanation
Let's walk through the program, from main's input handling to the isPrime call for each number.
1. Reading the range
scanf("%d %d", &low, &high) reads two integers. The format specifier doesn't care about order — it just reads whatever integers are available. The user might enter them in either order, and the program has to handle both.
2. Normalizing the range
if (low > high) { swap } — this ensures low ≤ high before the loop. Without the swap, a reversed input would produce an empty range (the loop condition n <= high would fail on the first check, since low > high). This is a small but important detail: it turns a subtle input-order bug into a non-issue.
3. The loop
for (int n = low; n <= high; n++) — iterate over every integer in the range, inclusive of both bounds. This is the standard range loop. Note that we're using int for n, not long or long long, because the range is assumed to fit in an int (which is a reasonable assumption for typical use — INT_MAX is over 2 billion).
4. The isPrime call
if (isPrime(n)) — call the function for each n. The function returns 1 for primes, 0 for composites (and for 0 and 1). The if treats 1 as true, 0 as false. This is exactly what predicate functions are for: they hide the complexity of "is this number prime?" behind a single boolean query.
5. Printing
printf("%d ", n) — print each prime followed by a space. The space separates primes on the same line, which is more compact than one-per-line. The count++ after the print keeps a running total, printed at the end. Counting is useful because it lets you verify the output against known values (25 primes under 100, 168 under 1000, etc.).
6. The isPrime function, revisited
The function handles three cases in order:
n <= 1→ not prime (covers 0, 1, and negatives).n == 2orn == 3→ prime (the two smallest primes).n ≥ 4→ loop fromi = 2to√n, checking for divisors. If any is found, return 0. If none, return 1.
The early returns for 0, 1, 2, 3 mean the loop can assume n ≥ 4, which simplifies the loop logic. The loop uses i * i <= n instead of i <= sqrt(n) — same effect, but in integer arithmetic, avoiding floating-point precision issues and library calls.
7. Complexity of the range scan
For a range of size R = high - low + 1, the loop runs R times. For each iteration, isPrime(n) does at most √n divisions. So the total work is O(R × √high) in the worst case. For R = 100 and high = 100, that's about 100 × 10 = 1000 divisions. For R = 10,000 and high = 100,000, it's about 10,000 × 316 = 3 million divisions — still fast (well under a second on any modern CPU).
For much larger ranges, you'd want a sieve instead. The Sieve of Eratosthenes generates all primes up to high in O(high log log high) time — much faster than calling isPrime for each n. But the sieve is a different algorithm, with different memory characteristics, and it's not what this assignment asks for. Our approach — one isPrime call per number — is the natural way to demonstrate function reuse, even if it's not the absolute fastest.
8. Testing the output
The number of primes in a range is a good sanity check. There are exactly 25 primes under 100, 168 under 1000, and 1229 under 10,000. If your program outputs those counts for the ranges [2, 100], [2, 1000], [2, 10000], you can be confident the implementation is correct. The count variable makes this verification trivial — just glance at the total.
9. Relation to the Sieve of Eratosthenes
The Sieve of Eratosthenes is a different (and faster) algorithm for finding all primes up to n. The idea: start with a boolean array of size n+1, all true. Mark 0 and 1 false. Then for each prime p starting from 2, mark all multiples of p (starting from p*p) as false. When you're done, the true entries are the primes. This runs in O(n log log n) time — noticeably faster than our O(n√n) approach for large n. But it uses O(n) memory, and it's more complex to write. For the assignment — which is about combining a function and a loop — our approach is exactly right. The sieve is a natural follow-up.
10. Range-based improvements
For very large ranges, there's a variant of the sieve called the "segmented sieve" that operates on chunks of the range rather than the whole range at once. This is what you'd use in production code that needs to find primes in, say, [10¹², 10¹² + 10⁶]. But again, that's beyond the scope of this assignment. Our simple loop-plus-function is the right level of complexity here — and it's the version to understand first, before reaching for the fancier tools.
🔍 Try this: run the program for 1 100 and count the primes manually — there should be 25. Then try 1 1000 — there should be 168. Then swap the low and high inputs and verify the output is the same. Each of these is a small check that the implementation is correct for edge cases.
Frequently Asked Questions
1. Should I use one function or two?
The whole point of this assignment is to combine isPrime with a loop, so two functions (or one function plus a loop in main) is the right structure. If you wrote the primality test inline in the loop, you'd be duplicating logic that assignment 2 already solved — and you'd have no way to test the primality logic separately. Using isPrime as a building block is both cleaner and easier to test.
2. What if the range is huge — say, from 1 to 10,000,000?
The current approach would be slow — about 10 million calls to isPrime, each doing up to √10,000,000 ≈ 3163 divisions. That's roughly 30 billion operations, which would take minutes. For ranges this large, use the Sieve of Eratosthenes instead. It computes all primes up to 10 million in about a second. The tradeoff is memory — the sieve needs a boolean array of size high+1 — but for a range like this, that's only about 10 MB, which is nothing on a modern machine.
3. Why do I need to swap the low and high values?
Because users don't always enter data in the expected order. If you ask for "low high" and the user enters "100 1" (high then low), the loop condition n <= high would be immediately false (since n starts at 100, which is already greater than 1), and the program would print nothing. Swapping before the loop makes the program robust — it produces the correct output regardless of input order. This is a small but worthwhile defensive practice.
4. Why is 2 included in the output but 1 is not?
2 is prime (its only divisors are 1 and 2). 1 is not prime (it has only one divisor). The isPrime function handles this in its early checks: if (n <= 1) return 0; excludes 1, and if (n == 2 || n == 3) return 1; includes 2. So 2 appears in the output for ranges starting at or below 2, and 1 never does. The same applies to 0 — the n <= 1 check excludes it.
5. How many primes are there under N?
By the Prime Number Theorem, the number of primes ≤ N is approximately N / ln(N). For N = 100, that's about 21.7 — actual is 25. For N = 1000, about 145 — actual is 168. For N = 10,000, about 1086 — actual is 1229. The approximation gets better for larger N. For exact counts, you'd use the sieve or a precomputed table. Our program's count output gives the exact value for whatever range you enter.
6. Can I make the output prettier?
Absolutely. Some ideas: print primes in a fixed-width grid (10 per line), add commas between numbers, format the total as "Found 25 primes" — any of these would improve the output. The version shown here is minimalist, but it's a starting point. For a fancier version, you might print "11 13 17 19 23" with sorted alignment — that's just a matter of adding formatting in the printf call. The core algorithm stays the same.
💡 Tip: Once this works, try implementing the Sieve of Eratosthenes as a follow-up. The sieve is a different algorithm — a boolean array instead of repeated primality calls — but it produces the same result, faster for large ranges. Comparing the two is a great exercise in algorithm design and complexity analysis. Then you can honestly say you understand two different ways to find primes in a range, and why each is appropriate for different input sizes.