Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "is_prime.h"
- #include <cmath>
- #include <algorithm>
- #include <atomic>
- #include <thread>
- #include <vector>
- bool IsPrime(uint64_t x) {
- if (x <= 1) {
- return false;
- }
- uint16_t num_threads = 8;
- if (x <= num_threads * 2) {
- num_threads = 1;
- }
- std::atomic<bool> is_prime = true;
- std::vector<std::thread> workers;
- uint64_t lower_bound = 2, upper_bound = static_cast<uint64_t>(sqrt(x));
- uint64_t from = 2, step = (upper_bound - lower_bound) / num_threads, to = from + step;
- for (size_t i = 0; i < num_threads; ++i) {
- workers.emplace_back([x, &is_prime, from, to] {
- for (size_t j = from; j <= to && is_prime; ++j) {
- if (x % j == 0) {
- is_prime = false;
- return;
- }
- }
- });
- from = to + 1;
- to = std::min(from + step, upper_bound);
- }
- for (auto& worker : workers) {
- worker.join();
- }
- return is_prime;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement