[Codility] Lesson-05.1: CountDiv

YeongHyeon Park
2 min readDec 12, 2020

--

This post deals with the problem of counting the number of elements whose remainder is 0 when divided by a specific value in a given array.

Task Description

Write a function:

def solution(A, B, K)

that, given three integers A, B and K, returns the number of integers within the range [A..B] that are divisible by K, i.e.:

{ i : A ≤ i ≤ B, i mod K = 0 }

For example, for A = 6, B = 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.

Write an efficient algorithm for the following assumptions:

  • A and B are integers within the range [0..2,000,000,000];
  • K is an integer within the range [1..2,000,000,000];
  • A ≤ B.

Copyright 2009–2020 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

Key Point

  • When linear searching for a long-range array, time consumption will be longer.
  • After dividing 0 with any value, the result is 0.

Solution (using Python)

def solution(A, B, K):
bound_1, bound_2 = (A / K), (B / K) // 1
if(bound_1 != 0 and bound_1 % 1 == 0): bound_1 -= 1
bound_1 = bound_1 // 1
answer = max(int(bound_2 - bound_1), 0)
if(A == 0): answer += 1
return answer

Please use the above solution for reference.
I recommend you to write your own source code.

--

--

No responses yet