//------------------------------------------------------------------- // shortadd.cpp // // This program computes the probability that the sum of a pair // of randomly chosen 'short' integers (i.e., 16-bits) will not // fit within a 16-bit register or 'short' memory-variable. It // is amusing to observe that this probability is close to 1/2. // // And for unsigned multiplication of short integers, which can // be treated simply by changing '+' to '*' in this code, it is // almost a certainty that 16-bit register-overflow will occur, // a fact which beginning programmers are wise to keep in mind. // // compile using: $ g++ shortadd.cpp -o shortadd // execute using: $ ./shortadd // // NOTE: This program may take 15-20 seconds to finish running. // // programmer: ALLAN CRUSE // written on: 29 JAN 2011 // revised on: 04 FEB 2011 -- fix for 32-bit CPU architectures //------------------------------------------------------------------- #include // for printf() int main( int argc, char **argv ) { long long samples = 0; // for count of summand-pairs long long carries = 0; // for count of overflow-sums for (unsigned int x = 0; x < 65536; x++) for (unsigned int y = 0; y < 65536; y++) { samples += 1; if ( x + y > 65535 ) carries += 1; } printf( "\ncarries = %lld \nsamples = %lld \n", carries, samples ); float probability = (1.0*carries) / (1.0*samples); printf( "\nprobability of register-overflow " ); printf( "when adding 'short' integers " ); printf( "= %1.5f \n\n", probability ); }