룬아님의 취중코딩

codility 14번 CountDiv 본문

개발/알고리즘

codility 14번 CountDiv

룬아님 2019. 8. 26. 23:54

CountDiv

 

 

Write a function:

class Solution { public 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.

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

 

class Solution {
    public int solution(int A, int B, int K) {
        // write your code in Java SE 8
        int cnt = 0;
        for(int i=A; i<=B; i++){
            if(i%K == 0){
                cnt++;
                cnt += (B - i) / K;
                break;
            }
        }
        return cnt;
    }
}
class Solution {
    public int solution(int A, int B, int K) {
        return B/K - A/K + (A%K == 0 ? 1: 0);
    }
}

 

https://app.codility.com/demo/results/training2EGG9R-DTC/

https://app.codility.com/demo/results/trainingV6T2E7-7F2/

반응형

'개발 > 알고리즘' 카테고리의 다른 글

Codility 16번 Triangle  (0) 2019.09.01
Codility 13번 MinAvgTwoSlice  (0) 2019.08.28
Codlility 15번 Distinct  (0) 2019.08.26
Codility 10번 PassingCars  (0) 2019.08.17
Codility 12번 MaxProductOfThree  (0) 2019.08.17
Comments