[알고리즘]/백준

백준 9613 자바 - GCD 합

broship 2021. 7. 2. 07:56

문제


 

 

문제해결


- 중첩 반복문을 사용해서 모든 쌍의 gcd를 구한 후 결과를 더하면 된다

- 결과는 long에 담아야 한다

import java.util.Scanner;

public class B9613 {

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

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        for (int i = 0; i < n; i++) {
            int m = sc.nextInt();
            int[] arr = new int[m];
            for (int j = 0; j < m; j++) {
                arr[j] = sc.nextInt();
            }

            long result = 0;
            for (int j = 0; j < m; j++) {
                for (int k = j+1; k < m; k++) {
                    result += gcd(arr[j], arr[k]);
                }
            }
            System.out.println(result);
        }
    }
}