-3

Fairly basic question but I need something that can make var n = Math.random() to give me "n" as a positive odd integer How do I do this?

Atom Vayalinkal
  • 2,642
  • 7
  • 29
  • 37

2 Answers2

2

Generate an integer in the appropriate range, multiply it by 2, then add 1.

For example if you want odd integers between 1 and 99 then generate a random integer in the range 0 to 49.

Related

Community
  • 1
  • 1
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
1

Generate the number in desired range and then make it ODD if it is not.

    //<-Generate the number between 0 to MAX 
    int randNum=   (int)(Math.random()*MAX_VALUE); 
    if(randNum %2 == 0){//generated number is even
       if(randNum == MAX_VALUE){
         randNum  = randNum -1 ;
       }else{
         randNum  = randNum +1 ;
       }
    }

Now the random number is an odd number within the range

Yogendra Singh
  • 33,927
  • 6
  • 63
  • 73