CountDiv
Task
This is a division task. This is classified as ‘Respectable’, but is simple.
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 }
Solution
You can’t simply calculate (A-B)/K because the remainders at both ends may sum to > K. Instead use the built-in ceil and floor functions.
#include <math.h>
int solution(int A, int B, int K) {
// write your code in C++14 (g++ 6.2.0)
// number whole repeats
int ACeil = ceil(static_cast<double>(A) / K) * K;
int BFloor = floor(static_cast<double>(B) / K) * K;
int res = ((BFloor – ACeil) / K)+1;
return res;
}
Test Function
This code tests the solution
int main() {
assert(solution(6, 11, 2) == 3);
assert(solution(6, 11, 1) == 6);
assert(solution(6, 11, 3) == 2);
assert(solution(6, 11, 4) == 1);
assert(solution(6, 11, 5) == 1);
assert(solution(6, 11, 6) == 1);
assert(solution(6, 11, 6) == 1);
assert(solution(6, 11, 7) == 1);
assert(solution(6, 11, 8) == 1);
assert(solution(6, 11, 9) == 1);
assert(solution(6, 11, 10) == 1);
assert(solution(6, 11, 11) == 1);
assert(solution(6, 11, 12) == 0);
assert(solution(0, 11, 1) == 12);
assert(solution(0, 11, 2) == 6);
assert(solution(0, 100, 3) == 34);
return 0;
}
Results
Correctness | 100% |
Performance | 100% |