如何生成指定范围内的可被5整除的随机整数? [英] How do you generate a random integer in a specified range, divisible by 5?

查看:170
本文介绍了如何生成指定范围内的可被5整除的随机整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个整数范围,如何生成一个在该范围内可被5整除的随机整数?

我正在使用Java

解决方案

只需生成一个规则的随机整数并将其乘以5!

详细信息:[0, n)中生成一个随机整数,其中n是您范围内5的倍数,然后乘以5并向其添加最低的倍数.

单线: System.out.println(rnd.nextInt(max / 5 - (min + 4) / 5 + 1) * 5 + (min + 4) / 5 * 5);(假定非负有效参数)

功劳:最低的多重表达式(min + 4) / 5 * 5来自此处,并且表达式简化了一些基础@Thomas的答案(当前imo上不正确)

Given a range of integers, how do I generate a random integer divisible by 5 in that range?

I'm using Java

解决方案

just generate a regular random integer and multiply it by 5!

details: generate a random integer in [0, n) where n is the number of multiples of 5 in your range, then multiply it by 5 and add the lowest multiple to it.

one-liner: System.out.println(rnd.nextInt(max / 5 - (min + 4) / 5 + 1) * 5 + (min + 4) / 5 * 5); (assuming non-negative and valid arguments)

credits: lowest multiple expression (min + 4) / 5 * 5 from here and expression simplified a bit based on @Thomas's (imo currently incorrect) answer

这篇关于如何生成指定范围内的可被5整除的随机整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆