Created
June 12, 2023 20:14
-
-
Save NuclearPhoenixx/d6b14062c814568d5e70754927cfae51 to your computer and use it in GitHub Desktop.
Classic sieve of Eratosthenes algorithm that essentially eliminates multiples of a prime number bigger than the candidate itself while stepping through every non-eliminated number.
This file contains hidden or 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
/* | |
* Classic Sieve of Eratosthenes algorithm to search primes. | |
* | |
* Written by Phoenix1747, 2020-11-10. | |
*/ | |
#include <iostream> | |
#include <vector> | |
using namespace std; | |
int main() { | |
unsigned long long int n; | |
cout << " :: Upper limit for search: "; | |
cin >> n; | |
if(!cin){ | |
cout << "Number must be a postive integer!" << endl; | |
return 1; | |
} | |
vector<unsigned long long int> found; | |
vector<bool> prim(n,true); | |
for(size_t num = 2; num <= n; num++){ //main algorithm | |
if(!prim[num]) continue; | |
found.push_back(num); | |
for(size_t i = 1; i*num <= n; i++) prim[i*num] = false; | |
} | |
cout << "\nPrimes found: "; | |
for(auto &prime:found) cout << prime << ","; | |
cout << "\n\nSearch ended successfully. Found [" << found.size() << "] prime numbers!" << endl; | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment