본문 바로가기

Lesson 5. Perfix Sums - CountDiv #1

반응형

1. 문제

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.

A부터 B까지의 정수 중, K로 나누어 떨어지는 정수의 갯수를 구하는 문제.

 

2. 매개변수 조건

  • A <= B
  • A, B 값 : 0 ~ 2,000,000,000
  • K 값 : 1 ~ 2,000,000,000

 

3. 코드 (C++)

K값으로 나누어 떨어지는지 하나씩 확인한다.

int solution(int A, int B, int K) {

    int cnt = 0;
    for(int i = A; i <= B; i++)
    {
        if(i % K == 0) cnt++;
    }    

    return cnt;
}

 

 

4. 결과

반응형