Java Program to Implement Linear Congruential Method for Generating Pseudo Random Number

«
»
This is java program to generate a random numbers, using linear congruential generator. The formula for next random number in the sequence is x(n+1) = {a*x(n)+c}mod m, where x(n+1) is current number to generate, x(n) is previously generated, a is multiplier, c is additive term and m is modulus.

Here is the source code of the Java Program to Implement the linear congruential generator for Pseudo Random Number Generation. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

  1. //This is a sample program to generate random numbers based on linear congruential generator
  2. import java.math.BigInteger;
  3. import java.util.Random;
  4.  
  5. public class Linear_Congruential_Random_Numbers 
  6. {
  7.     public static void main(String args[])
  8.     {
  9.         BigInteger n = new BigInteger(16, new Random(){});
  10.         Random rand = new Random();
  11.         BigInteger m = new BigInteger("65535");//2^16
  12.  
  13.         for(int i=0; i<5; i++)
  14.         {
  15.             System.out.print(n+", ");
  16.             BigInteger a = new BigInteger(16, new Random(){});
  17.             BigInteger c = new BigInteger(16, new Random(){});
  18.             n = ((a.multiply(a)).add(c)).mod(m);
  19.         }
  20.         System.out.println("... ");
  21.     }
  22. }

Output:

advertisement
$ javac Linear_Congruential_Random_Numbers.java
$ java Linear_Congruential_Random_Numbers
5107, 48257, 43654, 50875, 12815, ...

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

advertisement
advertisement

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

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 & technical discussions at Telegram SanfoundryClasses.