# Java Program to Generate Random Numbers using Multiply with Carry Method

«
»
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.

1. `//This is a sample program to generate a random numbers based on Multiply with carry method`
2. `import java.util.Random;`
3. ` `
4. `public class Multiply_With_Carry `
5. `{`
6. `    public static void main(String args[])`
7. `    {`
8. `        int max_Sequence_Elements = 10;`
9. `        Random random = new Random();`
10. `        int base_b = 2000;`
11. `        int multiplier_a = random.nextInt(base_b);`
12. `        int r = 1;`
13. `        int []c = new int[max_Sequence_Elements];`
14. `        int []x = new int[max_Sequence_Elements];`
15. ` `
16. `        c[0] = random.nextInt(multiplier_a);`
17. `        x[0] = random.nextInt(base_b);`
18. ` `
19. `        System.out.print("The random number sequence is: " + x[0]);`
20. `        //generating sequence`
21. `        for(int i=1; i<max_Sequence_Elements; i++)`
22. `        {`
23. `            x[i] = (multiplier_a*x[i-r] + c[i-1]) % base_b;`
24. `            c[i] = (multiplier_a*x[i-r] + c[i-1]) / base_b;`
25. `            System.out.print(" " + x[i]);`
26. `        }`
27. `    }`
28. `}`

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```

Sanfoundry Global Education & Learning Series – 1000 Java Programs.