[Edit] The initial answer was for 0 to 1,000,000. I now see it should be 0 to 10,000,000.
As rand()
will give an answer of at least 15 bits, call rand()
multiple times, shift by 15 and XOR the results. Finally mod by 10,000,001.
unsigned long x;
x = rand();
x <<= 15;
x ^= rand();
x %= 10000001;
The distribution is very flat, but does introduce a very small bias. After 32768*32768 iterations, each value of x
0 to 10,000,000 to occur about 107.37 times. Instead they range from 107 to 108 times.
Combining multiple rand()
call results with +
, *
or |
will cause a significant bias in the distribution of the results.
[Edit]
RAND_MAX
is 32767 (0x7FFF) for OP's platform. The C spec says "value of the RAND_MAX macro shall be at least 32767". Because RAND_MAX may be longer than 15 bits, it is important to use the ^
operator above rather than |
for this code when used on other platforms.