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 Java SynchronousQueue
Assertions in JUnit 4 and JUnit 5
Java Program to Implement Double Ended Queue
Java Program to Implement an Algorithm to Find the Global min Cut in a Graph
Java Program to Implement Fibonacci Heap
Spring MVC Async vs Spring WebFlux
Generating Random Numbers in a Range in Java
Spring NoSuchBeanDefinitionException
Converting String to Stream of chars
Spring Boot - Quick Start
Java Program to Implement Sorted List
Simple Single Sign-On with Spring Security OAuth2
The SpringJUnitConfig and SpringJUnitWebConfig Annotations in Spring 5
The Guide to RestTemplate
“Stream has already been operated upon or closed” Exception in Java
Guide to DelayQueue
Period and Duration in Java
Spring Security OAuth Login with WebFlux
Java Program to Compare Binary and Sequential Search
Java Program to Perform Postorder Recursive Traversal of a Given Binary Tree
Apache Commons Collections MapUtils
Java Program to Implement Hash Tables Chaining with List Heads
Java Program to Implement Randomized Binary Search Tree
Working with Network Interfaces in Java
Java Program to Perform Deletion in a BST
Adding a Newline Character to a String in Java
Guide to Spring 5 WebFlux
Spring Boot - Twilio
New Features in Java 12
Java Program to Implement Circular Singly Linked List
Java Program to Implement Gauss Seidel Method
Prevent Cross-Site Scripting (XSS) in a Spring Application