gpt-3.5-turbo-0125· openai
Suzhen/CodeChat
напиши на си на mpi: проходит соревнование между процессами в три круга. Количество…
- User
напиши на си на mpi: проходит соревнование между процессами в три круга. Количество процессов вводится командной строкой. На каждом круге процессы генерируют числа от 100 000 до 350 000 до тех пор, пока их сумма не достигнет 1 000 000. Необходимо вывести, сколько итераций ушло каждому потоку процессу на каждый круг, а также вывести среди них победителя и проигравшего, то есть тех, у кого в сумме наименьшее и наибольшее количество итераций соответственно.
- Assistant
#include <mpi.h> #include <iostream> #include <vector> #include <cstdlib> #include <ctime> int main(int argc, char** argv) { int rank, size; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); srand(time(NULL) + rank); int total_rounds = 3; int target_sum = 1000000; std::vector<int> iterations_per_round(total_rounds, 0); int current_sum = 0; int total_iterations = 0; for (int round = 0; round < total_rounds; ++round) { while (current_sum < target_sum) { int number = rand() % 250001 + 100000; // Generate number between 100000 and 350000 current_sum += number; ++iterations_per_round[round]; ++total_iterations; } current_sum = 0; } // Gather iterations from all processes std::vector<int> all_iterations(size * total_rounds); MPI_Gather(iterations_per_round.data(), total_rounds, MPI_INT, all_iterations.data(), total_rounds, MPI_INT, 0, MPI_COMM_WORLD); if (rank == 0) { std::vector<int> total_iterations_per_process(size, 0); for (int i = 0; i < size; ++i) { for (int j = 0; j < total_rounds; ++j) { total_iterations_per_process[i] += all_iterations[i * total_rounds + j]; } } int min_iterations = total_iterations_per_process[0]; int max_iterations = total_iterations_per_process[0]; int winner = 0; int loser = 0; for (int i = 0; i < size; ++i) { if (total_iterations_per_process[i] < min_iterations) { min_iterations = total_iterations_per_process[i]; winner = i; } if (total_iterations_per_process[i] > max_iterations) { max_iterations = total_iterations_per_process[i]; loser = i; } std::cout << "Process " << i << ":"; for (int j = 0; j < total_rounds; ++j) { std::cout << " Round " << j + 1 << ": " << all_iterations[i * total_rounds + j] << " iterations"; } std::cout << std::endl; } std::cout << "Winner: Process " << winner << " with " << min_iterations << " total iterations." << std::endl; std::cout << "Loser: Process " << loser << " with " << max_iterations << " total iterations." << std::endl; } MPI_Finalize(); return 0; }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.