Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the number of multiples for a number in range

Tags:

java

algorithm

I have a question regarding the CountDiv problem in Codility.

The problem given is: Write a function:

class Solution { public 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 }

My code:

class Solution {
    public int solution(int A, int B, int K) {        
         int start=0;
         if (B<A || K==0 || K>B )
            return 0;
         else if (K<A)
            start = K * ( A/K +1);
         else if (K<=B)
            start = K;

         return (B-start+1)/K+ 1;
    }
} 

I don't get why I'm wrong, specially with this test case:

extreme_ifempty 
A = 10, B = 10, K in {5,7,20}
WRONG ANSWER 
got 1 expected 0

if K =5 then with i=10 A<=i<=B and i%k =0 so why should I have 0? Problem statement.

like image 555
drevlav Avatar asked Sep 04 '14 09:09

drevlav


People also ask

How do you find the multiples of a number in a range?

Thus including 20 and 300 it has 60−4+1=57 multiples. If suppose instead of 300, you had x on the end where x is not a multiple of 5 then you just take first multiple of 5 when you start walking left on integer line from x, i.e. if x=304, you replace it by 300 again.

How do you find multiples of a number in Python?

We can use range() function in Python to store the multiples in a range. First we store the numbers till m multiples using range() function in an array, and then print the array with using (*a) which print the array without using loop. # of a number n without using loop. # (m * n)+1 incremented by n.


2 Answers

This is the O(1) solution, which passed the test

int solution(int A, int B, int K) {
    int b = B/K;
    int a = (A > 0 ? (A - 1)/K: 0);
    if(A == 0){
        b++;
    }
    return b - a;
}

Explanation: Number of integer in the range [1 .. X] that divisible by K is X/K. So, within the range [A .. B], the result is B/K - (A - 1)/K

In case A is 0, as 0 is divisible by any positive number, we need to count it in.

like image 194
Pham Trung Avatar answered Oct 13 '22 02:10

Pham Trung


Java solution with O(1) and 100% in codility, adding some test cases with solutions for those who want to try and not see others solutions:

  // Test cases
  //  [1,1,1] = 1
  // [0,99,2] = 50
  // [0, 100, 3] = 34  
  // [11,345,17] = 20
  // [10,10,5] = 1
  // [3, 6, 2] = 2
  // [6,11,2] = 3  
  // [16,29,7] = 2
  // [1,2,1] = 2    
public int solution(int A, int B, int K) {
   int offsetForLeftRange = 0;
   if ( A % K == 0) { ++offsetForLeftRange; }

   return  (B/K) - (A /K) + offsetForLeftRange;
}
like image 28
moxi Avatar answered Oct 13 '22 02:10

moxi