Matt Barker
Matt Barker

Reputation: 11

Generating random simple math division problems

I'm making a simple Android app for my daughter so she can do math problems. I found it fairly easy to generate addition, subtraction and multiplication questions at random, however division is more tricky.

I don't want to get into decimals, so I have to check each is divisible without remainder. This is what I am working with...

public void genDivQuestion() {
        text = (TextView) findViewById(R.id.textView1);
        text.setText(divisible());
        answer = first / second;
}

public String divisible() {
        first = RandomNumGen.getRandIntBetween(2, 12);
        second = RandomNumGen.getRandIntBetween(2, 12);
        if (first % second == 0) {
            return first + " \u00F7 " + second + " = ?";
        } else {
            return "0";
        }
}

I'm not sure what to do at the line "return "0";". If I try calling divisible() to try again, the app just crashes.

This is the RandomNumGen class, which I appropriated from a beginner's book by James Cho:

import java.util.Random;

public class RandomNumGen {

    private static Random rand = new Random();

    public static int getRandIntBetween(int lowerBound, int upperBound) {
        return rand.nextInt(upperBound - lowerBound) + lowerBound;
    }

    public static int getRandInt(int upperBound) {
        return rand.nextInt(upperBound);
    }
}

Upvotes: 1

Views: 2139

Answers (1)

Gil Moshayof
Gil Moshayof

Reputation: 16771

Instead of drawing 2 random numbers and checking if they are divisible with each other, try the following:

first = someRandomNumber(2, 12);
second = someRandomNumber(2, 12);

showDivisionProblem(first * second, first)

Here the problem will ask you to divide first * second by first, where the answer should be second.

For example:

3 * 2 / 2 --> 6 / 2 = 3

No need to run in a loop until you find 2 good numbers. This way, the numbers will always be dividable.

Edit:

if it's important to limit the two operands by 12, then consider the following:

first = someRandomNumber(2, 12);
second = someRandomNumber(1, 12 / first);

where first is of type int.

In this case, if first is any value above 6, second is forced to be 1. If first is any value between 6 and 4, second can be 1 or 2 If first is 4, second can be 1, 2 or 3 etc.

Upvotes: 2

Related Questions