Archive/Questions
[programmers/Swift] N개의 최소공배수
Marco
2022. 5. 13. 20:22
728x90
programmers.co.kr - 코딩테스트연습 - Lv.2 - 연습문제 - N개의 최소공배수
코딩테스트 연습 - N개의 최소공배수
두 수의 최소공배수(Least Common Multiple)란 입력된 두 수의 배수 중 공통이 되는 가장 작은 숫자를 의미합니다. 예를 들어 2와 7의 최소공배수는 14가 됩니다. 정의를 확장해서, n개의 수의 최소공배
programmers.co.kr
Constraints :
- arr은 길이 1이상, 15이하인 배열입니다.
- arr의 원소는 100 이하인 자연수입니다.
//
// Created by Yongwoo Marco on 2022/05/08.
// Copyright © 2022 Yongwoo Marco Kim. All rights reserved.
//
// 최대공약수
func GCD(_ min: Int, _ max: Int) -> Int {
return min % max == 0 ? max : GCD(max, min % max)
}
// 최소공배수
func LCM(_ a: Int, _ b:Int) -> Int {
return a * b / GCD(a,b)
}
func solution(_ arr:[Int]) -> Int {
return arr.reduce(1, {LCM($0, $1)})
}
print(solution([2,6,8,14])) // 168
print(solution([1,2,3])) // 6
How I tried this :
GCD와 LCM을 구하는 함수를 만들어 두었었는데 바로 써먹음..
문제에 관한 모든 저작권 : https://programmers.co.kr/
728x90