티스토리 뷰

문제




코드

import java.util.Scanner;

public class Main {

	public static void main(String[] args) throws Exception {
		Scanner scanner = new Scanner(System.in);
		int t = scanner.nextInt();
		for (int test_case = 0; test_case < t; test_case++) {
			int n = scanner.nextInt();
			int[] a = new int[n];

			for (int i = 0; i < n; i++) {
				a[i] = scanner.nextInt();
			}

			long sum = 0L;

			for (int i = 0; i < n - 1; i++) {
				for (int j = i + 1; j < n; j++) {
					sum += operation(a[i], a[j]);
				}
			}

			System.out.println(sum);
		}
	}

	public static int operation(int a, int b) {
		// 최대공약수(GCD) : 두 수 A B의 최대공약수는 A와 B의 공통된 약 중에서 가장 큰 정수이다.
		// 최소공배수(LCM) : 두 수 A B의 최소공배수는 A와 B의 공통된 배수 중에서 가장 작은 정수이다.

		int GCD = 0;
		int A = a;
		int B = b;

		// 재귀함수를 사용하지 않은 유클리드 호제법(최대공약수)
		while (B != 0) {
			int R = A % B;
			A = B;
			B = R;
			GCD = A;
		}

		return GCD;
	}

}

출처


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



'알고리즘 > 백준알고리즘(JAVA)' 카테고리의 다른 글

#1934번 : 최소공배수  (0) 2018.11.04
#2609번 : 최대공약수와 최소공배수  (0) 2018.11.04
#10430번 : 나머지  (0) 2018.11.04
#1260번 : DFS와 BFS  (0) 2018.09.27
#2743번 : 단어 길이 재기  (0) 2018.09.26
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
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 29 30 31
글 보관함