Program description:

Lab 6

Write an MPI program, countprimes which will count the number of prime numbers in the numbers from 1 to n inclusive where n is a long integer. The value for n which can be set in the program using a constant should be 50,000. Each process will test its share of the cases. Each process should print out any primes that it finds in a readable manner indicating which process found it and the actual prime. The master process should end with printing a total for the count of the number of primes and the total amount of time taken to find all the primes. Please follow the following instructions carefully before submitting your work: Before submission, make sure you clean up the directories so that no miscellaneous files are kept around in the submission.

Your code:

Make file

numprimes:	numprimes.c
		/usr/lib64/openmpi/bin/mpicc -O -o numprimes numprimes.c

		rm -f numprimes core *~

.c File

#include <stdio.h>
#include <unistd.h>
#include <mpi.h>

// Return 1 if 'i'th bit of 'n' is 1; 0 otherwise
#define EXTRACT_BIT(n,i) ((n&(1<<i))?1:0)
#define N 100

// Checks if number is prime
int check_prime (int id, long z) {
  long i;
  for(i = 2; i < z; i++){
	if(z % i == 0)
		return 0;
    printf ("%d) %d\n", id, z); //Prints the process number and the prime numbers that process found
    fflush (stdout);
    return 1;

int main (int argc, char *argv[]) 
  int count;            // Solutions found by this proc 
  int global_count;     // Total number of solutions
  int i;
  int id;               // Process rank
  int p;                // Number of processes
  char hostname[1024];
  long n = N;
  // OpenMPI
  MPI_Init (&argc, &argv);

  MPI_Comm_rank (MPI_COMM_WORLD, &id);
  MPI_Comm_size (MPI_COMM_WORLD, &p);

  hostname[1023] = '\0';
  gethostname(hostname, 1023);
  printf("MPI rank %d on host %s\n", id, hostname);

  // Goes through the numbers, checking if they are prime and if so, increasing count
  count = 0;
  for (i = id + 1; i < n; i += p)
    count += check_prime (id, i);

  MPI_Reduce (&count, &global_count, 1, MPI_INT, MPI_SUM, 0,

  if (!id) printf ("There are %d different solutions\n",
		   global_count); // Prints out total number of prime numbers found
  return 0;

All the assignments will be posted. Subscribe for more! :)