# 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

```.wp-block-code {
border: 0;
}

.wp-block-code > div {
overflow: auto;
}

.shcb-language {
border: 0;
clip: rect(1px, 1px, 1px, 1px);
-webkit-clip-path: inset(50%);
clip-path: inset(50%);
height: 1px;
margin: -1px;
overflow: hidden;
position: absolute;
width: 1px;
word-wrap: normal;
word-break: normal;
}

.hljs {
box-sizing: border-box;
}

.hljs.shcb-code-table {
display: table;
width: 100%;
}

.hljs.shcb-code-table > .shcb-loc {
color: inherit;
display: table-row;
width: 100%;
}

.hljs.shcb-code-table .shcb-loc > span {
display: table-cell;
}

.wp-block-code code.hljs:not(.shcb-wrap-lines) {
white-space: pre;
}

.wp-block-code code.hljs.shcb-wrap-lines {
white-space: pre-wrap;
}

.hljs.shcb-line-numbers {
border-spacing: 0;
counter-reset: line;
}

.hljs.shcb-line-numbers > .shcb-loc {
counter-increment: line;
}

.hljs.shcb-line-numbers .shcb-loc > span {
}

.hljs.shcb-line-numbers .shcb-loc::before {
border-right: 1px solid #ddd;
content: counter(line);
display: table-cell;
text-align: right;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
white-space: nowrap;
width: 1%;
}
```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.