끄적끄적
Codility Lesson5 - CountDiv 본문
Codility Lesson5 - CountDiv
https://app.codility.com/demo/results/training7V2QZV-P8M/
문제
Write a function:
def solution(A, B, 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.
정답
def solution(A,B,K):
result=0
for i in range(A,B+1):
if i%K==0:
result+=1
return result
결과


A와 B의 차이가 크고, 그 사이에 K로 나눠지는 수가 많아지면 시간이 너무 오래 걸림
정답
def solution(A,B,K):
result=0
A_K = int((A)/ K)
B_K= int(B/K)
if A % K ==0:
result = B_K - A_K +1
else:
result = B_K - A_K
return result
결과


'Codility Lessons' 카테고리의 다른 글
| Codility Lesson5 - GenomicRangeQuery (0) | 2023.09.20 |
|---|---|
| Codility Lesson5 - PassingCars (0) | 2023.09.20 |
| Codility Lesson4 - MissingInteger (0) | 2023.09.19 |
| Codility Lesson4 - MaxCounters (0) | 2023.09.18 |
| Codility Lesson4 - PermCheck (0) | 2023.09.18 |