generating a random number within range 0 to n where n can be > RAND_MAX

前端 未结 9 2076
梦毁少年i
梦毁少年i 2021-01-18 08:32

How can I generate a random number within range 0 to n where n can be > RAND_MAX in c,c++?

Thanks.

9条回答
  •  终归单人心
    2021-01-18 08:42

    If your implementation has an integer type large enough to hold the result you need, it's generally easier to get a decent distribution by simply using a generator that produces the required range than to try to combine outputs from the smaller generator.

    Of course, in most cases, you can just download code for something like the Mersenne Twister or (if you need a cryptographic quality generator) Blum-Blum-Shub, and forget about writing your own.

提交回复
热议问题