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

«
»
This C program generates random number using multiply with carry method. Most RNGs work by keeping a certain number, say k, of the most recently generated integers, then return the next integer as a function of those k. The initial k integers, the seeds, are assumed to be randomly chosen, usually 32-bits. The period of the RNG is related to the number of choices for seeds, usually 2^(32k), so to get longer periods you need to increase k. Here is a complimentary-multiply-with-carry RNG with k = 4097

Here is the source code of the C program to generate random number using complimentary-multiply-with-carry method with k = 4097. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

1. `#include <stdio.h>`
2. `#include <math.h>`
3. `#include <stdlib.h>`
4. `static unsigned long Q[4096], c = 362436; `
5. `/* choose random initial c<809430660 and */`
6. `/* 4096 random 32-bit integers for Q[]   */`
7. `unsigned long mwc(void){`
8. `    unsigned long long t, a = 18782LL;`
9. `    static unsigned long i = 4095;`
10. `    unsigned long x, r = 0xfffffffe;`
11. `    i= (i+1)&4095;`
12. `    t = a * Q[i] + c;`
13. `    c=(t >> 32); `
14. `    x = t + c; `
15. `    if(x < c)`
16. `    {`
17. `        x++;`
18. `        c++;`
19. `    }`
20. `    return (Q[i] = r - x);   `
21. `}`
22. `int main(void)`
23. `{`
24. ` `
25. `  printf("\nRandom Number generated : %lld\n", mwc());`
26. `  return 0;`
27. `}`

```\$ gcc mwc.c -o mwc
\$ ./mwc

Random Number generated: 4294604858```

Sanfoundry Global Education & Learning Series – 1000 C Programs.