fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <cmath>
  4. #include <mpi.h>
  5.  
  6. // Function to check if a number is prime
  7. bool isPrime(int num) {
  8. if (num <= 1) return false;
  9. for (int i = 2; i <= sqrt(num); i++) {
  10. if (num % i == 0) return false;
  11. }
  12. return true;
  13. }
  14.  
  15. // Function to find the largest gap between consecutive prime numbers
  16. int findLargestGap(int start, int end) {
  17. int largestGap = 0;
  18. int prevPrime = -1;
  19. for (int i = start; i <= end; i++) {
  20. if (isPrime(i)) {
  21. if (prevPrime != -1) {
  22. largestGap = std::max(largestGap, i - prevPrime);
  23. }
  24. prevPrime = i;
  25. }
  26. }
  27. return largestGap;
  28. }
  29.  
  30. int main(int argc, char** argv) {
  31. MPI_Init(&argc, &argv);
  32.  
  33. int rank, size;
  34. MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  35. MPI_Comm_size(MPI_COMM_WORLD, &size);
  36.  
  37. int n;
  38. if (rank == 0) {
  39. std::cout << "Enter the value of n: ";
  40. std::cin >> n;
  41. }
  42.  
  43. MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD);
  44.  
  45. int chunkSize = n / size;
  46. int start = rank * chunkSize + 2; // Start from 2, the first prime number
  47. int end = (rank == size - 1) ? n : (start + chunkSize - 1);
  48.  
  49. double startTime = MPI_Wtime();
  50. int largestGap = findLargestGap(start, end);
  51. double endTime = MPI_Wtime();
  52.  
  53. int globalLargestGap;
  54. MPI_Reduce(&largestGap, &globalLargestGap, 1, MPI_INT, MPI_MAX, 0, MPI_COMM_WORLD);
  55.  
  56. double timeTaken = endTime - startTime;
  57. double totalTimeTaken;
  58. MPI_Reduce(&timeTaken, &totalTimeTaken, 1, MPI_DOUBLE, MPI_MAX, 0, MPI_COMM_WORLD);
  59.  
  60. if (rank == 0) {
  61. std::cout << "Largest gap between consecutive prime numbers less than " << n << ": " << globalLargestGap << std::endl;
  62. std::cout << "Time taken: " << totalTimeTaken << " seconds" << std::endl;
  63. }
  64.  
  65. MPI_Finalize();
  66. return 0;
  67. }
  68.  
Success #stdin #stdout #stderr 0.25s 40756KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Error: unexpected '/' in "/"
Execution halted