Open In App

C++ Program To Find Prime Numbers Between Given Interval

Improve
Improve
Like Article
Like
Save
Share
Report

A prime number is defined as a natural number greater than 1 and is divisible by only 1 and itself. In other words, the prime number is a positive integer greater than 1 that has exactly two factors, 1 and the number itself. The first few prime numbers are 2, 3, 5, 7, 11, 13, 17, 19, 23 . . .

Note: 1 is not either prime or composite. The remaining numbers, except for 1, are classified as prime and composite numbers. 

Find Prime Numbers Between Given Interval

Given two numbers a and b as interval range, the task is to find the prime numbers in between this interval.

Examples: 

Input: a = 1, b = 10
Output: 2, 3, 5, 7
Input: a = 10, b = 20
Output: 11, 13, 17, 19

1. Using For Loop

In the below program, the range of numbers is taken as input and stored in the variables ‘a’ and ‘b’. Then using for-loop, the numbers between the interval of a and b are traversed. For each number in the for loop, it is checked if this number is prime or not. If found prime, print the number. Then the next number in the loop is checked, till all numbers are checked.

Below is the C++ program to implement the above approach:

C++




// C++ program to find the
// prime numbers between a
// given interval
#include <bits/stdc++.h>
using namespace std;
 
// Driver code
int main()
{
    // Declare the variables
    int a, b, i, j, flag;
 
    // Ask user to enter lower value
    // of interval
    cout << "Enter lower bound of the interval: ";
 
    // Take input
    cin >> a;
 
    // Ask user to enter upper value
    // of interval
    cout << "Enter upper bound of the interval: ";
 
    // Take input
    cin >> b;
 
    // Print display message
    cout << "Prime numbers between " << a << " and " << b
         << " are: ";
 
    // Traverse each number in the interval
    // with the help of for loop
    for (i = a; i <= b; i++) {
        // Skip 0 and 1 as they are
        // neither prime nor composite
        if (i == 1 || i == 0)
            continue;
 
        // flag variable to tell
        // if i is prime or not
        flag = 1;
 
        for (j = 2; j <= i / 2; ++j) {
            if (i % j == 0) {
                flag = 0;
                break;
            }
        }
 
        // flag = 1 means i is prime
        // and flag = 0 means i is not prime
        if (flag == 1)
            cout << i << " ";
    }
 
    return 0;
}


Output

Enter lower bound of the interval: 1
Enter upper bound of the interval: 10
Prime numbers between 1 and 10 are: 2 3 5 7 

The complexity of the above method

Time complexity: O((b-a)*(b/2)), a and b are the lower and upper limits.

Auxiliary space: O(1)

2. Optimized Solution

The idea is to use the fact that even numbers (except 2) are not primes.

Below is the C++ program to implement the above approach:

C++




// C++ program to find the prime numbers
// between a given interval
#include <bits/stdc++.h>
using namespace std;
 
// Driver code
int main()
{
    // Declare the variables
    int a, b, i, j;
 
    // Ask user to enter lower value of
    // interval please not interval < 0
    // cannot be prime numbers
    cout << "Enter lower bound of the interval: ";
 
    // Take input
    cin >> a;
 
    // Ask user to enter upper value
    // of interval
    cout << "Enter upper bound of the interval: ";
 
    // Take input
    cin >> b;
 
    // Print display message
    cout << "Prime numbers between " << a << " and " << b
         << " are: ";
 
    // Explicitly handling the cases
    // when a is less than 2 since 0
    // and 1 are not prime numbers
    if (a <= 2) {
        a = 2;
        if (b >= 2) {
            cout << a << " ";
            a++;
        }
    }
 
    // Making sure that a is odd before
    // beginning the loop
    if (a % 2 == 0)
        a++;
 
    // NOTE : We traverse through
    // odd numbers only
    for (i = a; i <= b; i = i + 2) {
        // flag variable to tell
        // if i is prime or not
        bool flag = 1;
 
        // We traverse till square root of j only.
        // (Largest possible value of prime factor)
        for (j = 2; j * j <= i; ++j) {
            if (i % j == 0) {
                flag = 0;
                break;
            }
        }
 
        // flag = 1 means i is prime
        // and flag = 0 means i is
        // not prime
        if (flag == 1) {
            if (i == 1)
                continue;
            else
                cout << i << " ";
        }
    }
 
    return 0;
}


Output:

Enter lower bound of the interval: 1
Enter upper bound of the interval: 10
Prime numbers between 1 and 10 are: 2 3 5 7

The complexity of the above method

Time complexity: O((b-a)*(sqrt(b))).

Auxiliary space: O(1).

3. Sieve of Eratosthenes Method

The sieve of Eratosthenes is one of the most efficient ways to find all primes smaller than N when N is smaller than 10 million or so.

Approach

  1. Create a boolean array prime[srt to n] and initialize all its entries as true.
  2. Mark prime[0] and prime[1] as false because they are not prime numbers.
  3. Starting from p = srt, for each prime number p less than or equal to the square root of n, mark all multiples of p greater than or equal to p*p as composite by setting prime[i] to false.
  4. Finally, print all prime numbers between srt and n.

Below is the C++ program to implement the above approach:

C++




// C++ program to find the prime numbers
// between a given interval using Sieve of Eratosthenes
#include <bits/stdc++.h>
using namespace std;
 
void SieveOfEratosthenes(int srt, int n)
{
    // Create a boolean array "prime[srt to n]" and
    // initialize all entries it as true. A value in
    // prime[i] will finally be false if i is Not a prime,
    // else true.
    bool prime[n + 2 - srt];
    memset(prime, true, sizeof(prime));
    prime[0] = false;
    prime[1] = false;
 
    for (int p = srt; p * p <= n; p++)
    {
        // If prime[p] is not changed, then it is a prime
        if (prime[p] == true)
        {
            // Update all multiples of p greater than or
            // equal to the square of it numbers which are
            // multiple of p and are less than p^2 are
            // already been marked.
            for (int i = p * p; i <= n; i += p)
                prime[i] = false;
        }
    }
 
    // Print all prime numbers
    for (int p = srt; p <= n; p++)
        if (prime[p])
            cout << p << " ";
}
 
// Driver Code
int main()
{
    int srt = 1;
    int end = 10;
    SieveOfEratosthenes(srt, end);
    return 0;
}


Output

2 3 5 7 

The complexity of the above method

Time Complexity: O(n*log(log(n))) as it iterates over all numbers from 2 to n and removes all the multiples of each prime number. In this code, the algorithm is applied only to a range [srt, n], which reduces the time complexity to O((n-srt+1)*log(log(n))) for the range [srt, n]. The loop for marking the multiples of each prime number iterates from p*p to n, which takes O((n-srt+1)*log(log(n))) time. Therefore, the overall time complexity of this code is O((n-srt+1)*log(log(n))).

Auxiliary Space: O(n), which is the size of the boolean array prime. However, the size of the array is reduced to n+2-srt, which is the size of the array required for the given range [srt, n]. Therefore, the auxiliary space complexity of the code is O(n-srt+1).



Last Updated : 28 Feb, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads