Created
September 21, 2011 14:02
-
-
Save GrAndSE/1232095 to your computer and use it in GitHub Desktop.
Example of prime numbers searching in C++ using list (with ptimizations)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <list> | |
#include <iostream> | |
#include "math.h" | |
using namespace std; | |
bool isPrime(int n, list<int> &primes) { | |
for (list<int>::iterator iter = primes.begin(); iter != primes.end(); ++iter) | |
if (*iter > (int) pow(n*1., 0.5) + 1) | |
return true; | |
else if (n % *iter == 0) | |
return false; | |
return true; | |
} | |
list<int> primes(int num) { | |
list<int> primes; | |
for (int i = 2; i < num; i++) | |
if (isPrime(i, primes)) | |
primes.push_back(i); | |
return primes; | |
} | |
int main() { | |
list<int> pr = primes(1000000); | |
cout << '['; | |
for (list<int>::iterator iter = pr.begin(); iter != pr.end(); ++iter) | |
cout << *iter << ','; | |
cout << ']' << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment