Respectable
CountDiv
Calculates the number of integers divisible by k in the range [a..b].
Write a function:
class solution {public int solution(int A, int B, int K); }
That is, given the three integers A, B, and K, it returns the number of integers in the range [A..B] divisible by K.
{i:A≤i≤B、i mod K = 0}
For example, if A = 6, B = 11, K = 2, then the function must return 3 because there are 3 numbers divisible by 2 in the range [6..11]: 6, 8 and 10. There is.
Write a ** efficient ** algorithm for the following assumptions:
This is a mathematical problem. Once you understand the essence, you won't call it "Respectable".
This is a math problem, a math problem, a respectable degree of incompatibility.
Program CountDivSolution.java
CountDivSolution.java
public int solution(int A, int B, int K) {
return (int)(Math.floor(B / (double)K)) - (int)(Math.ceil(A / (double)K)) + 1;
}
Detected time complexity:
O(1)
jUnit CountDivSolutionTest.java
Report Candidate Report: trainingMUJ282-CCG
Recommended Posts