Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "is_prime.h"
- #include <cmath>
- #include <algorithm>
- #include <thread>
- static std::atomic<bool> is_prime = true;
- void IsDividedBySmth(size_t x, size_t begin, size_t end, size_t num_threads) {
- if (x <= 1) {
- is_prime.store(false);
- return;
- }
- for (size_t i = begin; i < end; i += num_threads) {
- if (x % i == 0) {
- is_prime.store(false);
- }
- if (!is_prime.load()) {
- return;
- }
- }
- }
- bool IsPrime(uint64_t x) {
- is_prime.store(true);
- unsigned begin = 2;
- unsigned end = static_cast<uint64_t>(sqrt(x)) + 1;
- unsigned num_threads = std::thread::hardware_concurrency();
- std::vector<std::thread> workers;
- for (size_t i = 0; i < num_threads; ++i) {
- workers.emplace_back(IsDividedBySmth, x, begin + i, end, num_threads);
- }
- for (std::thread& thread : workers) {
- thread.join();
- }
- return is_prime;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement