我正在尝试在android中重新生成随机数。我想生成两个可以互相整除的数字。如果生成的数字不可分,我希望系统再次尝试,直到它生成可相互整除的数字。
这是我的代码:
Random random = new Random();
arrone = random.nextInt(100 - 20) + 20;
Random randm = new Random();
arrtwo = randm.nextInt(11 - 2) + 2;
if (arrone % arrtwo ==0){
// if they are divisible do this.
} else {
// if they are not divisible, I want it to try again and find two divisble numbers
}
答案 0 :(得分:3)
要重新解决问题,您需要两个数字,其中一个是另一个的倍数。显着的区别是你不需要使用循环来找到这样的一对值。
int min = 20;
int max = 100;
int second = rand.nextInt(11 - 2) + 2;
int multiplier = Math.max((min + second-1)/second,
rand.nextInt(max / second) + 1);
int first = multiplier * second;
在这种情况下,你知道第一个必须可以被第二个整除。
答案 1 :(得分:0)
boolean divisible = false;
while (!divisible ) {
Random random = new Random();
arrone = random.nextInt(100 - 20) + 20;
Random randm = new Random();
arrtwo = randm.nextInt(11 - 2) + 2;
if (arrone % arrtwo == 0){
// if they are divisible do this.
divisible = true;
}
}
}