Code Corner: Counting Multiples


Problem

We are given 3 numbers, a starting number A, an ending number B and an integer K, find the number of multiples of K there is between A and B inclusive.

Source

Example

a = 6
b = 9
k = 2
Should return 2

My solution

The ranges are irrelevant because this is a maths problem and thus regardless of whatever we enter we will always solve this in constant time. The formula we use is the one to calculate the n-th term for the sequence of multiples of k starting at the first multiple greater than or equal to a. This looks like:

an = a1 + (n - 1)k.  (I can explain this equation if anyone is interested.)

Where

  • an is the nth multiple
  • a1 is the starting multiple
  • n is the number of multiples

We can solve for n to get n = ( (an - a1) / k) + 1)

We can then calculate our other variables as

an = Math.floor(b / k) * k
a1 = Math.ceil(a / k) * k
Code language: JavaScript (javascript)

And put everything together to get

function solution(a, b, k) {
    const a1 = Math.ceil(a / k) * k
    const an = Math.floor(b / k) * k
    return ((an - a1) / k) + 1
}
Code language: JavaScript (javascript)

And that’s it.


Leave a Reply

Your email address will not be published. Required fields are marked *