Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Program to print prime numbers in a given range using C++ STL
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
#includeusing namespace std; typedef unsigned long long int unll; vector eratosthemes(unll n){ vector prime_num(n+1,true); prime_num[0] = false; prime_num[1] = false; int m = sqrt(n); for (unll p=2; p sieve_range(unll start,unll end){ vector s1 = eratosthemes(start); vector s2 = eratosthemes(end); vector elements(end-start); set_difference(s2.begin(), s2.end(), s1.begin(), s2.end(), elements.begin()); vector ::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 elements = sieve_range(start,end); for (auto i:elements) cout Output
11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89
Advertisements
