Monday, May 30, 2016

CountDiv (Codility)

Problem Statement: CountDiv

C++ Solution

 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
32
33
34
35
36
37
38
// you can use includes, for example:
// #include <algorithm>

// 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++11 (g++ 4.8.2)
    auto count = 0;

    auto start = A % K;
    if (start != 0)
    {
        start = (A + K) / K * K;
    }
    else
    {
        count++;
        start = A;
    }

    if (start > B) return 0;

    auto end = B % K;
    if (end != 0)
    {
        end = (B / K) * K;
    }
    else
    {
        count++;
        end = B;
    }

    count = (end - start) / K + 1;
    return count;
    
}

Learnings

  • Diff between B and A is not the right approach
For the input (11, 34, 17), the range i.e. B - A is 23 and dividing this by 17 gives 1. However, this is incorrect as the number 17 and 34 are divisible by 17 making the answer as 2.

No comments:

Post a Comment