在范围内随机生成奇数

5
我正在尝试随机生成奇数。我尝试了以下方法,但是它也会生成偶数:
int coun=random.nextInt();
for(int i=1; i<100; i++){
    if(i%2==1){
      coun=random.nextInt(i);
    }
}

怎样随机生成奇数?

2
请查看以下链接:https://dev59.com/-WjWa4cB1Zd3GeqPu94U - Michele Lacorte
1
random.nextInt(i) 返回一个介于0和i之间的随机值,因此确保i为奇数并不能确保返回一个奇数值。 - Michael
你不能保证random.nextInt()会返回一个奇数或偶数,因为它是随机的;但是你可以处理random.nextInt()的输出并确保整体结果是奇数。 - QuakeCore
4个回答

9

您可以将1添加到偶数

    int x=(int) (Math.random()*100);
    x+=(x%2==0?1:0);

或者将数字乘以2再加1

    int x=(int) (Math.random()*100);
    x=x*2+1;

许多可能的解决方案。

在第二种解决方案中,如果您想要从1到9的范围,则输出可能比9大15! - Falconx
1
你的问题没有指定任何限制,这只是一些例子而已。 - Luigi Cortese

4

所有形如 2*n + 1 的数字都是奇数。因此,生成随机奇数的一种方法是,生成一个随机整数,将其乘以2,再加上1:

int n = random.nextInt();
int r = 2 * n + 1; // Where r is the odd random number

对于每个随机数 n,都会生成一个唯一的奇数随机数r(换句话说,这是一个双射函数),从而确保了无偏差性(或者至少与函数random.nextInt()一样无偏差)。


但是如果你想要1到10之间的奇数呢?当你执行2 * n + 1操作时,它会给出大于10的数字。 - Falconx
然后确保您生成一个 n,使得 2 * n + 1 < 10。或者,n < (9/2) = 4。我认为 Peter has a solution 可以帮到您。 - John Bupit
@user1364513 然后请求从1到4的随机数。 - fps

4

在0和100之间有50个奇数。要选择其中一个,可以执行以下操作:

int n = random.nextInt(50);

要得到第 n 个奇数,您可以

int odd = n * 2 + 1;

将所有内容整合在一起

int odd = random.nextInt(max / 2) * 2 + 1;

1

一种解决方案是测试随机整数值是否为奇数。如果不是,则可以有一半的概率加上或减去1。

Random random = new Random();
int i = random.nextInt();
if (i % 2 == 0) {
    i += random.nextBoolean() ? 1 : -1;
}

1
nextInt() 已经包含了所有可能的 int 值。如果每次只加 1,就不会有偏差。 - Peter Lawrey
@PeterLawrey 是因为整数溢出的原因吧?否则,Integer.MIN_VALUE+1 永远不可能被生成。 - Tunaki
2
是的,由于溢出和下溢的存在,加一或减一并不重要,你会得到相同的分布。 - Peter Lawrey

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接