Primes in Range
Program to find all prime numbers in a given range
C++ Primes in Range Program
This program helps you to learn the fundamental structure and syntax of C++ programming.
#include <iostream>
#include <cmath>
using namespace std;
bool isPrime(int n) {
if (n <= 1) return false;
for (int i = 2; i <= sqrt(n); i++) {
if (n % i == 0) return false;
}
return true;
}
int main() {
int start, end;
cout << "Enter start of range: ";
cin >> start;
cout << "Enter end of range: ";
cin >> end;
cout << "Prime numbers between " << start << " and " << end << " are: ";
for (int i = start; i <= end; i++) {
if (isPrime(i)) {
cout << i << " ";
}
}
cout << endl;
return 0;
}Enter start of range: 10 Enter end of range: 30 Prime numbers between 10 and 30 are: 11 13 17 19 23 29
Understanding Primes in Range
This program finds all prime numbers within a given range. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. This program demonstrates function creation, nested loops, mathematical optimization, and efficient prime checking algorithms.
---
1. What is a Prime Number?
A prime number is a natural number greater than 1 that:
Examples of prime numbers:
Examples of non-prime (composite) numbers:
Special cases:
Applications:
---
2. Header Files Used
#include <iostream>
cout for output and cin for input#include <cmath>
sqrt() function---
3. The isPrime() Helper Function
bool isPrime(int n) {
if (n <= 1) return false;
for (int i = 2; i <= sqrt(n); i++) {
if (n % i == 0) return false;
}
}
return true;Why use a helper function?
Function breakdown:
Step 1: Check for edge cases
if (n <= 1) return false;
false immediately for invalid inputsStep 2: Check divisibility from 2 to √n
for (int i = 2; i <= sqrt(n); i++)
key optimization
Why check only up to √n?
Step 3: Check if i divides n
if (n % i == 0) return false;
false immediatelyStep 4: If no divisors found
return true;
---
4. Understanding the Square Root Optimization
Naive approach (checking all numbers from 2 to n-1):
Optimized approach (checking up to √n):
-
Much faster!
Example: Checking if 97 is prime
Naive:
Check 2, 3, 4, 5, ..., 96 (95 checks)
Optimized:
Check 2, 3, 4, 5, 6, 7, 8, 9, 10 (9 checks)
---
5. Main Function - Declaring Variables
int start, end;
start → beginning of the rangeend → end of the rangeExample:
---
6. Taking Input From User
cin >> start;
cin >> end;
Example:
10
and
30
start = 10, end = 30---
7. Displaying Range Header
This prints:
Output:
Prime numbers between 10 and 30 are:
---
8. Iterating Through the Range
for (int i = start; i <= end; i++)
This loop goes through each number in the range:
start (10)i <= end (30)i by 1 each iterationIterations:
---
9. Checking and Printing Prime Numbers
if (isPrime(i))
cout << i << " ";
For each number in the range:
isPrime(i) to check if it's primeisPrime(i) returns true, print the numberStep-by-step execution (range 10-30):
i = 10:
isPrime(10) → checks 2, 3, ... up to √10 ≈ 3not prime
❌
i = 11:
isPrime(11) → checks 2, 3, ... up to √11 ≈ 3prime
✅ → Print "11 "
i = 12:
not prime
❌
i = 13:
prime
✅ → Print "13 "
... and so on ...
Final output:
"11 13 17 19 23 29 "
---
10. Complete Example Walkthrough
Input:
start = 10, end = 30
Checking each number:
Not prime
Prime
✅
Not prime
Prime
✅
Not prime
Not prime
Not prime
Prime
✅
Not prime
Prime
✅
Not prime
Not prime
Not prime
Prime
✅
Not prime
Not prime
Not prime
Not prime
Not prime
Prime
✅
Not prime
Result:
11, 13, 17, 19, 23, 29
---
11. Why This Approach is Efficient
For range 10 to 30:
Alternative (naive prime checking):
Our approach is much faster, especially for larger ranges.
---
12. Further Optimizations (Advanced)
Sieve of Eratosthenes:
Our approach is good for:
---
13. Edge Cases
Case 1: Range includes 1 or 0
isPrime(1) returns false (handled in function)isPrime(0) returns falseCase 2: Range includes 2
Case 3: start > end
Case 4: Negative numbers
isPrime() returns false for n <= 1---
Summary
isPrime() checks if a number is primeThis program teaches:
Mastering prime number algorithms helps in:
Prime numbers are fundamental in mathematics and computer science, and understanding how to efficiently check for them is a crucial programming skill.
Let us now understand every line and the components of the above program.
Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.
Practical Learning Notes for Primes in Range
This C++ program is part of the "Loop Programs" topic and is designed to help you build real problem-solving confidence, not just memorize syntax. Start by understanding the goal of the program in plain language, then trace the logic line by line with a custom input of your own. Once you can predict the output before running the code, your understanding becomes much stronger.
A reliable practice pattern is to run the original version first, then modify only one condition or variable at a time. Observe how that single change affects control flow and output. This deliberate style helps you understand loops, conditions, and data movement much faster than copying full solutions repeatedly.
For interview preparation, explain this solution in three layers: the high-level approach, the step-by-step execution, and the time-space tradeoff. If you can teach these three layers clearly, you are ready to solve close variations of this problem under time pressure.