Updated:

1. 문제 링크

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

2. 사용 알고리즘

유클리드 호제법

3. 풀이

유클리드 호제법을 이용하여 최대공약수를 계산

4. 소스 코드

4-1. C++

https://github.com/dev-aiden/problem-solving/blob/main/boj/9613.cpp

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
#include <iostream>

using namespace std;

int arr[103];

int gcd(int a, int b) {
    while (b != 0) {
        int r = a % b;
        a = b;
        b = r;
    }
    return a;
}

int main(void) {
    ios_base::sync_with_stdio(false);
    int t; for (cin >> t; t--;) {
        int n; cin >> n;
        for (int i = 0; i < n; ++i) cin >> arr[i];
        long long ans = 0;
        for (int i = 0; i < n; ++i) {
            for (int j = i + 1; j < n; ++j) {
                ans += gcd(arr[i], arr[j]);
            }
        }
        cout << ans << "\n";
    }
    return 0;
}

4-2. JAVA

https://github.com/dev-aiden/problem-solving/blob/main/boj/9613.java

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
32
33
34
35
36
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Main {

    static int arr[] = new int[103];

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();
        for(int t = Integer.parseInt(br.readLine()); t-- > 0;) {
            StringTokenizer st = new StringTokenizer(br.readLine());
            int n = Integer.parseInt(st.nextToken());
            for(int i = 0; i < n; ++i) arr[i] = Integer.parseInt(st.nextToken());
            long ans = 0;
            for(int i = 0; i < n; ++i) {
                for(int j = i + 1; j < n; ++j) {
                    ans += gcd(arr[i], arr[j]);
                }
            }
            sb.append(ans).append("\n");
        }
        System.out.println(sb);
    }

    public static int gcd(int a, int b) {
        while (b != 0) {
            int r = a % b;
            a = b;
            b = r;
        }
        return a;
    }
}

Updated:

Leave a comment