#include #include #include #include #include #include int main(int argc, char *argv[]) { if (argc != 3) { std::cerr << "Please, give the number of elements and number of threads in " "the command line.\n"; return 1; } int const N = std::stoi(argv[1]); if (N <= 0) { std::cerr << "Number of elements must be positive.\n"; return 2; } int const num_threads = std::stoi(argv[2]); if (num_threads <= 0) { std::cerr << "Number of threads must be positive.\n"; return 2; } // Create an array from 0 to N-1. std::vector array(N); std::iota(begin(array), end(array), 0); std::int64_t sum = 0; // A function to sum part of the array in the variable sum auto part_sum = [&sum, &array = std::as_const(array), num_threads](int tid) { for (size_t j = tid; j < array.size(); j += num_threads) { sum += array[j]; } }; std::vector threads; for (int i = 0; i < num_threads; ++i) { threads.emplace_back(part_sum, i); } for (auto &thd : threads) { thd.join(); } std::int64_t n64 = N; if (sum == n64 * (n64 - 1) / 2) { std::cout << "Nice, I can sum!" << std::endl; } else { std::cout << "Back to school!" << std::endl; } return 0; }