C Program to Implement Park-Miller Random Number Generation Algorithm

This C program implements Park-Miller random number generation algorithm. The Miller–Rabin primality test or Rabin–Miller primality test is a primality test: an algorithm which determines whether a given number is prime, similar to the Fermat primality test and the Solovay–Strassen primality test.

Here is the source code of the C program to generate random number using Park-Miller algorithm. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. #include <stdio.h>
  2. #include <math.h>
  3. #include <stdlib.h>
  4. #include <time.h>
  5.  
  6. #define RNG_M 2147483647L /* m = 2^31 - 1 */
  7. #define RNG_A 16807L
  8. #define RNG_Q 127773L     /* m div a */
  9. #define RNG_R 2836L	 /* m mod a */
  10.  
  11. /* 32 bit seed */
  12. static long rnd_seed;
  13.  
  14. void set_rnd_seed (long seedval)
  15. {
  16. /* set seed to value between 1 and m-1 */
  17.  
  18.     rnd_seed = (seedval % (RNG_M - 1)) + 1;
  19. }
  20.  
  21. /* returns a pseudo-random number from set 1, 2, ..., RNG_M - 1 */
  22. long rnd()
  23. {
  24.     register long low, high, test;
  25.     set_rnd_seed( (unsigned int) time(0) + getpid());
  26.     high = rnd_seed / RNG_Q;
  27.     low = rnd_seed % RNG_Q;
  28.     test = RNG_A * low - RNG_R * high;
  29.     if (test > 0)
  30.         rnd_seed = test; 
  31.     else 
  32.         rnd_seed = test + RNG_M;
  33.     return rnd_seed;
  34. }
  35.  
  36.  
  37. int main(void)
  38. {
  39.  
  40.     printf("Random number generated is %d\n", rnd());
  41.     return 0;
  42. }

$ gcc bubblesort.c -o bubblesort
$ ./bubblesort
 
Random number generated is 284736523

Sanfoundry Global Education & Learning Series – 1000 C Programs.

advertisement
advertisement

Here’s the list of Best Books in C Programming, Data Structures and Algorithms.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.