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.

`#include <stdio.h>`

`#include <math.h>`

`#include <stdlib.h>`

static unsigned long Q[4096], c = 362436;

`/* choose random initial c<809430660 and */`

`/* 4096 random 32-bit integers for Q[] */`

unsigned long mwc(void){

unsigned long long t, a = 18782LL;

static unsigned long i = 4095;

unsigned long x, r = 0xfffffffe;

i= (i+1)&4095;

t = a * Q[i] + c;

c=(t >> 32);

x = t + c;

if(x < c)

`{`

`x++;`

`c++;`

`}`

return (Q[i] = r - x);

`}`

int main(void)

`{`

printf("\nRandom Number generated : %lld\n", mwc());

return 0;

`}`

advertisement

$ gcc mwc.c -o mwc $ ./mwc Random Number generated: 4294604858

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

advertisement

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