Primes in Range

Program to find all prime numbers in a given range

C++Intermediate
C++
#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;
}

Output

Enter start of range: 10
Enter end of range: 30
Prime numbers between 10 and 30 are: 11 13 17 19 23 29

Primes in Range in C++

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.

Algorithm

  1. Create a helper function isPrime() to check if a number is prime
  2. Use square root optimization: only check divisors up to √n
  3. Iterate through the range
  4. For each number, check if it's prime using the helper function
  5. Print all prime numbers found

The Square Root Optimization

Key insight: If a number n is composite, it must have a divisor less than or equal to √n.

Why this works:

  • If n = a × b, at least one of a or b must be ≤ √n
  • If both were > √n, then a × b > n (contradiction)
  • So we only need to check divisors up to √n

Example:

  • To check if 17 is prime:
    • √17 ≈ 4.12
    • Check divisors: 2, 3, 4
    • None divide 17 → ## Prime ✅

Summary

  • Prime number has exactly two divisors: 1 and itself
  • Helper function isPrime() checks if a number is prime
  • Square root optimization: only check divisors up to √n
  • Iterate through range, check each number, print primes
  • This approach is efficient for small to medium ranges

This program teaches:

  • Function creation and usage
  • Mathematical optimization (square root trick)
  • Nested logic (loop calling function)
  • Efficient algorithm design
  • Number theory concepts