IT/알고리즘

코딜리티 - CountDiv(c++)

반응형

문제

Write a function:

int solution(int A, int B, int 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.

 

풀이

(B를 K로 나눈 몫 - A를 K로 나눈 몫 + 1) 를 하면 그 사이에 K로 나눠지는 값들을 구할 수 있다.

한 가지 주의할 점은 A를 K로 나눌 때 나누어 떨어지지 않으면 범위 안에 들어가지 않으므로 +1을 해준다.

int solution(int A, int B, int K) {
    int range_A = (A%K == 0) ? A/K : A/K + 1;
    return B/K - range_A + 1;
}

 

반응형