diff --git a/Maths/CountNumbersDivisible.js b/Maths/CountNumbersDivisible.js index 632011f107..cc66d99ad2 100644 --- a/Maths/CountNumbersDivisible.js +++ b/Maths/CountNumbersDivisible.js @@ -34,30 +34,10 @@ const countNumbersDivisible = (num1, num2, divider) => { ) } - // if divider is out of range then return 0 - // as in such case no divisible exists - if (divider > num2) { - return 0 - } - - // Find the number of multiples of divider for num1 and num2 - // integer division part - const num1Multiplier = num1 / divider - const num2Multiplier = num2 / divider - - // The count of numbers divisibles by divider between num1 and num2 - let divisibleCount = num2Multiplier - num1Multiplier - - // If num1 is divisible by divider then, edge case for num1 is ignored - // which results in 1 less count - // to fix that we add +1 in this case - if (num1 % divider === 0) { - divisibleCount++ - } - - // As it includes integer division meaning floating values - // to get exact count Math.round() is added - return Math.round(divisibleCount) + const positiveDivider = Math.abs(divider) + return ( + Math.floor(num2 / positiveDivider) - Math.ceil(num1 / positiveDivider) + 1 + ) } export { countNumbersDivisible } diff --git a/Maths/test/CountNumbersDivisible.test.js b/Maths/test/CountNumbersDivisible.test.js index f497cfe726..6e11e73b2c 100644 --- a/Maths/test/CountNumbersDivisible.test.js +++ b/Maths/test/CountNumbersDivisible.test.js @@ -1,6 +1,36 @@ import { countNumbersDivisible } from '../CountNumbersDivisible' describe('Count the numbers divisible', () => { + test.each([ + [2, 3, 2, 1], + [0, 0, 3, 1], + [0, 2, 3, 1], + [-6, -2, 2, 3], + [-6, -2, -2, 3] + ])( + 'should count the inclusive range [%i, %i] for divisor %i', + (a, b, m, n) => { + expect(countNumbersDivisible(a, b, m)).toBe(n) + } + ) + + test('should agree with direct enumeration of small integer ranges', () => { + for (let lower = -5; lower <= 5; lower++) { + for (let upper = lower; upper <= 5; upper++) { + for (const divisor of [-5, -2, -1, 1, 2, 5]) { + const values = Array.from( + { length: upper - lower + 1 }, + (_, index) => lower + index + ) + const expected = values.filter( + (value) => value % divisor === 0 + ).length + expect(countNumbersDivisible(lower, upper, divisor)).toBe(expected) + } + } + } + }) + test.each([ [1, 20, 6, 3], [6, 15, 3, 4],