C++ STL algorithm, finding a prime number program example

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info: none

To do: Using the C++ list container and iterator to find a prime number in C++ programming

To show:  How to use the C++ list container and iterator algorithm in finding a prime number in C++ programming

 

// C++ STL algorithm, finding a prime number

#include <iostream>

#include <list>

#include <algorithm>

// for abs(), C++ wrapper

#include <cstdlib>

using namespace std;

 

// predicate, which returns whether an integer is a prime number

bool isPrimeNum(int number)

{

// ignore negative sign

number = abs(number);

// 0 and 1 are prime numbers

if(number == 0 || number == 1)

{

return true;

}

 

// find divisor that divides without a remainder

int divisor;

for(divisor = (number/2); (number%divisor) != 0; --divisor)

{;}

// if no divisor greater than 1 is found, it is a prime number

return divisor == 1;

}

 

int main(void)

{

// list container

list<int> lst1;

 

// insert elements from 24 to 30, constructing a list

for(int i=10; i<=20; ++i)

lst1.push_back(i);

 

// list iterator to search for prime number

list<int>::iterator pos;

 

// printing the data

cout<<"The list lst1 data: ";

for(pos=lst1.begin(); pos!=lst1.end(); pos++)

cout<<*pos<<" ";

cout<<endl<<endl;

// some operation

pos = find_if(lst1.begin(), lst1.end(), // range

isPrimeNum); // predicate

// print the result

if(pos != lst1.end())

{

// found

cout<<*pos<<" is the first prime number found"<<endl;

}

else {

// not found

cout<<"no prime number found"<<endl;

}

return 0;

}

 

Output examples:

 

The list lst1 data: 10 11 12 13 14 15 16 17 18 19 20

11 is the first prime number found

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index