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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With