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
where,
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.
Approach:
- 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:
Java
import java.util.*;
class GFG {
static void lcm( int seed, int mod, int multiplier,
int inc, int [] randomNums,
int noOfRandomNum)
{
randomNums[ 0 ] = seed;
for ( int i = 1 ; i < noOfRandomNum; i++) {
randomNums[i]
= ((randomNums[i - 1 ] * multiplier) + inc)
% m;
}
}
public static void main(String[] args)
{
int seed = 5 ;
int mod = 7 ;
int multiplier = 3 ;
int inc = 3 ;
int noOfRandomNum = 10 ;
int [] randomNums = new int [noOfRandomNum];
lcm(seed, mod, multiplier, inc, randomNums,
noOfRandomNum);
for ( int i = 0 ; i < noOfRandomNum; i++) {
System.out.print(randomNums[i] + " " );
}
}
}
|
Output
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.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!