algorithm - How to generate a random number <= 7 from two random numbers <= 5? -


here reference implementation , not understand why choose 21 here? thanks.

public static int rand7() {     while (true) {         int num = 5 * (rand5() - 1) + (rand5() - 1);         if (num < 21) return (num % 7 + 1);     } } 

btw, read question before asking, specific question why using 21 here. in thread, not answered. if missed anything, please feel free correct. thanks. :) in advance, lin

it's because 21 multiple of 7.

the term 5 * (rand5() - 1) + (rand5() - 1) produces number in range [0, 24] (uniform distribution). used create random number in [0, 6] % 7. however, not produce uniform distribution if use entire range. remainders 0, 1, 2, 3 occur once more remainders 4, 5, 6. therefore, according numbers produce 1 of these remainders cut off , range [0, 20] (< 21) used. equivalently cut off first 4 numbers (> 3) produce uniform distribution.


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -