본문으로 바로가기

Description

세 개의 정수 A, B, K가 주어지면 A~B범위 내의 정수를 K로 나눌 수 있는 수를 반환합니다

Write a function:

class Solution { public int solution(int A, int B, int K); }

that, given three integers A, B and K, returns the number of integers within the range [A..B] that are divisible by K, i.e.:

{ i : A ≤ i ≤ B, 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.

Write an efficient algorithm for the following assumptions:

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];A ≤ B.

Solution 1. Math

public int solution(int A, int B, int K) {
    int result = B/K - A/K;
    return A%K ==0? result+1 : result;
}

반복으로 모든 경우의 수를 찾지 않고 바로 계산하여 시간복잡도 O(1)로 풀어낼 수 있습니다.

Reference

 

CountDiv coding task - Learn to Code - Codility

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

app.codility.com