CountDiv

Compute number of integers divisible by k in range [ab]
ℹ️ © Codility, 2009-2018

Problem

Write a function that, given three integers a, b and k, returns the number of integers within the range [ab] that are divisible by k, i.e.: {i: aib, i mod k = 0}.

For example, for a = 6, b = 11 and k = 2, your function should return 3, because there are three numbers divisible by 2 within the range [6 … 11], namely 6, 8 and 10.

Assume that:
a and b are integers within the range [0 … 2,000,000,000];
k is an integer within the range [1 … 2,000,000,000];
ab.

Complexity:
• expected worst-case time complexity is O(1);
• expected worst-case space complexity is O(1).

Solution

C#

class Solution {
  public int solution(int a, int b, int k) {
    return (b / k) - (a > 0 ? (a - 1) / k : -1);
  }
}

Java

class Solution {
  public int solution(int a, int b, int k) {
    return (b / k) - (a > 0 ? (a - 1) / k : -1);
  }
}

JavaScript

function solution(a, b, k) {
  return (
    Math.floor(b / k) - (a > 0 ? Math.floor((a - 1) / k) : -1)
  );
}

PHP

function solution($a, $b, $k) {
  return (int)(
    floor($b / $k) - ($a > 0 ? floor(($a - 1) / $k) : -1)
  );
}