ALGORITHM/PROGRAMMERS

[프로그래머스] N개의 최소공배수

0298 2021. 7. 26. 09:32

https://programmers.co.kr/learn/courses/30/lessons/12953

 

코딩테스트 연습 - N개의 최소공배수

두 수의 최소공배수(Least Common Multiple)란 입력된 두 수의 배수 중 공통이 되는 가장 작은 숫자를 의미합니다. 예를 들어 2와 7의 최소공배수는 14가 됩니다. 정의를 확장해서, n개의 수의 최소공배

programmers.co.kr

2021-07-26


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
    public static int solution(int[] arr) {
        int answer = arr[0];
        for(int i = 1; i < arr.length; i++) {
            int g = gcd(answer, arr[i]);
            answer = (answer / g) * (arr[i]/g) * g;
        }
 
        return answer;
    }
 
    static int gcd(int min, int max) {
        while(min != 0) {
            int tmp = max % min;
            max = min;
            min = tmp;
        }
        return max;
    }
}
cs

 

#문제풀이

배열을 두 개씩 묶는다. 그 두 개의 최소공배수를 구한 후, 그 값으로 그 다음 배열값과의 최소 공배수를 구한다. 

 

반복해서 끝까지 구하면 배열 전체의 최소공배수를 얻을 수 있다.