dimanche 30 décembre 2018

How to generate a random number that is evenly divisible by another randomly generated number in JavaScript

I'm working on a simple math flashcards app using JavaScript and jQuery. The available operations are addition, subtraction, multiplication, and division, each of which have functions that use generateTop() and generateBottom() to assign values to HTML elements.

I'm having trouble figuring out how to use my division problem function to generate random numbers so that the topNumber is evenly divisible by the bottomNumber. I'm using the following code to generate random numbers for each problem:

let topNumber = 0;
let bottomNumber = 0;

function generateTop(max, min){
  topNumber = Math.floor(Math.random() * (max - min) + min);
  return topNumber;
};

function generateBottom(max, min){
  bottomNumber = Math.floor(Math.random() * (max - min) + min);
  return bottomNumber;
};

Here is my current division problem generator:

function division(){
  problemTop.html(generateTop(1, 144));
  problemBottom.html(generateBottom(1, topNumber));
  opSym.html("÷");
}

I can adjust the max and min to get a positive integer for addition, subtraction, and multiplication problems but am stuck on how to ensure that I get a positive integer for division problems. I've tried messing with some different loop ideas but haven't gotten anything to work. I want to keep min at 1 and max at 144.

I've checked SO for solutions but can only find how to generate random numbers divisible by one other explicit, hard-coded number. How can I adjust my division function so that the topNumber can be divided evenly by the bottomNumber? Any help is greatly appreciated.




Aucun commentaire:

Enregistrer un commentaire