Advertisement
TimSenin

Untitled

Nov 15th, 2022
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.95 KB | None | 0 0
  1. #include "is_prime.h"
  2. #include <cmath>
  3. #include <algorithm>
  4. #include <thread>
  5.  
  6. static std::atomic<bool> is_prime = true;
  7.  
  8. void IsDividedBySmth(size_t x, size_t begin, size_t end, size_t num_threads) {
  9.     if (x <= 1) {
  10.         is_prime.store(false);
  11.         return;
  12.     }
  13.     for (size_t i = begin; i < end; i += num_threads) {
  14.         if (x % i == 0) {
  15.             is_prime.store(false);
  16.         }
  17.         if (!is_prime.load()) {
  18.             return;
  19.         }
  20.     }
  21. }
  22.  
  23. bool IsPrime(uint64_t x) {
  24.     is_prime.store(true);
  25.  
  26.     unsigned begin = 2;
  27.     unsigned end = static_cast<uint64_t>(sqrt(x)) + 1;
  28.     unsigned num_threads = std::thread::hardware_concurrency();
  29.  
  30.     std::vector<std::thread> workers;
  31.     for (size_t i = 0; i < num_threads; ++i) {
  32.         workers.emplace_back(IsDividedBySmth, x, begin + i, end, num_threads);
  33.     }
  34.     for (std::thread& thread : workers) {
  35.         thread.join();
  36.     }
  37.  
  38.     return is_prime;
  39. }
  40.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement