๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
โŒจ๏ธ Language/swift

[Swift] Codility Lesson 5 - CountDiv

by hyebin (Helia) 2022. 7. 26.
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

Write a function:

public func solution(_ A : Int, _ B : Int, _ K : Int) -> Int

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.

 

๋ฌธ์ œ ๋งํฌ
 

CountDiv coding task - Learn to Code - Codility

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

app.codility.com

GitHub
 

GitHub - yoohyebin/swift

Contribute to yoohyebin/swift development by creating an account on GitHub.

github.com

 

๋ฌธ์ œ ๋ถ„์„

  •  ์ •์ˆ˜ A, B, K๊ฐ€ ์ž…๋ ฅ์œผ๋กœ ์ฃผ์–ด์ง„๋‹ค.
  • A๋ถ€ํ„ฐ B๊นŒ์ง€ ์‚ฌ์ด์˜ ์ •์ˆ˜๋“ค ์ค‘ K๋กœ ๋‚˜๋ˆ„์–ด ๋–จ์–ด์ง€๋Š” ์ •์ˆ˜์˜ ๊ฐœ์ˆ˜๋ฅผ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ์ด๋‹ค.
ex) A = 6, B = 11, K = 2

[6...11] = 6, 7, 8, 9, 10, 11
์ด ์ •์ˆ˜๋“ค ์ค‘ 2(K)๋กœ ๋‚˜๋ˆ„์–ด ๋–จ์–ด์ง€๋Š” ์ˆ˜๋Š”  6, 8, 10์ด๋‹ค.
๋”ฐ๋ผ์„œ ์ •๋‹ต์€ 3์ด๋‹ค. 

ํ•ด๊ฒฐ๋ฐฉ์•ˆ

  1. B๋ฅผ K๋กœ ๋‚˜๋ˆˆ ๋ชซ์—์„œ A๋ฅผ K๋กœ ๋‚˜๋ˆˆ ๋ชซ์„ ๋นผ๊ธฐ
    • 0๋ถ€ํ„ฐ N๊นŒ์ง€ ๋ฒ”์œ„ ์ค‘ K๋กœ ๋‚˜๋ˆ„์–ด ๋–จ์–ด์ง€๋Š” ์ •์ˆ˜์˜ ๊ฐœ์ˆ˜๋ฅผ ๊ตฌํ•  ๋•Œ N์„ K๋กœ ๋‚˜๋ˆˆ ๋ชซ์„ ๊ตฌํ•˜๋ฉด ๋œ๋‹ค.
    • A๋ถ€ํ„ฐ B๊นŒ์ง€์˜ ๋ฒ”์œ„์—์„œ K๋กœ ๋‚˜๋ˆ„์–ด ๋–จ์–ด์ง€๋Š” ์ •์ˆ˜์˜ ๊ฐœ์ˆ˜๋ฅผ ๊ตฌํ•  ๋•Œ๋Š” 0๋ถ€ํ„ฐ B๊นŒ์ง€ ์—์„œ 0๋ถ€ํ„ฐ A๊นŒ์ง€ K๋กœ ๋‚˜๋ˆ„์–ด ๋–จ์–ด์ง€๋Š” ์ •์ˆ˜์˜ ๊ฐœ์ˆ˜๋ฅผ ๊ตฌํ•˜๋ฉด ๋œ๋‹ค.
  2. A๊ฐ€ K๋กœ ๋‚˜๋ˆ„์–ด ๋–จ์–ด์ง„๋‹ค๋ฉด re ๋ณ€์ˆ˜๋ฅผ 1 ์ฆ๊ฐ€

Solution

public func solution(_ A : Int, _ B : Int, _ K : Int) -> Int {
    let re = B/K - A/K
    return A%K == 0 ? re + 1 : re
}

  • ์‹œ๊ฐ„ ๋ณต์žก๋„: O(1)
๋ฐ˜์‘ํ˜•