Advertisement
Guest User

Untitled

a guest
Apr 10th, 2020
169
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.83 KB | None | 0 0
  1. #include <iostream>
  2. #include <stdio.h>
  3. #include <math.h>
  4. #include <thread>
  5. #include <vector>
  6. #include <chrono>
  7. #include <algorithm>
  8.  
  9.  
  10.  
  11. #define thread_num 4
  12. #define N 2048
  13.  
  14. using namespace std;
  15.  
  16. static unsigned char color[N][N][3];
  17.  
  18. chrono::duration<double> elapsed_seconds;
  19.  
  20. int ulam_get_map(int x, int y, int n)
  21. {
  22.     x -= (n - 1) / 2;
  23.     y -= n / 2;
  24.  
  25.     int mx = abs(x), my = abs(y);
  26.     int l = 2 * max(mx, my);
  27.     int d = y >= x ? l * 3 + x + y : l - x - y;
  28.  
  29.     return pow(l - 1, 2) + d;
  30. }
  31.  
  32. int isprime(int n)
  33. {
  34.     int p;
  35.  
  36.     for (p = 2; p * p <= n; p++)
  37.         if (n % p == 0) return 0;
  38.  
  39.     return n > 2;
  40. }
  41.  
  42. int main() {
  43.     FILE* fp;
  44.     char const* filename = "ulam.ppm";
  45.     char const* comment = "# ";
  46.  
  47.     int i, start_width, stop_width, start_height, stop_height;
  48.  
  49.     vector<thread> workers;
  50.  
  51.     for (i = 0; i < thread_num; i++)
  52.     {
  53.         start_width = (i % 2) * N / (thread_num / 2);
  54.         stop_width = start_width + N / 2;
  55.         start_height = floor(i / 2) * N / (thread_num / 2);
  56.         stop_height = start_height + N / 2;
  57.  
  58.         workers.push_back(thread([start_width, stop_width, start_height, stop_height]()
  59.             {
  60.                 chrono::system_clock::time_point start = chrono::system_clock::now();
  61.                 int i, j, k;
  62.                 for (j = start_width; j < stop_width; j++)
  63.                     for (k = start_height; k < stop_height; k++)
  64.                         if (isprime(ulam_get_map(k, j, N)))
  65.                             for (i = 0; i < 3; i++)
  66.                                 color[j][k][i] = 255;
  67.                 chrono::system_clock::time_point end = chrono::system_clock::now();
  68.                 elapsed_seconds += end - start;
  69.             }));
  70.     }
  71.  
  72.     for_each(workers.begin(), workers.end(), [](thread& t)
  73.         {
  74.             t.join();
  75.         });
  76.  
  77.     fp = fopen(filename, "wb");
  78.     fprintf(fp, "P6\n %s\n %d\n %d\n %d\n", comment, N, N, 255);
  79.     fwrite(color, 1, 3 * N * N, fp);
  80.     fclose(fp);
  81.  
  82.     cout << "elapsed time ulama's spiral: " << elapsed_seconds.count() << '\n';
  83.  
  84.     return 0;
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement