#include <stdio.h>
#include <mpi.h>

int main(void) {
    int my_rank, comm_sz;
    MPI_Init(NULL, NULL);
    MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
    MPI_Comm_size(MPI_COMM_WORLD, &comm_sz);

    const int n = 12;
    if (n % comm_sz != 0) {
        if (my_rank == 0) {
            printf("Use 1, 2, 3, 4, 6, or 12 processes.\n");
        }
        MPI_Finalize();
        return 1;
    }

    int local_n = n / comm_sz;
    int x[12], y[12], z[12];
    int local_x[12], local_y[12], local_z[12];

    if (my_rank == 0) {
        for (int i = 0; i < n; i++) {
            x[i] = i + 1;
            y[i] = 10 * (i + 1);
        }
    }

    MPI_Scatter(x, local_n, MPI_INT,
                local_x, local_n, MPI_INT,
                0, MPI_COMM_WORLD);
    MPI_Scatter(y, local_n, MPI_INT,
                local_y, local_n, MPI_INT,
                0, MPI_COMM_WORLD);

    for (int i = 0; i < local_n; i++) {
        local_z[i] = local_x[i] + local_y[i];
    }

    MPI_Gather(local_z, local_n, MPI_INT,
               z, local_n, MPI_INT,
               0, MPI_COMM_WORLD);

    if (my_rank == 0) {
        printf("x + y:");
        for (int i = 0; i < n; i++) {
            printf(" %d", z[i]);
        }
        printf("\n");
    }

    MPI_Finalize();
    return 0;
}
