Linear Congruential Method is a class of Pseudo-Random Number Generator (PRNG) algorithms used for generating sequences of random-like numbers in a specific range. This method can be defined as:
Xi+1 = aXi + c mod m
X, is the sequence of pseudo-random numbers
m, ( > 0) the modulus
a, (0, m) the multiplier
c, (0, m) the increment
X0, [0, m) – Initial value of sequence known as seed
Note: m, a, c, and X0 should be chosen appropriately to get a period almost equal to m.
- For a = 1, it will be the additive congruence method.
- For c = 0, it will be the multiplicative congruence method.
- The seed value X0 is chosen, Modulus parameter m, Multiplier term a, and increment term c.
- Initialize the required amount of random numbers to generate (say, an integer variable noOfRandomNums).
- Define storage to keep the generated random numbers (here, the vector is considered) of size noOfRandomNums.
- Initialize the 0th index of the vector with the seed value.
- For the rest of the indexes follow the Linear Congruential Method to generate the random numbers.
randomNums[i] = ((randomNums[i – 1] * a) + c) % m
- Finally, return the random numbers.
Below is the implementation of the above approach:
5 4 1 6 0 3 5 4 1 6
The literal meaning of pseudo is false or imaginary. These random numbers are called pseudo because some known arithmetic procedure is utilized to generate them. Even the generated sequence forms a pattern hence the generated number seems to be random but may not be truly random.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.