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

前端 未结 9 2063
梦毁少年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:55

    Do x random numbers (from 0 to RAND_MAX) and add them together, where

    x = n % RAND_MAX

    0 讨论(0)
  • 2021-01-18 08:58

    Random numbers is a very specialized subject that unless you are a maths junky is very easy to get wrong. So I would advice against building a random number from multiple sources you should use a good library.

    I would first look at boost::Random

    If that is not suffecient try of this group sci.crypt.random-numbers Ask the question there they should be able to help.

    0 讨论(0)
  • 2021-01-18 09:01

    suppose you want to generate a 64-bit random number, you could do this:

    uint64_t n = 0;
    for(int i = 0; i < 8; ++i) {
        uint64_t x = generate_8bit_random_num();
        n = (n << (8 * i)) | x;
    }
    

    Of course you could do it 16/32 bits at a time too, but this illustrates the concept.

    How you generate that 8/16/32-bit random numbers is up to you. It could be as simple as rand() & 0xff or something better depending on how much you care about the randomness.

    0 讨论(0)
提交回复
热议问题