SHOW:
|
|
- or go back to the newest paste.
1 | - | #include <cmath> |
1 | + | #include <cstdint> |
2 | #include <chrono> | |
3 | #include <iostream> | |
4 | #include <atomic> | |
5 | - | int SigmaN(int n) |
5 | + | #include <thread> |
6 | #include <vector> | |
7 | - | return n * (n + 1) / 2; |
7 | + | |
8 | using namespace std; | |
9 | using namespace std::chrono; | |
10 | typedef duration<float> fsec; | |
11 | ||
12 | auto started = steady_clock::now(); | |
13 | atomic<int> counter = 0; | |
14 | ||
15 | inline int GetNumber() | |
16 | { | |
17 | return ++counter; | |
18 | } | |
19 | ||
20 | inline int64_t SigmaN(int64_t n) // to avoid overflow | |
21 | { | |
22 | return n * (n + 1) >> 1; | |
23 | } | |
24 | ||
25 | int SerialN(int n) | |
26 | { | |
27 | for (int i = 0; i < n ; ++i) | |
28 | { | |
29 | if (SigmaN(i) == n) | |
30 | return i; | |
31 | } | |
32 | ||
33 | return 0; | |
34 | - | using namespace std; |
34 | + | |
35 | - | using namespace std::chrono; |
35 | + | |
36 | - | |
36 | + | |
37 | - | typedef duration<float> fsec; |
37 | + | |
38 | if (n < 0) | |
39 | - | int number = 1; |
39 | + | |
40 | ||
41 | - | auto started = steady_clock::now(); |
41 | + | |
42 | ||
43 | - | while (0 < number) // until overflow |
43 | + | |
44 | root : 0; | |
45 | } | |
46 | ||
47 | void Work() | |
48 | { | |
49 | while (true) | |
50 | { | |
51 | int number = GetNumber(); | |
52 | ||
53 | - | printf("%d = %d^2 = sum(1..%d)\n", number, root, last_of_serial); |
53 | + | if (0 > number) |
54 | break; // until overflow | |
55 | ||
56 | - | auto elapsed = duration_cast<fsec>(steady_clock::now() - started); |
56 | + | |
57 | - | printf("%0.2f sec\n", elapsed.count()); |
57 | + | |
58 | if (0 < root) | |
59 | { | |
60 | auto last_of_serial = SerialN(number); | |
61 | - | ++number; |
61 | + | |
62 | if (0 < last_of_serial) | |
63 | { | |
64 | //print elapsed time | |
65 | printf("%d = %d^2 = sum(1..%d)\n %0.2f sec\n", | |
66 | number, root, last_of_serial, | |
67 | duration_cast<fsec>(steady_clock::now() - started).count() | |
68 | ); | |
69 | } | |
70 | } | |
71 | }//while | |
72 | } | |
73 | ||
74 | ||
75 | ||
76 | int main (void) | |
77 | { | |
78 | const size_t sizeofThread = 9; | |
79 | ||
80 | vector<thread> workers; | |
81 | ||
82 | for (int i = 0; i < sizeofThread; ++i) | |
83 | { | |
84 | workers.push_back(thread(Work)); | |
85 | } | |
86 | ||
87 | for (auto& t : workers) | |
88 | t.join(); | |
89 | } |