1- #include <mpi.h>
2- #include <stdio.h>
3- #include <math.h>
1+ #include <mpi.h> // import MPI header
2+ #include <stdio.h> // needed for printf
3+ #include <math.h> // needed for sqrt
44
5- #define DATA_SIZE 1024
5+ #define DATA_SIZE 1024 // let's count the primes among the first 1024 numbers
66
77int main (int argc , char * argv []) {
8- int sent [DATA_SIZE ], recv [DATA_SIZE ];
8+ int send [DATA_SIZE ], recv [DATA_SIZE ];
99 int rank , size , count , root , res , i , j ;
1010 MPI_Status status ;
1111
12- MPI_Init (& argc , & argv );
13- MPI_Comm_rank (MPI_COMM_WORLD , & rank );
14- MPI_Comm_size (MPI_COMM_WORLD , & size );
12+ MPI_Init (& argc , & argv ); // initialize MPI
13+ MPI_Comm_rank (MPI_COMM_WORLD , & rank ); // get own rank/ID
14+ MPI_Comm_size (MPI_COMM_WORLD , & size ); // get total number of processes
1515
16- if (rank == 0 ) { //generate data if root
17- for (i = DATA_SIZE ; (-- i )>=0 ; ) { sent [i ] = (i + 1 ); }
16+ if (rank == 0 ) { //generate data (i.e., the first DATA_SIZE natural numbers) if root
17+ for (i = DATA_SIZE ; (-- i )>=0 ; ) { send [i ] = (i + 1 ); }
1818 }
1919
20- count = (DATA_SIZE / size );
21- MPI_Scatter (sent , count , MPI_INT , recv , count , MPI_INT , 0 , MPI_COMM_WORLD );
20+ count = (DATA_SIZE / size ); // divide the data among _all_ processes
21+ // scatter: if rank=0, send data (and get own share); otherwise: receive data
22+ MPI_Scatter (send , count , MPI_INT , recv , count , MPI_INT , 0 , MPI_COMM_WORLD );
2223
23- // each node now processes its share of data
24+ // each node now processes its share of the numbers
2425 res = count ; //here: count how many prime numbers are contained in the array
25- outer : for (i = count ; (-- i ) >= 0 ; ) {
26- for (j = ((int )(sqrt (recv [i ]))|1 ); j > 1 ; j -- ) {
27- if ((recv [i ] % j ) == 0 ) {
28- res -- ;
29- break ; }
26+ for (i = count ; (-- i ) >= 0 ; ) { //j: test all odd numbers 1<j<sqrt(j)|1
27+ for (j = ((int )(sqrt (recv [i ]))|1 ); j > 1 ; j -= 2 ) {
28+ if ((recv [i ] % j ) == 0 ) { // if a number can be divided by j
29+ res -- ; // it cannot be a prime number, reduce number of primes
30+ break ; } // break inner loop to test next number
3031 }
3132 }
3233 printf ("Process %d discovered %d primes in the numbers from %d to %d.\n" , rank , res , recv [0 ], recv [count - 1 ]);
3334
35+ // reduce: each node takes results, applies operator MPI_SUM locally, sends result to root, where MPI_SUM is
36+ // applied again. (here: locally summing up does not matter, as only 1 number). The final result is returned.
3437 MPI_Reduce (& res , recv , 1 , MPI_INT , MPI_SUM , 0 , MPI_COMM_WORLD );
3538 if (rank == 0 ) { //if root, print
3639 printf ("The total number of primes in the first %d natural numbers is %d.\n" , (count * size ), recv [0 ]);
3740 }
3841
39- MPI_Finalize ();
42+ MPI_Finalize (); // shut down MPI
4043 return 0 ;
4144}
0 commit comments