Codility 'CountDiv' Solution

Martin Kysel · August 4, 2014

Short Problem Definition:

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

CountDiv

Complexity:

expected worst-case time complexity is O(1)

expected worst-case space complexity is O(1)

Execution:

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.

Solution:

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

To learn more about solving Coding Challenges in Python, I recommend these courses: Educative.io Python Algorithms, Educative.io Python Coding Interview.