Even division with random numbers

I needed to generate random numbers for even division from a given range. Using the modulo operator (Wikipedia) gives the remainder of a division. This gave me some headache, but I thought I’d share what I found.

var a:Number = Math.round((randomNumber() % 8 + 1)*3);

The randomNumber() method looks like this:

return Math.round(Math.random() * (endIndex - startIndex)) + startIndex;

The above example with the hard coded values 8 and 3 generates numbers in the range 3 to 24, all with modulo 0.

If you would like numbers that can be divided with 5, the following code does the job:

var a:Number = Math.round((randomNumber() % 5 + 1)*5);

So, the maximum number that is generated is specified by the product of 5*5 or 8*3. 5 and 3 specify the denominator.

The quick fix I came up with is to create different variants of these code snippets, and randomly select on. In example, have one line of code for division with 2, 3, 4, 5 and so forth and then randomly select one line to use.