5

I'm trying to generate odd numbers randomly. I tried this, but it generates even numbers also:

int coun=random.nextInt();
for(int i=1; i<100; i++){
    if(i%2==1){
      coun=random.nextInt(i);
    }
}

How can I generate odd numbers randomly?

Falconx
  • 279
  • 2
  • 4
  • 11
  • 2
    check this http://stackoverflow.com/questions/12594974/generating-an-odd-random-number-between-a-given-range – Michele Lacorte Sep 13 '15 at 20:03
  • 1
    `random.nextInt(i)` returns a random value between 0 and `i`, so ensuring that `i` is odd won't ensure an odd value is returned – Michael Sep 13 '15 at 20:05
  • you cant guarantee that random.nextInt () will return a an odd or even number,its random, how ever you can process the output of random.nextInt () and ensure that the overall result is odd. – QuakeCore Sep 13 '15 at 20:08

4 Answers4

9

You could add 1 to even numbers

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

or multiply the number by 2 and add one

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

a lot of possible solutions.

Luigi Cortese
  • 10,841
  • 6
  • 37
  • 48
4

All numbers of the form 2*n + 1 are odd. So one way to generate a random odd number would be, to generate a random integer, multiply it by 2, and add 1 to it:

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

For each random number n, there is a unique odd random number r generated (in other words, it is a bijection) - thus ensuring unbiasedness (or at least, as much unbiasedness as the function random.nextInt()).

John Bupit
  • 10,406
  • 8
  • 39
  • 75
  • But what about if you want odd nums from 1 to 10? then when you do this operation 2 * n + 1 it will give more than 10 – Falconx Sep 13 '15 at 20:22
  • Then make sure that you generate an `n` such that `2 * n + 1 < 10`. Or, `n < (9/2) = 4`. I think [Peter has a solution](http://stackoverflow.com/a/32554155/1492578) for you. – John Bupit Sep 13 '15 at 20:24
  • @user1364513 Then ask for random numbers from 1 to 4 – fps Sep 13 '15 at 20:25
4

There is 50 odd numbers between 0 and 100. To select one of them you can do

int n = random.nextInt(50);

to get the n-th odd number you can

int odd = n * 2 + 1;

Putting it all together

int odd = random.nextInt(max / 2) * 2 + 1;
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
1

One solution would be to test wheter the random integer value is odd or not. If it is not, you can add or subtract one with half probability.

Random random = new Random();
int i = random.nextInt();
if (i % 2 == 0) {
    i += random.nextBoolean() ? 1 : -1;
}
Tunaki
  • 132,869
  • 46
  • 340
  • 423