Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Generating a random number that is divisible by n in JavaScript
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.
Example
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;
};
console.log(specialRandom(num));
Output
And the output in the console will be −
6006
This output is likely to differ on each run.
Advertisements
