# Thread: fast random number generation

1. ## fast random number generation

Hi,
I have made a program that generates random numbers. It takes arguments from the command line like this:
Usage: argv[0] [-n | -c [val]] [min-max] [num]

Default behaviour is to print [num] random numbers, ranging from [min] to [max], with a newline after each number. The option "-n" will cause no newlines to be printed between each value, OR, "-c val" will print an ascii value "val", between each number.

Here is the main processing function of the program (all the arguments have been checked):

Code:
```/* Main function to output random numbers.
It outputs "num" random numbers, between "min" and "max",
with "ch" between each number. */
void OutputRanNums
(int ch, int min, int max, unsigned long int iterations)
{
register long int rannum;
register unsigned int diff;
register unsigned long int num = iterations;

/* Work out offset value, increment as rand()
could return 0 as lowest value */
diff = max - min;
diff++;

/* Any better ideas? */
srand(time(NULL));
for( ; num>0 ; num-- )
{
rannum = rand();
rannum %= diff;
rannum += min;
printf("%ld",rannum);
if( ch )
printf("%c",ch);
}
fflush(stdout);
}```
I wonder if any bit shifting could be done (or any other tricks) to speed this up...

2. ## ~

Well, you're not generating the random numbers - rand() is - so actually, this is slower random number generation. Also, what's the use of the prog? I can understand a random(min,max) style function, but not one that just prints em out.

3. Someone told once in the forum the using % (mod) is a little bit slow, I think Quzah gave once another way to do that faster then using mod, so try searching the board.

4. I understand that rand() generates the psuedo-random numbers, but I want the random numbers in a certain range.
Eg. I want a print out of 100 random numbers ranging from 10-20.

In the past I have heard a few people asking how to produce N random numbers from range X to Y "in linux", in IRC channels (heh, don't ask me why=). I really just created the program because a good way to learn is to practice. Perhaps it may be useful in creating test data or something.
Who knows, one day, someone may even find it usefull.

PS
The source is also able to output the values in binary format, so "rand -n 65-90 15" could be used to produce a random password or something... just a thought.

5. ## ~

"using % (mod) is a little bit slow"

Another way is to AND the returned value with the number. Of course, it only works for powers of two, but

rand() % 2 == rand() & 1
rand() % 4 == rand() & 3
rand() % 8 == rand() & 7

etc.