#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);

    int n = 0;
    if (my_rank == 0) {
        printf("How many integers (1-1000000000)? ");
        fflush(stdout);
        if (scanf("%d", &n) != 1 || n < 1 || n > 1000000000) {
            n = 0;
        }
    }
    MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD);

    if (n == 0) {
        if (my_rank == 0) {
            printf("Please enter an integer from 1 through 1000000000.\n");
        }
        MPI_Barrier(MPI_COMM_WORLD); /* PicoCluster shutdown workaround. */
        MPI_Finalize();
        return 1;
    }

    long long local_sum = 0;
    for (int i = my_rank + 1; i <= n; i += comm_sz) {
        local_sum += i;
    }

    long long total = 0;
    MPI_Reduce(&local_sum, &total, 1, MPI_LONG_LONG_INT, MPI_SUM,
               0, MPI_COMM_WORLD);

    if (my_rank == 0) {
        printf("Sum from 1 through %d: %lld\n", n, total);
    }
    MPI_Barrier(MPI_COMM_WORLD); /* PicoCluster shutdown workaround. */
    MPI_Finalize();
    return 0;
}
