- Home /
Not a Unity Question
Division Sum Generator problem
I've got a sum generator for an educational game I'm working on, I've got it working for addition, subtraction and multiplication but I'm having trouble coming up with a division sum generator, I need a way of making the second number a divisor of the first number, I'm just not sure how to go about doing that, any help is appreciated. Here's my existing code:
//Plus Problem Setup
void Plus()
{
Sign.text = "+";
number1 = Random.Range (1, 11);
number2 = Random.Range (1, 11);
answer = number1 + number2;
}
//Minus Problem Setup
void Minus()
{
Sign.text = "-";
number1 = Random.Range (1, 21);
number2 = Random.Range (1, number1);
answer = number1 - number2;
}
//Multiplication Problem Setup
void Multiplication()
{
Sign.text = "x";
number1 = Random.Range (1, 11);
number2 = Random.Range (1, 11);
answer = number1 * number2;
}
//Division Problem Setup
void Division()
{
Sign.text = "÷";
number1 = Random.Range (1, 21);
number2 = Random.Range (1, number1);
answer = number1 / number2;
}
Not a Unity Question. You can do it this way:
do {
number2 = Random.Range (1, number1+1);
} while (number1 % number2 != 0);
Note I'm assu$$anonymous$$g eventually this code will find '1' if the number is prime, but given computer Random, that may not be a sure thing. I always hesitate to put in any code that has the potential to hang. It might be better to make an attempt for some fixed number of trys, and if it fails, generate a new Random number:
int i = 0;
do {
i++;
if (i > 1000) {
number1 = Random.Rangle(1, 21);
i = 0;
}
number2 = Random.Range (1, number1+1);
} while (number1 % number2 != 0);
Note on the 'number1+1'. Unity Random.Range() is exclusive on the final value (i.e. it does not generate it) for integers. If I did not do that, and your number1 was assigned 1, then your code would hang.
I know this has been closed but just to point out, you could do this inversely by working out number1 based on a random pick of number2 and multiplying it by something, then you know for sure if divides to give 'something':
number2 = Random.Range (1, 21);
number1 = Random.Range (1, $$anonymous$$athf.CeilToInt(21f/(float)number2))*number2;
answer = number1/number2;
Scribe