题目:给一个函数rand5(),它可以产生0到4之间的随机数(整数),要求写出函数rand8(),可以产生0到7之间的随机数(整数)
解决方法:
- function rand8()
- {
- while (true)
- {
- $i = 5 * rand5() + rand5();
- if( $i < 24 )
- {
- return $i % 8 ;
- }
- }
- }
rand5() 产生 0 , 1 , 2 , 3 , 4
rand5()*5 产生 0 , 5, 10 , 15 , 24
两者相加产生 0-24的均匀分布
当值小于24 也就是 0-23的时候,对其取模运算,可以得到0-7