Codility 'CountDiv' Solution

Martin Kysel · August 4, 2014

Short Problem Definition:

Compute number of integers divisible by k in range [a..b].



expected worst-case time complexity is O(1)

expected worst-case space complexity is O(1)


This little check required a bit of experimentation. One needs to start from the first valid value that is bigger than A and a multiply of K.


def solution(A, B, K):
    if B < A or K <= 0:
        raise Exception("Invalid Input")

    min_value =  ((A + K -1) // K) * K

    if min_value > B:
      return 0

    return ((B - min_value) // K) + 1

Twitter, Facebook