Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Randomly generate odd numbers in the range [duplicate]

Tags:

java

random

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?

like image 422
Falconx Avatar asked Dec 02 '22 16:12

Falconx


1 Answers

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.

like image 91
Luigi Cortese Avatar answered Dec 27 '22 19:12

Luigi Cortese