문제 링크: https://www.acmicpc.net/problem/9613

 

9613번: GCD 합

첫째 줄에 테스트 케이스의 개수 t (1 ≤ t ≤ 100)이 주어진다. 각 테스트 케이스는 한 줄로 이루어져 있다. 각 테스트 케이스는 수의 개수 n (1 < n ≤ 100)가 주어지고, 다음에는 n개의 수가 주어진

www.acmicpc.net

 

▶ 해설


n 개의 수가 주어집니다. 각각의 숫자마다의 GCD (최소 공약수)를 구한 후 더한 것을 출력합니다.

 

import java.math.BigInteger;
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
for (int tc = 0; tc < t; tc++) {
String [] str = br.readLine().split(" ");
int n = Integer.parseInt(str[0]);
int []arr = new int[n];
for(int i=0;i<n;i++) {
arr[i] = Integer.parseInt(str[i+1]);
}
long sum=0;
for(int i=0;i<n;i++) {
for(int j=i;j<n;j++) {
if(i!=j) {
sum+=gcd(arr[i],arr[j]);
}
}
}
System.out.println(sum);
}
}
public static int gcd(int a, int b) {
if(b==0) return a;
return gcd(b,a%b);
}
}

 

'Alogorithm' 카테고리의 다른 글

백준 21275 [자바] java 폰 허석만  (0) 2022.01.26
백준 2015 [자바] java 수들의 합4  (0) 2022.01.20
백준 JAVA 2407번 조합  (0) 2021.12.30
백준 JAVA 9342번 염색체  (0) 2021.12.21
백준 JAVA 9655번 돌게임  (0) 2021.12.07