-1

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.

Community
  • 1
  • 1
Akshayanti
  • 354
  • 3
  • 15

1 Answers1

0

Here's the implementation of srand() and rand() in MSVC.

unsigned long rand_key;
void srand(unsigned long seed) {
    rand_key = seed;
}
int rand(void) {
    return ((rand_key = (rand_key * 214013L + 2531011L)) >> 16) & 0x7FFF;
}

Implementations on other platforms may differ, but they're essentially the same (calculating the next number from the current number). So calling srand() with the same seed is guaranteed to generate the exactly same sequence.

You can mix some stuff up to get a better seed:

#include <time.h>
#include <unistd.h>

srand( (unsigned)time(NULL) ^ getpid() );
iBug
  • 35,554
  • 7
  • 89
  • 134