Created
May 11, 2015 12:12
-
-
Save jperelli/8f30a8aa78cfec7d8cba to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
License: GNU GPLv2 | |
Authors: Julián Perelli | |
with ideas from http://people.sc.fsu.edu/~jburkardt/c_src/mpi/mpi.html | |
Organization: Sistemas Operativos Avanzados 2015 - UTN FRLP | |
Compile with: mpicc primos_mpi.c -o primos_mpi | |
Run with: mpirun -n 4 ./primos_mpi 100 | |
*/ | |
#include "mpi.h" | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <errno.h> | |
#include <string.h> | |
int contar_primos(int a, int b) { | |
/* Esta es una forma trivial (naive) de contar primos */ | |
int i; | |
int j; | |
int total; | |
int primo; | |
total = 0; | |
for ( i = a; i < b; i++ ) { | |
primo = 1; | |
for ( j = 2; j < i; j++ ) { | |
if ( ( i % j ) == 0 ) { | |
primo = 0; | |
break; | |
} | |
} | |
total = total + primo; | |
} | |
return total; | |
} | |
int main(int argc, char *argv[]) { | |
int max; | |
int id; | |
int ierr; | |
int p; | |
int primes; | |
int primes_part; | |
// Leer numero maximo, hasta el cual contar primos | |
if ( argc < 2 ) { | |
fprintf( stderr, "Uso: %s parametro_numerico\n", argv[0] ); | |
return 1; | |
} | |
errno = 0; | |
max = strtoull( argv[1], NULL, 10 ); | |
if ( errno ) { | |
fprintf( stderr, "%s: parametro %s: %s\n", argv[0], argv[1], strerror(errno) ); | |
return 2; | |
} | |
printf("Contando primos hasta el %i\n", max); | |
// Initialize MPI. | |
ierr = MPI_Init ( &argc, &argv ); | |
// Get the number of processes. | |
ierr = MPI_Comm_size ( MPI_COMM_WORLD, &p ); | |
// Determine this processes's rank. | |
ierr = MPI_Comm_rank ( MPI_COMM_WORLD, &id ); | |
primes_part = contar_primos( id*(max / p), id*((max / p)+1) ); | |
printf("llamando a contar_primos con %i, %i = %i\n", id*(max / p), (id+1)*((max / p)), primes_part ); | |
ierr = MPI_Reduce(&primes_part, &primes, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD); | |
if ( id == 0 ) { | |
printf("Hay %i primos hasta el %i\n", primes, max); | |
} | |
// End MPI. | |
ierr = MPI_Finalize(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment