CodeWars 코딩 문제 2021/01/16 - Count the divisible numbers

이호현·2021년 1월 16일
0

Algorithm

목록 보기
54/138

[문제]

Complete the function that takes 3 numbers x, y and k (where x ≤ y), and returns the number of integers within the range [x..y] (both ends included) that are divisible by k.

More scientifically: { i : x ≤ i ≤ y, i mod k = 0 }

Example
Given x = 6, y = 11, k = 2 the function should return 3, because there are three numbers divisible by 2 between 6 and 11: 6, 8, 10

  • Note: The test cases are very large. You will need a O(log n) solution or better to pass. (A constant time solution is possible.)

[풀이]

function divisibleCount(x, y, k) {
  while(x % k) {
    x++;
  }

  return parseInt(((y - x) / k) + 1);
}

x가 k로 나눠질 때까지 증가시킴.
그리고 y에서 x를 뺀 수를 k로 나눈 몫에 1을 더한 값을 return하면 됨.

profile
평생 개발자로 살고싶습니다

0개의 댓글