Skip to content

Instantly share code, notes, and snippets.

@SandSnip3r
Created May 2, 2017 17:41
Show Gist options
  • Save SandSnip3r/489ba62ea7467d9ac2d0724c6756625d to your computer and use it in GitHub Desktop.
Save SandSnip3r/489ba62ea7467d9ac2d0724c6756625d to your computer and use it in GitHub Desktop.
#include <atomic>
#include <cmath>
#include <iostream>
#include <thread>
#include <vector>
using namespace std;
bool isPrime(uint64_t num) {
if (num < 2) {
return false;
}
if (num <= 3) {
return true;
}
if (num%2 == 0) {
return false;
}
for (uint64_t i=3, sqRoot=sqrt(num); i<=sqRoot; i+=2) {
if (num % i == 0) {
return false;
}
}
return true;
}
void countPrimes(uint64_t startNum, uint64_t endNum, atomic<uint64_t> &count) {
for (auto i=startNum; i<=endNum; ++i) {
if (isPrime(i)) {
++count;
}
}
}
uint64_t howManyPrimesInRange(const uint64_t startRange, const uint64_t endRange) {
auto numOfNums = (endRange-startRange)+1;
const auto HARDWARE_THREADS = thread::hardware_concurrency();
const auto NUM_OF_THREADS = (numOfNums < HARDWARE_THREADS ? numOfNums : HARDWARE_THREADS);
vector<thread> primeCountingThreads;
primeCountingThreads.reserve(NUM_OF_THREADS);
atomic<uint64_t> primeCount{0};
for (auto i=0; i<NUM_OF_THREADS; ++i) {
uint64_t startNum = startRange + (static_cast<float>(numOfNums)/NUM_OF_THREADS)*i;
uint64_t endNum = startRange + (static_cast<float>(numOfNums)/NUM_OF_THREADS)*(i+1)-1;
primeCountingThreads.emplace_back(countPrimes, startNum, endNum, std::ref(primeCount));
}
for (auto &thr : primeCountingThreads) {
thr.join();
}
return primeCount;
}
int main() {
const uint64_t MIN_NUMBER{2}, MAX_NUMBER{1000003};
cout << howManyPrimesInRange(MIN_NUMBER, MAX_NUMBER) << '\n';
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment