Skip to content

Commit df7ba7f

Browse files
committed
fix: count divisible numbers correctly in inclusive ranges
1 parent 5c39e87 commit df7ba7f

2 files changed

Lines changed: 34 additions & 24 deletions

File tree

‎Maths/CountNumbersDivisible.js‎

Lines changed: 4 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -34,30 +34,10 @@ const countNumbersDivisible = (num1, num2, divider) => {
3434
)
3535
}
3636

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-
// Find the number of multiples of divider for num1 and num2
44-
// integer division part
45-
const num1Multiplier = num1 / divider
46-
const num2Multiplier = num2 / divider
47-
48-
// The count of numbers divisibles by divider between num1 and num2
49-
let divisibleCount = num2Multiplier - num1Multiplier
50-
51-
// If num1 is divisible by divider then, edge case for num1 is ignored
52-
// which results in 1 less count
53-
// to fix that we add +1 in this case
54-
if (num1 % divider === 0) {
55-
divisibleCount++
56-
}
57-
58-
// As it includes integer division meaning floating values
59-
// to get exact count Math.round() is added
60-
return Math.round(divisibleCount)
37+
const positiveDivider = Math.abs(divider)
38+
return (
39+
Math.floor(num2 / positiveDivider) - Math.ceil(num1 / positiveDivider) + 1
40+
)
6141
}
6242

6343
export { countNumbersDivisible }

‎Maths/test/CountNumbersDivisible.test.js‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,36 @@
11
import { countNumbersDivisible } from '../CountNumbersDivisible'
22

33
describe('Count the numbers divisible', () => {
4+
test.each([
5+
[2, 3, 2, 1],
6+
[0, 0, 3, 1],
7+
[0, 2, 3, 1],
8+
[-6, -2, 2, 3],
9+
[-6, -2, -2, 3]
10+
])(
11+
'should count the inclusive range [%i, %i] for divisor %i',
12+
(a, b, m, n) => {
13+
expect(countNumbersDivisible(a, b, m)).toBe(n)
14+
}
15+
)
16+
17+
test('should agree with direct enumeration of small integer ranges', () => {
18+
for (let lower = -5; lower <= 5; lower++) {
19+
for (let upper = lower; upper <= 5; upper++) {
20+
for (const divisor of [-5, -2, -1, 1, 2, 5]) {
21+
const values = Array.from(
22+
{ length: upper - lower + 1 },
23+
(_, index) => lower + index
24+
)
25+
const expected = values.filter(
26+
(value) => value % divisor === 0
27+
).length
28+
expect(countNumbersDivisible(lower, upper, divisor)).toBe(expected)
29+
}
30+
}
31+
}
32+
})
33+
434
test.each([
535
[1, 20, 6, 3],
636
[6, 15, 3, 4],

0 commit comments

Comments
 (0)