Program to print prime numbers in a given range using C++ STL

C++Server Side ProgrammingProgramming

In this tutorial, we will be discussing a program to print prime numbers for a given range of numbers using the C++ Standard Template Library.

In this, we will be given two numbers say a and b. The task is to print all the coming prime numbers in this range. For this, we will be using the Sieve of Eratosthenes method by running it as a subroutine. Simultaneously we will be storing all the prime numbers in a vector and finally printing them all.

Example

#include<bits/stdc++.h>
using namespace std;
typedef unsigned long long int unll;
vector<unll> eratosthemes(unll n){
   vector<bool> prime_num(n+1,true);
   prime_num[0] = false;
   prime_num[1] = false;
   int m = sqrt(n);
   for (unll p=2; p<=m; p++){
      if (prime_num[p]){
         for (unll i=p*2; i<=n; i += p)
            prime_num[i] = false;
      }
   }
   vector<unll< elements;
   for (int i=0;i<n;i++)
   if (prime_num[i])
      elements.push_back(i);
   return elements;
}
bool check_zero(unll i){
   return i == 0;
}
vector<unll> sieve_range(unll start,unll end){
   vector<unll> s1 = eratosthemes(start);
   vector<unll> s2 = eratosthemes(end);
   vector<unll> elements(end-start);
   set_difference(s2.begin(), s2.end(), s1.begin(),
   s2.end(), elements.begin());
   vector<unll>::iterator itr =
   remove_if(elements.begin(),elements.end(),check_zero);
   elements.resize(itr-elements.begin());
   return elements;
}
int main(void){
   unll start = 10;
   unll end = 90;
   vector<unll> elements = sieve_range(start,end);
   for (auto i:elements)
   cout<<i<<' ';
   return 0;
}

Output

11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89
raja
Published on 01-Nov-2019 06:36:49
Advertisements