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.)
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.
Today I am working on a summation problem made to look like building a tower out of cubic bricks. It’s fun to brute force sometimes.
Coming back to Rust code after a bit of a hiatus with a simple problem… The Two-sum problem. Finding numbers in an array. Yay, fun.
King Pinn: I Salute You. I’m driving halfway across the country and this song is on repeat. Rest in Peace Tonderai Makoni. You were awesome.
After a few weeks off I’m back to business. This is just an update post detailing plans for the rest of the year.
At last we finally have the great reveal, our mystery project was implementing RSA encryption in rust.