Skip to content

Instantly share code, notes, and snippets.

@giannisdaras
Created July 1, 2018 20:11
Show Gist options
  • Save giannisdaras/03852aeed8b3ce5a20b2910d596e5653 to your computer and use it in GitHub Desktop.
Save giannisdaras/03852aeed8b3ce5a20b2910d596e5653 to your computer and use it in GitHub Desktop.
Parallel computation of primes
#include <stdio.h>
#include <math.h>
#include <unistd.h>
#include <sys/types.h>
#define number_of_procs 4
int main() {
long i, j, prime, low, high,count_left=0,count_right=0;
pid_t p;
low = 3;
high = 11;
long chunck = ceil((high-low)/number_of_procs);
long start = low;
for (int k=0; k<number_of_procs; k++){
p = fork();
if (p==0){
int end=0;
if (start+chunck > high){
end = high;
}
else{
end = start + chunck;
}
for (i=start; i<=end; i++){
prime=1;
if (i%2==0){
prime=0;
}
for (j=3; j<(sqrt(i)+1); j+=2){
if ( (i%j) ==0){
prime=0;
break;
}
}
if (prime){
printf("%ld is a prime\n",i);
}
}
break;
}
else {
start += chunck + 1;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment