直接上代码
public int rand7() {
int n;
while(true) {
int tmp1 = rand5();
int tmp2 = rand5();
n = (tmp1 - 1) * 5 + tmp2; //n最大值为25
if(n <= 21) { //为等概率,最大只能为7的倍数
return 1 + n % 7;
}
}
}
此为随机数问题的通式,其他随机数问题依照此理。
直接上代码
public int rand7() {
int n;
while(true) {
int tmp1 = rand5();
int tmp2 = rand5();
n = (tmp1 - 1) * 5 + tmp2; //n最大值为25
if(n <= 21) { //为等概率,最大只能为7的倍数
return 1 + n % 7;
}
}
}
此为随机数问题的通式,其他随机数问题依照此理。