Problem Description: Write function divisibleCount(x, y, k) that takes in 3 numbers x, y and k, and returns the number of integers within the range [x..y] that are divisible by k i.e.:
{ i : x ≤ i ≤ y, i mod k = 0 }
For example:
x = 6, y = 11 and k = 2, your function should return 3, because there are three numbers divisible by 2 within the
range [6..11], namely 6, 8 and 10.
Note: x<=y
Level:6kyu
Link To Kata: Count the divisible numbers
This array at first look seems to be a basic problem where we can loop from the starting range to the end range and count the numbers divisible by the given number. But there is the catch. This naive solution ends up slowing down our algorithm which results in time limit exceeded.
So in order to solve this Kata we take a much more algorithmic approach. We first of all find the remainder of starting range number by using a modulus operator against the divisor. If the divisor is not equal to 0 then we add the difference of divisor and remainder to x. Next we subtract the remainder in case of end range number using the same method from the end range number.
Then if we start range is greater then end range we conclude that there is no such number in our given range which is completely divided by our divisor. We return a 0 as the solution to this kata.
Otherwise we divide the difference of end range and start range by our divisor. We add 1 to the value which we get after dividing and return the sum as the solution to this Kata.
Please go through the code for a better understanding.
Here is the link to code: Kata Day 44
Please mention your suggestions or your doubts in the comment below.
Happy coding. :)
No comments:
Post a Comment