Advertisement

C program to generate random numbers between 1 and a million

Started by December 20, 2023 01:16 AM
2 comments, last by alvaro 11 months ago

I wrote a C program to generate random numbers between 1 and a million:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
   // Initialize the random number generator with the current time
   srand(time(NULL));

   for (int ctr = 0; ctr < 25; ctr++)
   {
       // Generate a random number between 1 and 1000000
       int random_number = rand() % 1000000 + 1;

       // Print the random number
       printf("The random number is %d\n", random_number);
   }
   return 0;
}

However, the numbers aren't high enough. I think they only go up to 30 thousand something.

Anyone know how to fix it so I can get some higher numbers? I want it to be in C.

Thanks.

Mike C.http://www.coolgroups.com/zoomer/http://www.coolgroups.com/ez/

Nah, you're just really really unlucky. Keep trying !!


… kidding of course.
You have a some options:

1- Use floats: (float)rand() / RAND_MAX. This option is pretty terrible. It's limited to RAND_MAX of those 1 million numbers-- that 30k you saw earlier

2- Use a random number generator provided by your operating system. /dev/urandom/ on linux or BCryptGenRandom on windows.

3- Use a third party library or function.

Advertisement

rand() produces numbers between 0 and RAND_MAX, and RAND_MAX might be as small as 32767. Also, some implementations produce very low-quality pseudo-random numbers, especially in the lowest bits. This was probably okay in the 70s and 80s, but in modern times you should be generating 64-bit random numbers and they should be of reasonably high quality.

In a pinch, feel free to use these instead of the standard srand() and rand():

unsigned long long mix(unsigned long long x) {
  x ^= x >> 32;
  x *= 0x8b7aa13b2b73d2bbull;
  x ^= x >> 32;
  x *= 0x85159c3e8f3112f1ull;
  x ^= x >> 32;
  return x;
}

unsigned long long state = 1;

void my_srand(unsigned long long seed) {
  state = mix(seed ^ 0x7033726b30674e7full);
}

unsigned long long my_rand() {
  unsigned long long result = mix(state);
  state += 0xb0d37a055e5047c5ull;
  return result;
}

This topic is closed to new replies.

Advertisement