The Wayback Machine - https://web.archive.org/web/20240204103950/https://www.geeksforgeeks.org/c-cpp-program-to-find-prime-numbers-between-given-range/
Open In App
Related Articles

C/C++ Program to find Prime Numbers between given range

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Given two numbers L and R, the task is to find the prime numbers between L and R.

Examples:

Input: L = 1, R = 10
Output: 2 3 5 7
Explanation:
Prime number between the 1 and 10 are 2, 3, 5, and 7 

Input: L = 30, R = 40
Output: 31 37 

 

Approach 1:

The idea is to iterate from in the range [L, R] and check if any number in the given range is prime or not. If yes then print that number and check for the next number till we iterate all the numbers.

Below is the implementation of the above approach:

C




// C program to find the prime numbers
// between a given interval
#include <stdio.h>
 
// Function for print prime
// number in given range
void primeInRange(int L, int R)
{
    int i, j, flag;
 
    // Traverse each number in the
    // interval with the help of for loop
    for (i = L; i <= R; 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;
 
        // Iterate to check if i is prime
        // or not
        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)
            printf("%d ", i);
    }
}
 
// Driver Code
int main()
{
    // Given Range
    int L = 1;
    int R = 10;
 
    // Function Call
    primeInRange(L, R);
 
    return 0;
}


C++




// C++ program to find the prime numbers
// between a given interval
#include <bits/stdc++.h>
using namespace std;
 
// Function for print prime
// number in given range
void primeInRange(int L, int R)
{
    int flag;
 
    // Traverse each number in the
    // interval with the help of for loop
    for (int i = L; i <= R; 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;
 
        // Iterate to check if i is prime
        // or not
        for (int 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 << " ";
    }
}
 
// Driver Code
int main()
{
    // Given Range
    int L = 1;
    int R = 10;
 
    // Function Call
    primeInRange(L, R);
 
    return 0;
}


Output

2 3 5 7 

Time Complexity: O((R-L)*N), where N is the number, and L and R are the given range.
Auxiliary Space: O(1)

Approach 2: (Optimized Approach)

An optimized approach of the above is to check until square root of each value instead of half. We also don’t check even numbers.

Approach:

The approach behind this solution is:

  1. We first print 2 if 2 is in range as 2 is the only even prime number.
  2. Then we iterate all the odd numbers only.
  3. In every iteration we check and print if the number is prime or not using isPrime function.
  4. In isPrime function:
    • We will first deal with a few numbers such as 1, 2, 3 in a case.
    • Then we deal with the numbers which are divisible by 2 and 3 in a separate case.
    • For remaining numbers:
      • Iterate from 5 to sqrt(n) and check for each iteration whether (that value) or (that value + 2) divides n or not.
        • If we find any number that divides, then we return false.
      • Again increment the value by 6 [because any prime can be expressed as 6n+1 or 6n-1]. 
    • If any number can’t divide the number, then we return true.

Below is the implementation of the above approach:

C




// C program to find the prime numbers
// between a given interval
#include <stdbool.h>
#include <stdio.h>
 
// Function check whether a number
// is prime or not
bool isPrime(int n)
{
    // Check if n=2 or n=3
    if (n == 2 || n == 3)
        return true;
    // Check whether n is divisible by 2 or 3
    if (n % 2 == 0 || n % 3 == 0)
        return false;
 
    // Check from 5 to square root of n
    // Iterate i by (i+6)
    for (int i = 5; i * i <= n; i = i + 6)
        if (n % i == 0 || n % (i + 2) == 0)
            return false;
 
    return true;
}
 
// Function for print prime
// number in given range
void primeInRange(int L, int R)
{
 
    // Skip 0 and 1 as they are
    // neither prime nor composite
    // and also if 2 is in range
    // then print it
    if (R >= 2 && L <= 2) {
        printf("2 ");
        L = 3;
    }
 
    // Making sure that L is odd before
    // beginning the loop
    if (L % 2 == 0)
        L++;
 
    // NOTE : We traverse through
    // odd numbers only
    for (int i = L; i <= R; i += 2) {
 
        // If number is prime print it
        if (isPrime(i))
            printf("%d ", i);
    }
}
 
// Driver code
int main()
{
    // Given Range
    int L = 1;
    int R = 10;
 
    // Function Call
    primeInRange(L, R);
 
    return 0;
}
 
// This code is contributed by Susobhan Akhuli


C++




// C++ program to find the prime numbers
// between a given interval
#include <bits/stdc++.h>
using namespace std;
 
// Function check whether a number
// is prime or not
bool isPrime(int n)
{
    // Check if n=2 or n=3
    if (n == 2 || n == 3)
        return true;
    // Check whether n is divisible by 2 or 3
    if (n % 2 == 0 || n % 3 == 0)
        return false;
 
    // Check from 5 to square root of n
    // Iterate i by (i+6)
    for (int i = 5; i * i <= n; i = i + 6)
        if (n % i == 0 || n % (i + 2) == 0)
            return false;
 
    return true;
}
 
// Function for print prime
// number in given range
void primeInRange(int L, int R)
{
 
    // Skip 0 and 1 as they are
    // neither prime nor composite
    // and also if 2 is in range
    // then print it
    if (R >= 2 && L <= 2) {
        cout << "2 ";
        L = 3;
    }
 
    // Making sure that L is odd before
    // beginning the loop
    if (L % 2 == 0)
        L++;
 
    // NOTE : We traverse through
    // odd numbers only
    for (int i = L; i <= R; i += 2) {
 
        // If number is prime print it
        if (isPrime(i))
            cout << i << " ";
    }
}
 
// Driver code
int main()
{
    // Given Range
    int L = 1;
    int R = 10;
 
    // Function Call
    primeInRange(L, R);
 
    return 0;
}
 
// This code is contributed by Susobhan Akhuli


Output

2 3 5 7 

Time Complexity: O((R-L)*sqrt(N)), where N is the number, and L and R are the given range.
Auxiliary Space: O(1)

Approach 3:

An alternative approach to implement the same code would be to use a sieve algorithm. A sieve algorithm starts by creating a list of all the numbers in the desired range and then crossing out the multiples of each prime number. The resulting list will contain only the prime numbers.

C




#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
 
bool* prime;
 
void sieve(int x, int y)
{
    prime = calloc((y + 1), sizeof(bool));
    for (int i = 2; i <= y; i++) {
        prime[i] = true;
    }
    for (int i = 2; i * i <= y; i++) {
        if (prime[i])
            for (int j = i * i; j <= y; j += i) {
                prime[j] = false;
            }
    }
}
 
int* allPrime(int l, int r, int* size)
{
    int count = 0;
    for (int i = l; i <= r; i++) {
        if (prime[i]) {
            count++;
        }
    }
    int* result = malloc(count * sizeof(int));
    int j = 0;
    for (int i = l; i <= r; i++) {
        if (prime[i]) {
            result[j++] = i;
        }
    }
    *size = count;
    return result;
}
 
int main()
{
    int starting_range = 5;
    int ending_range = 100;
    sieve(starting_range, ending_range);
 
    int size;
    int* result
        = allPrime(starting_range, ending_range, &size;);
 
    if (size == 0) {
        printf("There are no prime numbers in this range\n");
    }
    else {
        printf("The prime numbers in this range are: ");
        for (int i = 0; i < size; i++) {
            printf("%d ", result[i]);
        }
        printf("\n");
    }
    free(prime);
    free(result);
    return 0;
}


C++




#include <bits/stdc++.h>
using namespace std;
 
vector<bool> prime;
 
void sieve(int x, int y)
{
 
    prime.resize(y + 1, true);
    prime[1] = false;
 
    for (int i = 2; i * i <= y; i++) {
        if (prime[i])
            for (int j = i * i; j <= y; j += i) {
                prime[j] = false;
            }
    }
}
 
vector<int> allPrime(int l, int r)
{
    vector<int> result;
    for (int i = l; i <= r; i++) {
        if (prime[i]) {
            result.push_back(i);
        }
    }
 
    return result;
}
 
int main()
{
    int starting_range = 5;
    int ending_range = 100;
 
    sieve(starting_range, ending_range);
 
    vector<int> result
        = allPrime(starting_range, ending_range);
 
    if (result.empty()) {
        cout << "There are no prime numbers in this range"
             << endl;
    }
    else {
        cout << "The prime numbers in this range are: ";
        for (int n : result) {
            cout << n << " ";
        }
        cout << endl;
    }
    return 0;
}


Output

The prime numbers in this range are: 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 

Time Complexity : O(n log(log(n))
Auxiliary Space: (R-l), where R and l are the starting and ending ranges. 


Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!


Last Updated : 17 May, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads
Complete Tutorials