Social navigation

Codility – Count Divisible

Solution to Codility lesson3-exercise1 Count Divisible problem, link to Codility problem and complete solution at the end of the post.

Definitions:

Problem:Define a function solution with input A, B and K, such that solution returns the number of integers divisible by K , belonging to the interval [A, B].

Expected worst-case time complexity is O(1);

Expected worst-case space complexity is O(1);

Elements of input arrays can be modified.

Analysis:

The solution to this problem is pretty simple, the integers divisible by K, are the ones described by

.

gives us all divisible integers from 1 to B,

.
Now we just have to subtract the integers that dot not belong to the interval [A, B]. We have to be careful here, since A belongs to the interval, if A is divisible we have count it, so when excluding, we are going to do

. And the solution is

We are doing only one operation to solve this problem, so this gives us, time complexity and space complexity of O(1);