简体   繁体   中英

Generate random numbers that can be divided by 2

I need to generate random numbers that can be divided by 2 so : 2 4 6 8 10 12 14 16 18 .....

My code looks like:

Random random = new Random();
int i = random.nextInt(20);

Hopefully you know what I want and you can help me.

Just multiply i by 2

Random random = new Random();
int i = random.nextInt(20) * 2;

And adjust the random upper bound if you want to stay under 20 (replace by 10)

int i = random.nextInt(10) * 2;

The loop version is too heavy and ineficient in my opinion

只是:

int number = new Random().nextInt(10) * 2;

Check the remainder/modulus of the result and if it is 1, add 1 to i to give an even number:

Random random = new Random();
int i = random.nextInt(20);
if(i%2 == 1){
    i++;
}

Deterministic approach -

Random random = new Random();
...
private int generateRandomDividedByTwo(){
   int i = -1;
   do{
      i = random.nextInt(20);
   }while(i%2!=0);
   return i;
}
int number = 100; //number of numbers you want to generate
for(int i = 0; i < number; i++) {
    int rand = random.nextInt(number);
    while(rand % 2 != 0) {
        rand = random.nextInt(number);
    }
    System.out.println(rand);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM