|
| 1 | +/** |
| 2 | + * Count the numbers divisible by ‘M’ in a given range |
| 3 | + * |
| 4 | + * @see {@link https://www.tutorialspoint.com/count-the-numbers-divisible-by-m-in-a-given-range-in-cplusplus} |
| 5 | + * |
| 6 | + * We have 3 numbers A, B, M as inputs, A and B defines the numbers range [A, B] |
| 7 | + * Count the total number of divisibles in that range by number M |
| 8 | + * |
| 9 | + * @author Chetan07j |
| 10 | + */ |
| 11 | + |
| 12 | +/** |
| 13 | + * Function to find total divisibles in given range |
| 14 | + * |
| 15 | + * @param {number} num1 |
| 16 | + * @param {number} num2 |
| 17 | + * @param {number} divider |
| 18 | + * |
| 19 | + * @returns {number} count of total number of divisibles |
| 20 | + */ |
| 21 | +const countNumbersDivisible = (num1, num2, divider) => { |
| 22 | + if (typeof num1 !== 'number' || typeof num2 !== 'number' || typeof divider !== 'number') { |
| 23 | + throw new Error('Invalid input, please pass only numbers') |
| 24 | + } |
| 25 | + |
| 26 | + // Valid number range is num1 < num2, otherwise throw error |
| 27 | + if (num1 > num2) { |
| 28 | + throw new Error('Invalid number range, please provide numbers such that num1 < num2') |
| 29 | + } |
| 30 | + |
| 31 | + // if divider is out of range then return 0 |
| 32 | + // as in such case no divisible exists |
| 33 | + if (divider > num2) { |
| 34 | + return 0 |
| 35 | + } |
| 36 | + |
| 37 | + // Find the number of multiples of divider for num1 and num2 |
| 38 | + // integer division part |
| 39 | + const num1Multiplier = num1 / divider |
| 40 | + const num2Multiplier = num2 / divider |
| 41 | + |
| 42 | + // The count of numbers divisibles by divider between num1 and num2 |
| 43 | + let divisibleCount = num2Multiplier - num1Multiplier |
| 44 | + |
| 45 | + // If num1 is divisible by divider then, edge case for num1 is ignored |
| 46 | + // which results in 1 less count |
| 47 | + // to fix that we add +1 in this case |
| 48 | + if (num1 % divider === 0) { |
| 49 | + divisibleCount++ |
| 50 | + } |
| 51 | + |
| 52 | + // As it includes integer division meaning floating values |
| 53 | + // to get exact count Math.round() is added |
| 54 | + return Math.round(divisibleCount) |
| 55 | +} |
| 56 | + |
| 57 | +export { countNumbersDivisible } |
0 commit comments