开发者

Best Algorithm to randomly generate a number that is divisible by N

Is there a better agorithm to do the following?

I am trying to generate 50 random numbers that are divisible by 7. I then select one of those 50 at random & return that number.

Is there a more efficient/better way to randomly generate numbers that are divisible by 7? Is there a better way I could code/do this?

    unsigned int generateRandomNumberDivisibleByN( unsigned int n, unsigned int num=10 )
    {
        // Post: Generate many different random numbers that are divisible by n, then randomly select one of
        //       of those numbers to return.

        unsigned int potentialN开发者_开发问答ums[num];

        for (int i=0, j=2; i<num; i++, j=rand()%INT_MAX)
        {
            potentialNums[i] = j*n;
        }

        return potentialNums[ rand()%num ]; // should this be rand()%(num-1) so it never returns an invalid array index?
    }


Why can't you just do this?

return (rand() % MAX) * 7;

It does almost the same thing.

Where MAX is small enough to avoid overflow during the multiplication by 7. Which you can define as:

const MAX = INT_MAX / 7;

Or if you want it to be fast, you can do something like:

return (rand() & 0xff) * 7;


The most efficient way to randomly generate a number divisible by 7 is to generate a random number and then multiply it by 7.

return ( rand() % ( INT_MAX / 7 ) ) * 7


Why generate a bunch of random numbers, then choose one of them at random? You have the core idea already: generate a random number and multiply it by 7. The potentialNums array doesn't add any value.


To make this much faster first use the fast random generation function found here this should make the actual process of creating randoms much faster,

Next, you can multiply the random by 7 and it will always be a multiple of 7, however, if this multiplication causes an overflow of the int (which with randoms is likely) you can always take a mask of the first few bits and multiply them.

e.g.

randomNumber = (generatedRandom & 0x00FFFFFF) * 7

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜