티스토리 뷰
문제
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)
'알고리즘 문제풀기 > Codility' 카테고리의 다른 글
Codility - [Lesson5] PassingCars (0) | 2018.05.16 |
---|---|
Codility - [Lesson5] GenomicRangeQuery (0) | 2018.05.16 |
Codility - [Lesson4] MaxCounters (0) | 2018.04.22 |
Codility - [Lesson4] MissingInteger (0) | 2018.04.19 |
Codility - [Lesson4] FrogRiverOne (0) | 2018.04.18 |
댓글