//------------------------------------------------------------------- // lincong.cpp // // This program shows how a pseudo-random number generator can // easily be implemented via the "linear congruential method". // // to compile: $ g++ lincong.cpp -o lincong // to execute: $ ./lincong // // Online reference: Wikipedia, "Linear Congruential Generator" // // programmer: ALLAN CRUSE // written on: 23 JAN 2011 //------------------------------------------------------------------- #include // for printf() unsigned int a = 1664525; // the "multiplier" unsigned int b = 1013904223; // the "increment" unsigned int m = (1 << 24); // the "modulus" unsigned int s = 0; // the "seed" unsigned int randomint( void ) { static unsigned int x = s; x = (a * x + b) % m; return x >> 8; } int main( int argc, char **argv ) { // generate twenty pseudorandom values unsigned int x[ 20 ]; for (int i = 0; i < 20; i++) x[i] = randomint(); // show these pseudorandom values printf( "\n Here are twenty pseudo-random numbers: \n" ); for (int i = 0; i < 20; i++) printf( " %10u \n", x[i] ); printf( "\n" ); // pause until the user has finished looking at them printf( " Press to continue " ); getchar(); // then use these pseudorandom values in a coin-tossing simulation printf( "\n And here they give us a coin-tossing simulation: \n" ); for (int i = 0; i < 20; i++) { if ( (x[i] % 2) > 0 ) printf( " Heads \n" ); else printf( " Tails \n" ); } printf( "\n" ); }