如何用JavaScript生成3个100-999间可被5整除的随机整数
解决方法:生成100-999间可被5整除的随机整数
下面给你两种可行的实现方式,按需选择即可:
方法1:直接计算符合条件的范围(高效无重试)
100到999之间,能被5整除的最小数是100(100 = 5×20),最大数是995(995 = 5×199)。我们可以先锁定这个有效区间,直接生成对应范围内的随机数,避免重复生成无效值:
const min = 100; const max = 999; // 算出范围内能被5整除的最小/最大值 const minDiv5 = Math.ceil(min / 5) * 5; const maxDiv5 = Math.floor(max / 5) * 5; // 计算符合条件的数的总个数 const totalValidNums = (maxDiv5 - minDiv5) / 5 + 1; // 封装生成符合条件随机数的函数 const getRandomDiv5 = () => { const randomIndex = Math.floor(Math.random() * totalValidNums); return minDiv5 + randomIndex * 5; }; const a = getRandomDiv5(); const b = getRandomDiv5(); const c = getRandomDiv5(); console.log(`${a} ${b} ${c}`);
方法2:生成后筛选(逻辑简单易理解)
如果觉得上面的计算有点绕,也可以先生成100-999的随机数,检查是否能被5整除,不符合就重新生成,直到得到有效数:
const min = 100; const max = 999; // 封装生成函数 const getRandomDiv5 = () => { let num; do { num = Math.floor(Math.random() * (max - min + 1)) + min; } while (num % 5 !== 0); return num; }; const a = getRandomDiv5(); const b = getRandomDiv5(); const c = getRandomDiv5(); console.log(`${a} ${b} ${c}`);
两种方法都能输出符合要求的结果,第一种无需重试效率更高,第二种逻辑直白,适合新手快速上手。
内容的提问来源于stack exchange,提问作者TwoSeconds
相关产品推荐
相关产品推荐

