Fakultas Ilmu Komputer UI

prime_mpi.c 1 KB
Newer Older
Ardhi Putra Pratama's avatar
Ardhi Putra Pratama committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <stdio.h>
#include "mpi.h"
#include <stdlib.h>
#include <assert.h>

int main(int argc, char *argv[]) {
  int lower,upper,total,i,j,isprime;
  int rank, size;
  int local_total = 0;
  int global_total = 0;
  double time_initial,time_current,time;

  MPI_Init(&argc, &argv);
  time_initial = MPI_Wtime();

  MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  MPI_Comm_size(MPI_COMM_WORLD, &size);

  local_total = 0;
  lower = 2;
  upper = 1234567;

  MPI_Bcast ( &upper, 1, MPI_INT, 0, MPI_COMM_WORLD );

  for (i = lower + rank; i<= upper; i=i+size) {
    isprime = 1;
    for ( j=2; j<i; j++) {
      if (i % j == 0) {
        isprime = 0;
        break;
      }
    }
    local_total+=isprime;
  }

  MPI_Reduce(&local_total,&global_total,1,MPI_INT,MPI_SUM,0,MPI_COMM_WORLD);

  time_current=MPI_Wtime();
  time = time_current - time_initial;

  if (rank == 0) {
    printf("Total Prime Numbers = %d\n",global_total);
    printf("ElapsedTime=%.3f\n",time);
  }

  MPI_Barrier(MPI_COMM_WORLD);
  MPI_Finalize();
  return 0;
}