Rm R
Rm R

Reputation: 43

generate two random number with specific rules

I'm writing a code that generate two random integer and display the result of dividing the first number by the second. I want the first integer to be more than the second integer and the result of the division without remainder (an integer number)

I tried using do while loop and continue to change the integers until it generate the numbers as I wanted.

std::random_device device;
std::mt19937 rd(device());
std::uniform_int_distribution<int> random(1, 100);

int firstNumber;
int secondNumber;

do
{
    firstNumber = random(rd);
    secondNumber = random(rd);
}
while ((firstNumber < secondNumber) && (firstNumber % secondNumber != 0));

int result = firstNumber / secondNumber;

//print the integer to check it
std::cout << firstNumber << std::endl; 
std::cout << secondNumber << std::endl;

each time I run this code it always give me the first integer more than the second. but the division result will be with remainder

Upvotes: 1

Views: 365

Answers (3)

rossum
rossum

Reputation: 15693

  1. Pick the first number randomly: num1.

  2. Pick a second number > 1 randomly: num2.

  3. Your larger number is num1 * num2. Your smaller number is num1. The result of the division is num2.

Upvotes: 0

Adrian Mole
Adrian Mole

Reputation: 51864

Your loop check is wrong! Try this …

do
{
    firstNumber = random(rd);
    secondNumber = random(rd);
} while ((firstNumber <= secondNumber) || (firstNumber % secondNumber != 0));

You need to keep running the loop until both conditions are met, so if either one __or__ the other is not, keep trying!

Also, if you have < as your first comparison, rather than <=, chances are you'll get both numbers the same.

Upvotes: 3

Bathsheba
Bathsheba

Reputation: 234785

You have a few bugs in your conditional checks. But another approach would be to generate the first number based on the result of the second number drawing:

std::uniform_int_distribution<int> random(1, 50);
secondNumber = random(rd);
{
    std::uniform_int_distribution<int> random(2, 100 / secondNumber);
    firstNumber = random(rd) * secondNumber;
}

which eliminates the need for a condition check.

Upvotes: 2

Related Questions