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
-
Economics & Finance
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.
Approach
To generate a random number divisible by n, we generate a random number within a range, divide it by n, round the result, and multiply back by n. This ensures the final number is always a multiple of n.
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.
How It Works
The function works by:
- Generating a random decimal between 0 and the limit (1,000,000)
- Dividing by the target number (n) to get how many "groups" of n fit
- Rounding to the nearest integer to get whole groups
- Multiplying back by n to get the final divisible number
Multiple Examples
// Generate numbers divisible by different values
console.log("Divisible by 5:", specialRandom(5));
console.log("Divisible by 10:", specialRandom(10));
console.log("Divisible by 25:", specialRandom(25));
console.log("Divisible by 100:", specialRandom(100));
// With custom limit
console.log("Divisible by 7 (limit 500):", specialRandom(7, 500));
Divisible by 5: 245580 Divisible by 10: 567890 Divisible by 25: 123450 Divisible by 100: 456700 Divisible by 7 (limit 500): 287
Conclusion
This method efficiently generates random numbers divisible by any given value by using mathematical operations to ensure the result is always a perfect multiple. The approach scales well with different limits and divisors.
