0

I don't know how to make the random numbers print only the ones that are divisible by 5

PS: I am a newbie

const min = 100;
const max = 999;

const a = Math.floor(Math.random() * (max - min + 1)) + min;
const b = Math.floor(Math.random() * (max - min + 1)) + min;
const c = Math.floor(Math.random() * (max - min + 1)) + min;

console.log(`${a} ${b} ${c}`);

// Sample output should be: 145 570 865
  • you can use remainder https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Remainder operator – SuleymanSah Oct 26 '22 at 14:26
  • Does this answer your question? [What does % do in JavaScript?](https://stackoverflow.com/questions/8900652/what-does-do-in-javascript) – SuleymanSah Oct 26 '22 at 14:27
  • 1
    You can use the Remainder (`%`) operator to detect whether a number is divisible by another number. But you'd be wiser to only select from a list of values that has already been restricted to valid values that are divisible by 5. Otherwise you'll be doing a lot of extra iterating while you wait for your random number generator to give you something divisible by 5. – Marc Oct 26 '22 at 14:29
  • 1
    Does this answer your question? https://stackoverflow.com/questions/50560493/javascript-generating-a-random-number-that-can-be-divided-by-5 – Reyno Oct 26 '22 at 14:29

2 Answers2

3

Think about it. To make sure your numbers are divisible by 5, how about generating random numbers from range 5 times smaller and then multiply by 5?

Like if I wanted to generate 0, 5, 10, 15 or 20, I could randomly pick [0..4] and then multiply the result by 5. Voilà!

Robo Robok
  • 21,132
  • 17
  • 68
  • 126
0

The easiest way to get your first requirement is to multiple some number by your divisor (like @Robo Robok said)

  1. input * 5 = number devisable by 5

the next step is to bound your candidate numbers, you have an upper bound and a lower bound and they may not divide evenly so you'll have to round up and down

  1. upper bound = floor(upper bound / 5)
  2. lower bound = ceiling(lower bound / 5)

That range is what you want to use with your random number

  1. number range = upper bound - lower bound

So, if we take the range and multiply it by the random number and multipy it by 5 you have your generator.

  1. random number = (ceil(number range * random number)+lower bound) * 5

Because this was a JavaScript question:

rangedRandFactory = (multiple, min, max) => {
  const ceil = Math.floor(max/multiple);
  const floor = Math.ceil(min/multiple);
  const range = ceil - floor;
  return () => ((Math.ceil(range*Math.random()))+floor) * multiple
}
QueueHammer
  • 10,515
  • 12
  • 67
  • 91