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.


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])
   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 =
   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;


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