![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ Program to Generate Random Numbers Using Multiply with Carry Method
The multiply-with-carry method is a variant of the add-with-carry generator introduced by Marsaglia and Zaman (1991). The main advantages of this 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.
In MWC base b is chosen to equal to the computer word size and multiplier a and lag r determine the modulus p = abr−1. Here, a is chosen so the modulus is prime and the multiplier has long period.
Algorithm
Begin Declare maximum _sequence _elements, b, r, c[maximum _sequence _elements], x[maximum _sequence _elements] Read the variables maximum _sequence _elements, b, r m = rand() mod b c[0] = rand() mod m x[0] = rand() mod b For I = 1 to maximum_sequence_element, do x[i] = (m * x[i - r] + c[i - 1]) mod b c[i] = (m * x[i - r] + c[i - 1]) / b print the sequence. Done. End.
Example Code
#include <iostream> using namespace std; int main(int argc, char **argv) { int max_Seq_Elements = 7; int b = 300; int m = rand() % b; int r = 1; int c[max_Seq_Elements]; int x[max_Seq_Elements]; c[0] = rand() % m; x[0] = rand() % b; cout << "The random number sequence is: " << x[0]; for (int i = 1; i < max_Seq_Elements; i++) { x[i] = (m * x[i - r] + c[i - 1]) % b; c[i] = (m * x[i - r] + c[i - 1]) / b; cout << " " << x[i]; } cout << "..."; }
Output
The random number sequence is: 177 173 226 221 56 157 84...
Advertisements