Untitled
פיבונאציunknown
c_cpp
a year ago
2.0 kB
7
Indexable
#include <stdio.h> #include <stdlib.h> #include <mpi.h> int readA(int **A); int main(int argc, char **argv) { int my_id, nprocs; int *A; // the input array. assume it is initialized int N; // size of the input array. assume it is initialized MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &nprocs); MPI_Comm_rank(MPI_COMM_WORLD, &my_id); if (my_id == 0) { N = readA(&A);// assume it reads array A and return his size if ((N % nprocs) != 0) { fprintf(stderr, "size of array not divisible by number of processes\n"); MPI_Abort(MPI_COMM_WORLD, 2); } } // Broadcast size of the array to all processes MPI_Bcast(&N, 1, MPI_INT, 0, MPI_COMM_WORLD); if(my_id !=0) A = (int *)malloc(sizeof(int) * N); // MPI_Bcast the array to all processes MPI_Bcast(A, N, MPI_INT,0, MPI_COMM_WORLD); // Calculate chunk size for each process int chunkSize = N / nprocs; // Determine the start and end index of each process's portion of the array int start = chunkSize * my_id; int end = start + chunkSize; // Check for Fibonacci series within each process's portion of the array int isFibonacci = 1; // Assume Fibonacci series initially for (int i = start; i < end; i++) { if (i <= 1) // Skip first two elements continue; if (A[i - start] != A[i - start - 1] + A[i - start - 2]) { isFibonacci = 0; // Not a Fibonacci series break; } } // Reduce all results to root process int sum_result; // used by process with rank 0 MPI_Reduce(&isFibonacci, &sum_result, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD); if (my_id == 0) { if (sum_result == nprocs) printf("yes\n"); // All processes found it is a Fibonacci series else printf("no\n"); } MPI_Finalize(); return 0; }
Editor is loading...
Leave a Comment