fork download
  1. #include <iostream>
  2. #include <fstream>
  3. #include <vector>
  4. #include <mpi.h>
  5.  
  6. // #define _NO_CXX11_AT_QUICK_EXIT
  7. // #include <cstdlib>
  8.  
  9. using namespace std;
  10.  
  11. // Function to read a large number from a file into a vector of digits
  12. void read_number(const string &filename, vector<int> &digits) {
  13. ifstream file(filename);
  14. int num_digits;
  15. file >> num_digits; // Read the number of digits
  16.  
  17. digits.resize(num_digits);
  18. for (int i = 0; i < num_digits; ++i) {
  19. file >> digits[i];
  20. }
  21. }
  22.  
  23. // Function to write the result to a file
  24. void write_result(const string &filename, const vector<int> &result) {
  25. ofstream file(filename);
  26. file << result.size() << endl; // Write the number of digits
  27. for (int digit : result) {
  28. file << digit << " ";
  29. }
  30. file << endl;
  31. }
  32.  
  33. int main(int argc, char* argv[]) {
  34. MPI_Init(&argc, &argv);
  35.  
  36. int rank, size;
  37. MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  38. MPI_Comm_size(MPI_COMM_WORLD, &size);
  39.  
  40. vector<int> num1_digits, num2_digits, result_digits;
  41. vector<int> local_num1, local_num2, local_result;
  42.  
  43. if (rank == 0) {
  44. // Process 0 reads the numbers from files
  45. read_number("Numar1.txt", num1_digits);
  46. read_number("Numar2.txt", num2_digits);
  47.  
  48. // Ensure both numbers have the same length by padding with zeros if necessary
  49. int max_size = max(num1_digits.size(), num2_digits.size());
  50. num1_digits.resize(max_size, 0);
  51. num2_digits.resize(max_size, 0);
  52.  
  53. result_digits.resize(max_size + 1, 0); // Result can be one digit larger
  54. }
  55.  
  56. // Scatter the digits across processes
  57. MPI_Scatter(num1_digits.data(), num1_digits.size() / size, MPI_INT,
  58. local_num1.data(), num1_digits.size() / size, MPI_INT, 0, MPI_COMM_WORLD);
  59. MPI_Scatter(num2_digits.data(), num2_digits.size() / size, MPI_INT,
  60. local_num2.data(), num2_digits.size() / size, MPI_INT, 0, MPI_COMM_WORLD);
  61.  
  62. // Perform local addition
  63. int carry = 0;
  64. for (int i = 0; i < local_num1.size(); ++i) {
  65. int sum = local_num1[i] + local_num2[i] + carry;
  66. local_result.push_back(sum % 10); // Store the last digit
  67. carry = sum / 10; // Carry for the next addition
  68. }
  69.  
  70. // Gather results back to process 0
  71. MPI_Gather(local_result.data(), local_result.size(), MPI_INT,
  72. result_digits.data(), local_result.size(), MPI_INT, 0, MPI_COMM_WORLD);
  73.  
  74. // Process 0 writes the result to the file
  75. if (rank == 0) {
  76. write_result("Numar3.txt", result_digits);
  77. }
  78.  
  79. MPI_Finalize();
  80. return 0;
  81. }
  82.  
Success #stdin #stdout #stderr 0.33s 40312KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Error: unexpected '/' in "/"
Execution halted