[코딜리티] codility lesson 5 Frefix Sums - CountDiv 100%

문제.

Programming language: 
Write a function:
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.
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];
  • A ≤ B.
Complexity:
  • expected worst-case time complexity is O(1);
  • expected worst-case space complexity is O(1).
Copyright 2009–2017 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

풀이.

// you can also use imports, for example:
// import java.util.*;

// you can write to stdout for debugging purposes, e.g.
// System.out.println("this is a debug message");

class Solution {
    public int solution(int A, int B, int K) {
        // write your code in Java SE 8
        
        return (B/K + ( A%K == 0 ? 1 : 0 )) - (A/K );
        
    }
}

설명.

A 와 B 사이에 K 의 배수가 몇개있는지 갯수를 세어라.

산수 문제이다.
만약, 이것을 루프나 배열로 또는 진짜 갯수를 세려 하다간 꽤나 큰 입력값 때문에 고생하게 될 것이다.


댓글

이 블로그의 인기 게시물

[코딜리티] codility lesson 5 Frefix Sums - MinAvgTwoSlice 100%

구글 블로그 ( blogspot ) 라벨 위젯 을 카테고리 처럼 만들기

[코딜리티] codility lesson 7 Stacks and Queues - StoneWall 100%