给定一个整数范围,如何在该范围内生成一个可被5整除的随机整数?
我正在使用Java
发布于 2013-10-13 10:30:02
只需生成一个规则的随机整数,并将其乘以5!
详细信息:在[0, n)中生成一个随机整数,其中n是您的范围内5的倍数,然后将其乘以5并将最小的倍数相加。
一行: System.out.println(rnd.nextInt(max / 5 - (min + 4) / 5 + 1) * 5 + (min + 4) / 5 * 5); (假设参数为非负且有效)
credits:最低的多重表达式(min + 4) / 5 * 5来自here,表达式根据@Thomas的答案简化了一点(国际海事组织目前不正确)
发布于 2013-10-13 10:44:44
这个问题要求在一个范围内是5的倍数,而不是在范围内的5的周期内的数字。
这个解决方案处理负片和范围有效性。
// because Java's % operator doesn't do what one might expect with negatives
int lbound = (min+4) - (((min+4) % 5) + 5) % 5;
int ubound = max - (((max % 5) + 5) % 5);
if (lbound > ubound) {
// do something about the range error
}
if (lbound == ubound) {
return lbound;
}
int range = ((ubound - lbound)/5) + 1;
return ((int)(Math.random() * range) * 5) + lbound;发布于 2013-10-13 17:19:19
首先创建一个Random,将low和high分别舍入到最接近的5的上下倍数:
Random r = new Random();
low = ((low+4)/5)*5; // next multiple of 5
high = (high/5)*5; // previous multiple of 5这可能会使low > high变得不可行,因此不再继续;或者它可能会使low == high变得毫无意义,所以您可能想要测试一下。下面的代码在任何一种情况下都能正常工作,因为+1和-1:在{low..high}中生成随机数
int randomPart = r.nextInt(high-low+1)+low-1;然后向上舍入到5的倍数。前面与low和high的恶作剧确保了它在范围内:
int nextInt = ((randomPart+4)/5)*5;https://stackoverflow.com/questions/19341074
复制相似问题