C++ Program to Implement Park-Miller Random Number Generation Algorithm

This is a C++ Program to generate random numbers using Park-Miller algorithm. A general formula of a random number generator (RNG) of this type is:
X_{k+1} = g X(k) mod n
where the modulus n is a prime number or a power of a prime number, the multiplier g is an element of high multiplicative order modulo n (e.g., a primitive root modulo n), and the seed X0 is co-prime to n.

Here is source code of the C++ Program to Implement Park-Miller Random Number Generation Algorithm. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. #include <iostream>
  2. #include <math.h>
  3. #include <stdlib.h>
  4.  
  5. using namespace std;
  6.  
  7. const long m = 2147483647L;
  8. const long a = 48271L;
  9. const long q = 44488L;
  10. const long r = 3399L;
  11.  
  12. static long r_seed = 12345678L;
  13.  
  14. double uniform()
  15. {
  16.     long hi = r_seed / q;
  17.     long lo = r_seed - q * hi;
  18.     long t = a * lo - r * hi;
  19.     if (t > 0)
  20.         r_seed = t;
  21.     else
  22.         r_seed = t + m;
  23.     return r_seed;
  24. }
  25.  
  26. int main(int argc, char **argv)
  27. {
  28.     double A[10];
  29.  
  30.     for (int i = 0; i < 10; i++)
  31.         A[i] = uniform();
  32.  
  33.     cout<<"Random numbers are:\n";
  34.     for (int i = 0; i < 10; i++)
  35.         cout << A[i]<<endl;
  36. }

Output:

$ g++ ParkMillerRandomNumbers.cpp
$ a.out
 
Random numbers are:
1.08525e+009
5.0826e+008
1.35229e+009
1.56324e+009
8.90733e+008
1.81003e+009
1.50959e+009
8.62973e+008
1.85299e+009
6.77684e+008

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.