티스토리 뷰

문제

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.

Assume that:

  • 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.

Complexity:

  • expected worst-case time complexity is O(1);
  • expected worst-case space complexity is O(1).

문제요약


두 정수 A, B 사이 값들 중 정수 K로 나누어 떨어지는 숫자의 갯수를 구하여라.


문제풀이


예를들어 0부터 11까지 2로 나누어 떨어지는 수는 floor(11 / 2) = 5개 이다. 그럼 A부터 B까지 K로 나누어 떨어지는 수는 floor(B / K) - floor((A - 1) / K) 이다. A - 1로 한 것은 A또한 나누어 떨어지는 수에 포함되어 있기 때문이다.

import math
def solution(A, B, K):
    return math.floor(B/K) - math.floor((A-1)/K)


댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/07   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
글 보관함