C++ Program to Implement the linear congruential generator for Pseudo Random Number Generation


The linear congruential generator is a very simple example of a random number generator. It is one of the oldest and best-known pseudorandom number generator algorithms. The function which is used in this method −

Xn+1=(aXn + C) mod m

where X is the sequence of pseudorandom values, and

m,0<m— the “modulus"
a,0<a<m — the "multiplier"
c,0<c<m — the "increment"
X0, 0<x0<m — the "seed" or "start value"

are integer constants that specify the generator.

A benefit of this method is is that with appropriate choice of parameters, the period is known and long.

Algorithm

Begin
   Declare class mRND
   Create a function Seed(number)
      Assign a variable _seed=number
      Create a constructor mRND
   Declare _seed(0), a(0), c(0), m(2147483648)
   Create a function rnd()
      Return
         _seed = (a * _seed + c) mod m
      Declare a, c, m, _seed
   Done
   Declare an another subclass MS_RND inheriting from base class mRND
   Create a constructor
      Read the variables a, c
      Create a function rnd()
      return mRND::rnd() right shift 16
   Done
   Declare an another subclass BSD_RND inheriting from base class mRND
   Create a constructor
      Read the variables a, c
      Create a function rnd()
      return mRND::rnd()
   Done
   For x=0 to 6
      Print MS_RAND
   For x=0 to 6
      Print BSD_RAND
   Done
End

Example Code

#include <iostream>
using namespace std;
class mRND {
   public:
   void seed(unsigned int s) {
      _seed= s;
   }
   protected:
   mRND() :
   _seed(0), a(0), c(0), m(2147483648) { }
   int rnd() {
      return (_seed = (a * _seed + c) % m);
   }
   int a, c;
   unsigned int m, _seed;
};
class MS_RND: public mRND {
   public:
   MS_RND() {
      a = 214013;
      c = 2531011;
   }
   int rnd() {
      return mRND::rnd() >> 16;
   }
};
class BSD_RND: public mRND {
   public:
   BSD_RND() {
      a = 1016404597;
      c = 12345;
   }
   int rnd() {
      return mRND::rnd();
   }
};
int main(int argc, char* argv[]) {
   BSD_RND bsd_rnd;
   MS_RND ms_rnd;
   cout << "MS RAND:" << endl << "-----------" << endl;
   for (int x = 0; x < 6; x++)
      cout << ms_rnd.rnd() << endl;
   cout << endl << "BSD RAND:" << endl << "-------------" << endl;
   for (int x = 0; x < 6; x++)
      cout << bsd_rnd.rnd() << endl;
      return 0;
}

Output

MS RAND:
-------
38
7719
21238
2437
8855
11797
BSD RAND:
--------
12345
1915290694
1005338679
629284700
741596485
1834373826

Updated on: 30-Jul-2019

793 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements