Potato
์•ˆ๋…•ํ•˜์„ธ์š”, ๊ฐ์žก๋‹ˆ๋‹ค?๐Ÿฅ” ^___^ ๐Ÿ˜บ github ๋ฐ”๋กœ๊ฐ€๊ธฐ ๐Ÿ‘‰๐Ÿป

Algorithm/Baekjoon

[๋ฐฑ์ค€] (Swift) 9613๋ฒˆ - GCDํ•ฉ

๊ฐ์ž ๐Ÿฅ” 2022. 2. 20. 12:40
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ ๋งํฌ

https://www.acmicpc.net/problem/9613

 

9613๋ฒˆ: GCD ํ•ฉ

์ฒซ์งธ ์ค„์— ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค์˜ ๊ฐœ์ˆ˜ t (1 ≤ t ≤ 100)์ด ์ฃผ์–ด์ง„๋‹ค. ๊ฐ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค๋Š” ํ•œ ์ค„๋กœ ์ด๋ฃจ์–ด์ ธ ์žˆ๋‹ค. ๊ฐ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค๋Š” ์ˆ˜์˜ ๊ฐœ์ˆ˜ n (1 < n ≤ 100)๊ฐ€ ์ฃผ์–ด์ง€๊ณ , ๋‹ค์Œ์—๋Š” n๊ฐœ์˜ ์ˆ˜๊ฐ€ ์ฃผ์–ด์ง„

www.acmicpc.net

 

๋‚ด๊ฐ€ ํ‘ผ ํ’€์ด

  • ์žฌ๊ท€ GCD ํ•จ์ˆ˜ ์ƒ์„ฑ (๊ธฐ์–ตํ•˜์ž!) -> ์ตœ๋Œ€๊ณต์•ฝ์ˆ˜๊ตฌํ•  ๋•Œ ์‚ฌ์šฉ (์œ ํด๋ฆฌ๋“œ ํ˜ธ์ œ๋ฒ•)
  • input์— ๋‹ด๊ฒจ์žˆ๋Š” ์ˆ˜๋“ค์˜ GCD๋ฅผ ๊ตฌํ•ด์ฃผ๊ณ  ๋”ํ•ด์„œ ์ถœ๋ ฅํ•ด์คŒ
let n = Int(readLine()!)!

func gcd(_ m: Int, _ n: Int) -> Int {
    if n == 0 {
        return m
    } else {
        return gcd(n, m%n)
    }
}


for _ in 0..<n {
    let input = readLine()!.split(separator: " ").map { Int(String($0))! }
    var result: [Int] = []
    for i in 1..<input.count - 1 {
        for j in i+1..<input.count {
            result.append(gcd(input[i], input[j]))
        }
    }
    print(result.reduce(0, +))
}

 

๋ฐ˜์‘ํ˜•