AndroidUSER
AndroidUSER

Reputation: 11

Re-Generate Random Number. Android?

I am trying to re-generate random numbers in android. I want to generate two numbers which are divisible by each other. If the generated numbers are not divisible, I want the system to try again until it generates numbers which are divisible by each other.

Here is my code:

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  

            }

Upvotes: 0

Views: 107

Answers (2)

Peter Lawrey
Peter Lawrey

Reputation: 533820

To rephrase the problem, you want two numbers where one is a multiple of the other. The significant difference is you don't need to use a loop to find such a pair of values.

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;

In this case, you know the first must be divisible by the second.

Upvotes: 3

gerbit
gerbit

Reputation: 962

    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;
        }
    }
}

Upvotes: 0

Related Questions