[Codility] Lesson5 - Prefix Sums : Count Div
Problem
Write a function:
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.
How to solve
- 정보
입력: A, B, K 정수
{ i : A ≤ i ≤ B, i mod K = 0 }
- 구해야 하는것?
A~B 사이 K 로 나눠지는 정수의 갯수 retrun
- 예시
A = 6, B=11, K=2 일 때,
6, 7, 8, 9, 10, 11 중 K=2 로 나누어지는 수는 6, 8, 10 3개!
- 풀이
(0, B) 의 K 로 나눠지는 수는 B/K+1
A==0 일 때,
(0, B) 의 K 로 나눠지는 수
A !=0 일 때,
B 까지의 K로 나눠지는 수의 합과 A-1까지의 K로 나눠지는 수의 차를 구하면 된다.
Solution(c++)
// you can use includes, for example:
#include <bits/stdc++.h>
// you can write to stdout for debugging purposes, e.g.
// cout << "this is a debug message" << endl;
int solution(int A, int B, int K) {
// write your code in C++14 (g++ 6.2.0)
if(A==0){
return B/K+1;
}else{
return (B/K + 1) - ((A-1)/K+1);
}
}
Test Result
app.codility.com/demo/results/trainingFQJQZ7-FCV/
Test results - Codility
Write a function: 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,
app.codility.com