fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <mpi.h>
  4.  
  5. using namespace std;
  6.  
  7. int main(int argc, char* argv[]) {
  8. MPI_Init(&argc, &argv);
  9.  
  10. int rank, size;
  11. MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  12. MPI_Comm_size(MPI_COMM_WORLD, &size);
  13.  
  14. // Check if number of processes is a power of 2 (valid hypercube)
  15. int dim = (int)log2(size);
  16. if (size != (1 << dim)) {
  17. if (rank == 0) {
  18. cerr << "Error: Number of processes must be a power of 2 for a hypercube." << endl;
  19. }
  20. MPI_Finalize();
  21. return 1;
  22. }
  23.  
  24. // Data to be broadcast (replace with your actual data)
  25. int data = 10;
  26.  
  27. // Broadcast loop (log2(size) iterations)
  28. for (int i = 0; i < dim; ++i) {
  29. // Partner selection based on binary representation of rank and i'th bit
  30. int partner = rank ^ (1 << i);
  31.  
  32. // Send data if current rank has a lower value in the i'th bit
  33. if ((rank >> i) & 1) {
  34. MPI_Send(&data, 1, MPI_INT, partner, 0, MPI_COMM_WORLD);
  35. } else if (rank != partner) { // Receive data if not the source
  36. MPI_Recv(&data, 1, MPI_INT, partner, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
  37. }
  38. }
  39.  
  40. // Print the received data on all processes
  41. cout << "Process " << rank << " received data: " << data << endl;
  42.  
  43. MPI_Finalize();
  44. return 0;
  45. }
Success #stdin #stdout #stderr 0.27s 40528KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Error: unexpected symbol in "using namespace"
Execution halted