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.
a = 6 b = 9 k = 2 Should return 2
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.)
anis the nth multiple
a1is the starting multiple
nis the number of multiples
We can solve for n to get
n = ( (an - a1) / k) + 1)
We can then calculate our other variables as
And put everything together to get
And that’s it.