Skip to content

Commit 31053e2

Browse files
committed
Add countNumbersDivisible algorithm with improved logic
1 parent 08d8c6b commit 31053e2

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

src/Math/countNumbersDivisible.js

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
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 (
23+
typeof num1 !== 'number' ||
24+
typeof num2 !== 'number' ||
25+
typeof divider !== 'number'
26+
) {
27+
throw new Error('Invalid input, please pass only numbers')
28+
}
29+
30+
// Valid number range is num1 < num2, otherwise throw error
31+
if (num1 > num2) {
32+
throw new Error(
33+
'Invalid number range, please provide numbers such that num1 < num2'
34+
)
35+
}
36+
37+
// if divider is out of range then return 0
38+
// as in such case no divisible exists
39+
if (divider > num2) {
40+
return 0
41+
}
42+
43+
// Divider cannot be zero, as division by zero is invalid
44+
if (divider === 0) {
45+
throw new Error('Divider cannot be zero')
46+
}
47+
48+
// Find the number of multiples of divider for num1 and num2
49+
// using integer division for accurate counting
50+
const divisibleCount =
51+
Math.floor(num2 / divider) - Math.floor((num1 - 1) / divider)
52+
53+
return divisibleCount
54+
}
55+
56+
export { countNumbersDivisible }

0 commit comments

Comments
 (0)