#include <iostream>
#include <vector>
#include <cmath>
#include <mpi.h>
// Function to check if a number is prime
bool isPrime(int num) {
if (num <= 1) return false;
for (int i
= 2; i
<= sqrt(num
); i
++) { if (num % i == 0) return false;
}
return true;
}
// Function to find the largest gap between consecutive prime numbers
int findLargestGap(int start, int end) {
int largestGap = 0;
int prevPrime = -1;
for (int i = start; i <= end; i++) {
if (isPrime(i)) {
if (prevPrime != -1) {
largestGap = std::max(largestGap, i - prevPrime);
}
prevPrime = i;
}
}
return largestGap;
}
int main(int argc, char** argv) {
MPI_Init(&argc, &argv);
int rank, size;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
int n;
if (rank == 0) {
n = 100000;
}
MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD);
int chunkSize = n / size;
int start = rank * chunkSize + 2; // Start from 2, the first prime number
int end = (rank == size - 1) ? n : (start + chunkSize - 1);
double startTime = MPI_Wtime();
int largestGap = findLargestGap(start, end);
double endTime = MPI_Wtime();
int globalLargestGap;
MPI_Reduce(&largestGap, &globalLargestGap, 1, MPI_INT, MPI_MAX, 0, MPI_COMM_WORLD);
double timeTaken = endTime - startTime;
double totalTimeTaken;
MPI_Reduce(&timeTaken, &totalTimeTaken, 1, MPI_DOUBLE, MPI_MAX, 0, MPI_COMM_WORLD);
if (rank == 0) {
std::cout << "Largest gap between consecutive prime numbers less than " << n << ": " << globalLargestGap << std::endl;
std::cout << "Time taken: " << totalTimeTaken << " seconds" << std::endl;
}
MPI_Finalize();
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPiAgCiNpbmNsdWRlIDx2ZWN0b3I+ICAKI2luY2x1ZGUgPGNtYXRoPiAgCiNpbmNsdWRlIDxtcGkuaD4gIAoKLy8gRnVuY3Rpb24gdG8gY2hlY2sgaWYgYSBudW1iZXIgaXMgcHJpbWUgIApib29sIGlzUHJpbWUoaW50IG51bSkgewoJaWYgKG51bSA8PSAxKSByZXR1cm4g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