Generating a random number that is divisible by n in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in a number as the only argument. The function should then return a random generated number which is always divisible by the number provided by the argument.


The code for this will be −

const num = 21;
// function that generates random numbers divisible by n with a default
upper limit of 1000000
const specialRandom = (num = 1, limit = 1000000) => {
   // getting a random number
   const random = Math.random() * limit;
   // rounding it off to be divisible by num
   const res = Math.round( random / num ) * num;
   return res;


And the output in the console will be −


This output is likely to differ on each run.

Updated on 21-Nov-2020 10:18:33