This is the java implementation of Multiply With Carry (MWC) algorithm to generate a set of random numbers. The main advantages of the MWC method are that it invokes simple computer integer arithmetic and leads to very fast generation of sequences of random numbers with immense periods. The formula it uses is, x(n) = (a*x(n-r) + c(n-1))mod n and c(n) = (a*x(n-r) + c(n-1))/n, where a is any multiplier, m is modulus, c is carry and r is initial number of seeds.
Here is the source code of the Java Program to Generate Random Numbers Using Multiply with Carry Method. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.
//This is a sample program to generate a random numbers based on Multiply with carry method
import java.util.Random;
public class Multiply_With_Carry
{
public static void main(String args[])
{
int max_Sequence_Elements = 10;
Random random = new Random();
int base_b = 2000;
int multiplier_a = random.nextInt(base_b);
int r = 1;
int []c = new int[max_Sequence_Elements];
int []x = new int[max_Sequence_Elements];
c[0] = random.nextInt(multiplier_a);
x[0] = random.nextInt(base_b);
System.out.print("The random number sequence is: " + x[0]);
//generating sequence
for(int i=1; i<max_Sequence_Elements; i++)
{
x[i] = (multiplier_a*x[i-r] + c[i-1]) % base_b;
c[i] = (multiplier_a*x[i-r] + c[i-1]) / base_b;
System.out.print(" " + x[i]);
}
}
}
Output:
$ javac Multiply_With_Carry.java $ java Multiply_With_Carry The random number sequence is: 795 382 1487 260 475 1798 1347 722 1389 63
Related posts:
A Guide to JUnit 5
Java Program to Implement Disjoint Set Data Structure
Spring Boot - Admin Server
Java – Delete a File
A Guide to Apache Commons Collections CollectionUtils
Java – Generate Random String
Send email with SMTPS (eg. Google GMail)
Different Ways to Capture Java Heap Dumps
Spring Cloud Series – The Gateway Pattern
Extra Login Fields with Spring Security
Hướng dẫn Java Design Pattern – Strategy
Send an email with an attachment
The Dining Philosophers Problem in Java
Working With Maps Using Streams
Lập trình đa luồng với CompletableFuture trong Java 8
Hướng dẫn Java Design Pattern – Mediator
Guide to the Java Clock Class
Java Program to Use rand and srand Functions
Connect through a Proxy
A Guide to Java SynchronousQueue
Java Program to Implement Double Ended Queue
Java Program to Generate a Random UnDirected Graph for a Given Number of Edges
OAuth2 for a Spring REST API – Handle the Refresh Token in AngularJS
Java Program to Find Inverse of a Matrix
Spring Boot - Exception Handling
Java Program to Check Whether an Undirected Graph Contains a Eulerian Cycle
Uploading MultipartFile with Spring RestTemplate
Quick Intro to Spring Cloud Configuration
Spring Boot - Admin Client
Java Program to Implement Bubble Sort
Java Program to Implement the linear congruential generator for Pseudo Random Number Generation
Java – Reader to Byte Array