I have some doubts about the following function that I have written in order to compute all the prime numbers in a specific interval. The resulting vector is not ordered but this is not a problem. I have some doubts about the consistency of the result between different rank, in particular about the casting part between ranks.
std::vector<unsigned> get_prime_numbers(unsigned a, unsigned b){
int rank, size;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
std::vector<unsigned> local_result;
for(size_t i = a + rank; i <= b; i++){
if(is_prime(i))
local_result.push_back(i);
}
std::vector<unsigned> global_result;
for(int r = 0; r < size; r++){
if(rank == r){
global_result.insert(global_result.end(), local_result.cbegin(), local_result.cend());
unsigned n = local_result.size();
MPI_Bcast(&n, 1, MPI_UNSIGNED, r, MPI_COMM_WORLD);
MPI_Bcast(local_result.data(), n, MPI_UNSIGNED, r, MPI_COMM_WORLD);
}
else{
unsigned n;
MPI_Bcast(&n, 1, MPI_UNSIGNED, r, MPI_COMM_WORLD);
std::vector<unsigned> rec(n);
MPI_Bcast(local_result.data(), n, MPI_UNSIGNED, r, MPI_COMM_WORLD);
global_result.insert(global_result.end(), rec.cbegin(), rec.cend());
}
}
return global_result;
}
The function
is_prime(unsigned i)
is an auxiliary function already implemented.
I think that the casting part is correct but I’m not sure
New contributor
Roberto is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.