Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Codility test - find multiples in range

I applied for a job and was asked to do a Codility test. The test was the following:

Return the number of integers within the range [A..B] that are divisible by K.

Args:

  • A: is an integer within the range [0..2,000,000,000]
  • B: is an integer within the range [0..2,000,000,000] and A <= B
  • K: is an integer within the range [1..2,000,000,000]

Time complexity must be O(1).

I know my solution isn't O(1), I couldn't come up with a better solution than this. Can anyone enlighten me?

BTW, it's in C# so 'int' is large enough to hold 2000000000.

public int solution(int A, int B, int K) 
{
    int i=0;

    for(int x=A;x<=B;x++)
    {
        if((x % K) == 0)
            i++;
    }

    return i;
}
like image 930
user2669338 Avatar asked Dec 22 '13 20:12

user2669338


1 Answers

Here's my solution in Java, score 100%

public int solution(int A, int B, int K) {

    int count = (B/K - A/K) + (A%K == 0 ? 1 : 0);

    return count;
}
like image 101
Francesco Rigoni Avatar answered Sep 19 '22 04:09

Francesco Rigoni