CountDiv

Compute number of integers divisible by k in range [a..b]

Solution in C/C++ (easy to convert into other languages...)

#include <math.h>

int solution(int A, int B, int K) {
   auto A_mod = A % K;
   
   if (A_mod)
      A += (K - A_mod);

   B -= B % K;

   return A > B ? 0 : ( B - A ) / K + 1;
}

Comments