Suppose you have a function (or a magic ball) that is capable of producing a totally random integer between 1 and 5 (inclusive).
Using this, how would you generate a random number (also an integer) between 1 and 7 (inclusive)? (Note that the for the number to be random, all integers between 1 and 7 must have an equal chance of being generated)
Assume that using your 1-5 generator is pretty time-consuming, so you want to minimize the number of times you are going to use it.
(In reply to
re(2): solution by Charlie)
Actually, I think it's possible to combine ideas from both techniques for an even better solution. Store a and aSize as static variables. Upon successfully finding a result in my technique, set aSize to groupSize and a to (c % groupSize) (and this time I mean that modulo operator!). This allows ensures that the rand5 function is never called more times than necessary at any point.