samedi 16 décembre 2017

Difference in behaviour of rand() function in C [duplicate]

This question already has an answer here:

I am trying to implement multiply-shift algorithm for hashing and need to generate a new random number every time. I used a function to do the same as follows-

long mulShift(long x)
// returns h(x) for multiply shift function
{
    srand (time (NULL));
    long a = rand() % (long)pow(2,u);
    if ((a>>1)<<1 == a)
        a = a + 1;
    long h = ((a*x) >> (u-k));
    printf("%ld\t%ld\n", x, a); 
    return h%m;
}

Here u and k are global variables. If I call this function in a loop as follows-

for (int i = 0; i<5; i++)
   mulShift(15);

I get the following output-

15 528638629

15 528638629

15 528638629

15 528638629

15 528638629

However, if I use srand before a for loop as follows-

srand(time(NULL));
    for (int i = 0; i<10; i++)
    {
        printf("%d\n", rand()%1000000);
    }

The output changes as follows-

638629

290058

512341

826358

80629

Why is this difference in behaviour? If I keep srand() inside the for loop in the last example, it again starts printing same values again and again. I apologise in advance if this is a stupid question.

Also, I'm using GCC on Ubuntu, if it makes a difference.




Aucun commentaire:

Enregistrer un commentaire