There are many ways to do this.
If you are fine with less granularity (higher chance of cheating), then something like (in the pseudo-code) rand() * n / RAND_MAX will work to propagate values ββin a larger range. The trap is that in your real code you need to avoid overflow either by casting rand () or n to a large enough type (for example, a 64-bit int if RAND_MAX is 0xFFFFFFFF) to save the result of multiplication without overflow or use Multiple decomposition API (e.g. GNU MulDiv64 or Win32 MulDiv ), which is optimized for this scenario.
If you need granularity up to each integer, you can call rand () several times and add the results. Another answer suggests calling rand () for each 8-bit / 16-bit / 32-bit fragment depending on the size of RAND_MAX.
But, IMHO, the above ideas can quickly become complicated, inaccurate, or both. Generating random numbers is a solvable problem in other libraries, and it is probably much easier to borrow existing code (e.g. from Boost ) than trying to collapse your own. An open source random number generation algorithm in C ++? has answers with sitelinks if you want something other than Boost.
[EDIT: review after a busy day ... meant to come back and clear my quick reply this morning, but it was suspended and only returned. :-)]
Justin grant
source share