[JAVA] [100%] CountDiv (src & junit & author's note)

Respectable

CountDiv

Calculates the number of integers divisible by k in the range [a..b]. image.png

Task description

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:


solve

image.png

Author's note

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

[100%] CountDiv (src & junit & author's note)
[100%] MissingInteger (src & junit & author's note)
[100%] [GenomicRangeQuery] (src & junit & author's note)
[100%] MaxCounters (src & junit & author's note)
[100%] Distinct (src & junit & author's note)
[100%] CyclicRotation (src & jUnit)
[100%] PermMissingElem (src & jUnit)
[100%] FrogJmp (src & jUnit)
[100%] OddOccurrencesInArray (src & jUnit)
[100%] MinAvgTwoSlice (src & junit)
[100%] PassingCars (src & junit)
[100%] PermCheck (src & junit)
[100%] TapeEquilibrium (src & jUnit)
[100%] MaxProductOfThree (src & jUnit)
[100%] BinaryGap (src & jUnit)
Java JUnit brief note