Advertisement
Guest User

Untitled

a guest
Feb 20th, 2020
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.01 KB | None | 0 0
  1. #include "is_prime.h"
  2. #include <cmath>
  3. #include <algorithm>
  4. #include <atomic>
  5. #include <thread>
  6. #include <vector>
  7.  
  8. bool IsPrime(uint64_t x) {
  9.     if (x <= 1) {
  10.         return false;
  11.     }
  12.     uint16_t num_threads = 8;
  13.     if (x <= num_threads * 2) {
  14.         num_threads = 1;
  15.     }
  16.     std::atomic<bool> is_prime = true;
  17.     std::vector<std::thread> workers;
  18.     uint64_t lower_bound = 2, upper_bound = static_cast<uint64_t>(sqrt(x));
  19.     uint64_t from = 2, step = (upper_bound - lower_bound) / num_threads, to = from + step;
  20.     for (size_t i = 0; i < num_threads; ++i) {
  21.         workers.emplace_back([x, &is_prime, from, to] {
  22.             for (size_t j = from; j <= to && is_prime; ++j) {
  23.                 if (x % j == 0) {
  24.                     is_prime = false;
  25.                     return;
  26.                 }
  27.             }
  28.         });
  29.         from = to + 1;
  30.         to = std::min(from + step, upper_bound);
  31.     }
  32.     for (auto& worker : workers) {
  33.         worker.join();
  34.     }
  35.     return is_prime;
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement