[Programmers] N개의 최소공배수 - 연습문제

동민·2021년 3월 11일
// N개의 최소공배수 - 연습문제
public class N_LCM {

	// 문제에서 입력되는 배열은 이미 정렬이 되어있는 상태이다
	public int solution(int[] arr) {

		int i = 0, count = 0;
		
		while (count != arr.length) {
			count = 0;
			i += arr[arr.length - 1]; // i를 1씩 증가시키면 비효율적이다. 어차피 최소공배수는 배열에서 가장 큰 수로도 나누어 져야함. 따라서 i를 배열의 가장 큰 수씩 증가시킨다.
			for (int j = 0; j < arr.length; j++) {
				if (i % arr[j] == 0) {
					count++;
				}
			}
		}
		return i;
	}

	public static void main(String[] args) {

		N_LCM s = new N_LCM();

		int[] arr1 = { 2, 6, 8, 14 };
		int[] arr2 = { 1, 2, 3 };

		System.out.println(s.solution(arr1));
		System.out.println(s.solution(arr2));

	}

}
profile
BE Developer

0개의 댓글