jeudi 27 juin 2019

Generating N random numbers from rand2()

Can someone explain the logic in for loop? how it is generating random numers

int rand2()
{
    return rand() & 1;
}

int randn(int N)
{

    int add = 0;
    int ref = 1;

    for (int i = 0; i < N; i++)
    {

        add = add + rand2() * ref;

        ref = ref * 2;
    }

    return add % N;
}

int main()
{
    srand(time(NULL));
    printf("%d, ", randn(5));

    return 0;
}




Aucun commentaire:

Enregistrer un commentaire