C++ Program to Generate Random Numbers using Multiply with Carry Method

This is a C++ Program to generate random numbers using Multiply with Carry method. In computer science, multiply-with-carry (MWC) is a method invented by George Marsaglia for generating sequences of random integers based on an initial set from two to many thousands of randomly chosen seed values. 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, ranging from around 260 to 22000000.

Here is source code of the C++ Program to Generate Random Numbers Using Multiply with Carry Method. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

1. #include <iostream>
2. #include <math.h>
3. #include <stdlib.h>
4.
5. using namespace std;
6.
7. int main(int argc, char **argv)
8. {
9.     int max_Sequence_Elements = 10;
10.
11.     int base_b = 2000;
12.     int multiplier_a = rand() % base_b;
13.     int r = 1;
14.     int c[max_Sequence_Elements];
15.     int x[max_Sequence_Elements];
16.
17.     c[0] = rand() % multiplier_a;
18.     x[0] = rand() % base_b;
19.
20.     cout << "The random number sequence is: " << x[0];
21.     //generating sequence
22.     for (int i = 1; i < max_Sequence_Elements; i++)
23.     {
24.         x[i] = (multiplier_a * x[i - r] + c[i - 1]) % base_b;
25.         c[i] = (multiplier_a * x[i - r] + c[i - 1]) / base_b;
26.         cout << " " << x[i];
27.     }
28.     cout << "...";
29. }

Output:

\$ g++ MultiplyWithCarry.cpp
\$ a.out

The random number sequence is: 334 1711 157 472 1355 1564 151 223 1146 990...

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
advertisement

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

If you find any mistake above, kindly email to [email protected]

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