πŸ“– Problem Solution/Programmers

ν”„λ‘œκ·Έλž˜λ¨ΈμŠ€ μ΅œλŒ€κ³΅μ•½μˆ˜μ™€ μ΅œμ†Œκ³΅λ°°μˆ˜ Swift

Fomagran πŸ’» 2020. 2. 29. 19:41
728x90
λ°˜μ‘ν˜•

문제 μ„€λͺ…

두 수λ₯Ό μž…λ ₯λ°›μ•„ 두 수의 μ΅œλŒ€κ³΅μ•½μˆ˜μ™€ μ΅œμ†Œκ³΅λ°°μˆ˜λ₯Ό λ°˜ν™˜ν•˜λŠ” ν•¨μˆ˜, solution을 μ™„μ„±ν•΄ λ³΄μ„Έμš”. λ°°μ—΄μ˜ 맨 μ•žμ— μ΅œλŒ€κ³΅μ•½μˆ˜, κ·Έλ‹€μŒ μ΅œμ†Œκ³΅λ°°μˆ˜λ₯Ό λ„£μ–΄ λ°˜ν™˜ν•˜λ©΄ λ©λ‹ˆλ‹€. 예λ₯Ό λ“€μ–΄ 두 수 3, 12의 μ΅œλŒ€κ³΅μ•½μˆ˜λŠ” 3, μ΅œμ†Œκ³΅λ°°μˆ˜λŠ” 12μ΄λ―€λ‘œ solution(3, 12)λŠ” [3, 12]λ₯Ό λ°˜ν™˜ν•΄μ•Ό ν•©λ‹ˆλ‹€.

μ œν•œ 사항

  • 두 μˆ˜λŠ” 1이상 1000000μ΄ν•˜μ˜ μžμ—°μˆ˜μž…λ‹ˆλ‹€.

μž…μΆœλ ₯ 예

n m return
3 12 [3, 12]
2 5 [1, 10]

풀이:

μ΅œλŒ€κ³΅μ•½μˆ˜λ₯Ό κ΅¬ν•˜λŠ” 법

nκ³Ό m쀑 μž‘μ€ 수 κΉŒμ§€ λ°˜λ³΅ν•˜κ²Œ ν•˜κ³  λ§Œμ•½ nκ³Ό m λ‘˜ λ‹€ λ‚˜λˆ΄μ„ λ•Œ 0이 λ˜λŠ” μˆ˜κ°€ 있으면 maxλΌλŠ” λ³€μˆ˜λ₯Ό λ°”κΏ”μ€€λ‹€.

μ΅œμ†Œκ³΅λ°°μˆ˜λ₯Ό κ΅¬ν•˜λŠ” 법

nκ³Όm쀑 μž‘μ€ 수둜 n의 배수λ₯Ό λ‚˜λˆ΄μ„ λ•Œ λ‚˜λ¨Έμ§€κ°€ 0이면 λ°˜λ³΅μ„ μ€‘λ‹¨ν•˜κ³  minλ³€μˆ˜μ— n의 배수λ₯Ό λ„£μ–΄μ€€λ‹€. μ•„λ‹ˆλ©΄ μ°¨λ‘€λ‘œ 1μ”© 더해쀀닀. 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
func solution(_ n:Int, _ m:Int-> [Int] {
    var max = Int()
    var min = Int()
    var x = 1
    if n > m {
        for i in 1...m{
            if n%i == 0 && m%i == 0{
                max = i
            }
        }
        while n*x%m != 0{
            x += 1
        }
        min = n*x
        return [max,min]
    } else {
        for i in 1...n{
             if n%i == 0 && m%i == 0{
                           max = i
                       }
        }
        while m*x%n != 0{
            x += 1
        }
        min = m*x
        return [max,min]
    }
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter

λ‹€λ₯Έ μ‚¬λžŒ 풀이 쀑 μ’‹λ‹€κ³  μƒκ°ν•˜λŠ” 것

풀이: μ΅œλŒ€κ³΅μ•½μˆ˜μ™€ μ΅œμ†Œκ³΅λ°°μˆ˜λ₯Ό κ΅¬ν•˜λŠ” ν•¨μˆ˜λ₯Ό 각 각 λ§Œλ“€μ—ˆλ‹€.

μš°μ„  μ΅œλŒ€κ³΅μ•½μˆ˜λ₯Ό κ΅¬ν•˜λŠ” ν•¨μˆ˜ aλ₯Ό b둜 λ‚˜λˆ΄μ„ λ•Œ 0이라면 a,b쀑 μž‘μ€ 수λ₯Ό λ°˜ν™˜ μ•„λ‹ˆλΌλ©΄ b와 aλ₯Ό b둜 λ‚˜λˆˆ 값을 λ°˜μ˜¬λ¦Όν•œ 값을 λ‹€μ‹œ λ°˜λ³΅ν•΄λΌ.

μ΅œμ†Œκ³΅λ°°μˆ˜λ₯Ό κ΅¬ν•˜λŠ” 법을 μ΅œλŒ€κ³΅μ•½μˆ˜λ‘œ a,bλ₯Ό κ³±ν•œ 값을 λ‚˜λˆˆ 것.

1
2
3
4
5
6
7
8
9
10
11
12
13
func gcd(_ a: Int, _ b: Int-> Int {
    let mod: Int = a % b
    return 0 == mod ? min(a, b) : gcd(b, mod)
}
 
func lcm(_ a: Int, _ b: Int-> Int {
    return a * b / gcd(a, b)
}
 
func solution(_ n:Int, _ m:Int-> [Int] {
    return [gcd(n, m), lcm(n, m)]
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
728x90
λ°˜μ‘ν˜•