jeudi 11 mars 2021

What is the average number of iterations calling (rand() % range) in order to receive a specified number within range?

Lets say you have a function:

int GetNumOfIterations(int highest_num, int num_in_range)
{
    int temp = -1;
    size_t i = 0;

    srand(time(NULL));

    while (num_in_range != temp)
    {
        temp = rand() % highest_num;
        ++i;
    }

    return i;
}

What will be the time complexity of it? In worst and average cases? What will be the average for 'i'?

An interviewer told me the average of iterations is the range's size, so if range is 0 to 100, the average of iterations is 100. Why? Is this the correct answer?

Thanks in advance!




Aucun commentaire:

Enregistrer un commentaire