Advertisement
Guest User

Untitled

a guest
Feb 20th, 2020
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.27 KB | None | 0 0
  1. #include "is_prime.h"
  2. #include <cmath>
  3. #include <algorithm>
  4. #include <thread>
  5. #include <atomic>
  6. #include <vector>
  7. #include <iostream>
  8.  
  9. void CheckFunc(uint64_t x, std::atomic<uint64_t>& i, std::atomic<bool>& result) {
  10.     result.store(x % i != 0);
  11.     i.fetch_add(1);
  12. }
  13.  
  14. void CloseAllThreads(std::vector<std::thread>& threads) {
  15.     for (auto& this_thread : threads) {
  16.         if (this_thread.joinable()) {
  17.             this_thread.join();
  18.         }
  19.     }
  20. }
  21.  
  22. bool IsPrime(uint64_t x) {
  23.     if (x <= 1) {
  24.         return false;
  25.     }
  26.     uint64_t root = sqrt(x);
  27.     auto bound = std::min(root + 6, x);
  28.     std::atomic<uint64_t> i = 2ull;
  29.     std::atomic<bool> result = true;
  30.     std::vector<std::thread> threads(10);
  31.  
  32.     while (i.load() < bound && result.load()) {
  33.         for (auto &this_thread : threads) {
  34.             if (i.load() < bound) {
  35.                 this_thread = std::thread(CheckFunc, x, std::ref(i), std::ref(result));
  36.             } else {
  37.                 break;
  38.             }
  39.             if (!result.load()) {
  40.                 CloseAllThreads(threads);
  41.                 break;
  42.             }
  43.         }
  44.     }
  45.  
  46.     CloseAllThreads(threads);
  47.     std::cout << x << " - " << i.load() << "... " << result.load() << std::endl;
  48.     return result;
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement