Compute number of integers divisible by k in range [a..b].
- Difficulty Level: Medium
- Question URL: https://app.codility.com/programmers/lessons/5-prefix_sums/count_div/
- Time Complexity:
Solution:
Solution to Codility's Count Divisible problem which is from the Codility Lesson 5: Prefix Sums and, is solved in Java 8 with 100% performance and correctness scores. The goal here is to compute number of integers divisible by k in range [a..b]. You can find the question of this CountDiv problem in the Codility website.
package Codility.Lesson5;
import java.util.*;
public class CountDiv {
public static void main(String[] args) {
// TODO Auto-generated method stub
int result = solution(0,50,4);
System.out.println(result);
}
public static int solution(int A, int B, int K) {
// write your code in Java SE 8
int firstCount =0;
int allCount =0;
if (B==0)
return 1;
if (A>1){
firstCount = (int)(A-1)/K;
}
allCount = (int)B/K;
if (A==0)
allCount++;
return allCount-firstCount;
}
}