#include <mpi.h>
#include <iostream>
#include <cmath>
#include <ctime>
#include <iomanip>
using namespace std
double cpu_time(void);
int prime_number(int n, int id, int numtasks);
int main(int argc, char** argv) {
int rank, size, n_factor = 2, n_lo = 1, n_hi = 100;
double start_time, end_time;
int n, primes, primes_part;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
if (rank == 0) {
cout << "Pomiar ilosci liczb pierwszych w powiekszajacych sie " << n_factor << "-krotnie podprzedzialach przedzialu [" << n_lo << " , " << n_hi << " ]" << endl;
cout << "\n";
cout << " N_max Ilosc liczb pierwszych Czas " << endl;
cout << "\n";
}
n = n_lo;
while (n <= n_hi) {
start_time = MPI_Wtime();
MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD);
primes_part = prime_number(n, rank, size);
MPI_Reduce(&primes_part, &primes, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
end_time = MPI_Wtime();
if (rank == 0) {
cout << " " << setw(3) << n
<< " " << setw(18) << primes
<< " " << setw(18) << end_time - start_time << endl;
}
n = n * n_factor;
}
MPI_Finalize();
return 0;
}
double cpu_time() {
return (double)clock() / (double)CLOCKS_PER_SEC
; }
int prime_number(int n, int id, int numtasks) {
int prime;
int total = 0;
for (int i = id + 2; i <= n; i += numtasks) {
prime = 1;
for (int j = 2; j < i; j++) {
if ((i % j) == 0) {
prime = 0;
break;
}
}
total = total + prime;
}
return total;
}
I2luY2x1ZGUgPG1waS5oPgojaW5jbHVkZSA8aW9zdHJlYW0+CiNpbmNsdWRlIDxjbWF0aD4KI2luY2x1ZGUgPGN0aW1lPgojaW5jbHVkZSA8aW9tYW5pcD4KCnVzaW5nIG5hbWVzcGFjZSBzdGQKCmRvdWJsZSBjcHVfdGltZSh2b2lkKTsKaW50IHByaW1lX251bWJlcihpbnQgbiwgaW50IGlkLCBpbnQgbnVtdGFza3MpOwoKaW50IG1haW4oaW50IGFyZ2MsIG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Ck7CgogICAgICAgIGVuZF90aW1lID0gTVBJX1d0aW1lKCk7CgogICAgICAgIGlmIChyYW5rID09IDApIHsKICAgICAgICAgICAgY291dCA8PCAiICAgICIgPDwgc2V0dygzKSA8PCBuCiAgICAgICAgICAgICAgICAgPDwgIiAgICAiIDw8IHNldHcoMTgpIDw8IHByaW1lcwogICAgICAgICAgICAgICAgIDw8ICIgICAgIiA8PCBzZXR3KDE4KSA8PCBlbmRfdGltZSAtIHN0YXJ0X3RpbWUgPDwgZW5kbDsKICAgICAgICB9CgogICAgICAgIG4gPSBuICogbl9mYWN0b3I7CiAgICB9CgogICAgTVBJX0ZpbmFsaXplKCk7CiAgICByZXR1cm4gMDsKfQoKZG91YmxlIGNwdV90aW1lKCkgewogICAgcmV0dXJuIChkb3VibGUpY2xvY2soKSAvIChkb3VibGUpQ0xPQ0tTX1BFUl9TRUM7Cn0KCmludCBwcmltZV9udW1iZXIoaW50IG4sIGludCBpZCwgaW50IG51bXRhc2tzKSB7CiAgICBpbnQgcHJpbWU7CiAgICBpbnQgdG90YWwgPSAwOwoKICAgIGZvciAoaW50IGkgPSBpZCArIDI7IGkgPD0gbjsgaSArPSBudW10YXNrcykgewogICAgICAgIHByaW1lID0gMTsKICAgICAgICBmb3IgKGludCBqID0gMjsgaiA8IGk7IGorKykgewogICAgICAgICAgICBpZiAoKGkgJSBqKSA9PSAwKSB7CiAgICAgICAgICAgICAgICBwcmltZSA9IDA7CiAgICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgfQogICAgICAgIH0KICAgICAgICB0b3RhbCA9IHRvdGFsICsgcHJpbWU7CiAgICB9CiAgICByZXR1cm4gdG90YWw7Cn0K