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

long long N = 100000000;

int desniDeoBroja(long long n, int d)
{
    long long n2 = n * n;
    int desni = 0;
    int cifra;
    int i = 1;

    long long temp = n2;

    while(d)
    {
        cifra = temp % 10;
        desni = desni + cifra * i;
        i = i * 10;
        temp = temp / 10;
        d--;
    }

    return temp;
}

int leviDeoBroja(long long n, int d)
{
    long long n2 = n * n;
    int levi = 0;
    int cifra;
    int i = 1;

    long long temp = n2;

    while(d)
    {
        temp = temp / 10;
        d--;
    }

    while(temp)
    {
        cifra = temp % 10;
        levi = levi + cifra * i;
        i = i * 10;
        temp = temp / 10;
    }

    return temp;
}

int kaprekarovBroj(long long n, int d)
{
    long long zbir = leviDeoBroja(n, d) + desniDeoBroja(n, d);

    if(n == zbir)
        return 1;

    return 0;
}

int main(int argc, char *argv[])
{
    int id, np;
    int d;
    MPI_Status status;
    long long niz[100000];
    int j = 0;

    MPI_Init(&arcg, &argv);

    MPI_Comm_rank(MPI_COMM_WORLD, &id);
    MPI_Comm_size(MPI_COMM_WORLD, &np);

    if(id == 0)
    {
        printf("d = ");
        scanf("%d", &d);
    }

    MPI_Bcast(&d, 1, MPI_INT, 0, MPI_COMM_WORLD);
    MPI_Bcast(&j, 1, MPI_INT, 0, MPI_COMM_WORLD);

    for(int i = id; i <= N; i+= np)
    {
        if(kaprekarovBroj)
        {
            niz[j] = i;
            j++;
        }
    }

    if (id == 0)
    {
        for(int i = 0; i < np; i++)
        {
            MPI_Recv(niz, 100000, MPI_LONG_LONG, i, 10, MPI_COMM_WORLD, &status);
        } 
    }

    else
    {
        MPI_Send(niz, 100000, MPI_LONG_LONG, 10, MPI_COMM_WORLD);
    }
    
    for(int i = 0; i < N; i++)
    {
        printf("%ld", niz[i]);
    }

    MPI_Finalize();

    return 0;
}