728x90
반응형
9613번: GCD 합
첫째 줄에 테스트 케이스의 개수 t (1 ≤ t ≤ 100)이 주어진다. 각 테스트 케이스는 한 줄로 이루어져 있다. 각 테스트 케이스는 수의 개수 n (1 < n ≤ 100)가 주어지고, 다음에는 n개의 수가 주어진
www.acmicpc.net
풀이
숫자 하나는 1,000,000을 넘지 않으니 int형으로 선언해도 된다.
하지만 GCD의 합은 int형의 범위를 넘어설 수 있으니 long형으로 선언해야 한다!!!
자료형에 제발 주의할 것
public class BOJ_9613 {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(in.readLine());
for(int i=0;i<t;i++) {
StringTokenizer st = new StringTokenizer(in.readLine()," ");
int total = Integer.parseInt(st.nextToken());
int arr[] = new int[total];
long sum = 0;
for(int x =0;x<total;x++) {
arr[x] = Integer.parseInt(st.nextToken());
}
for(int j=0;j<total-1;j++) {
for(int k=j+1;k<total;k++) {
int a = arr[j];
int b = arr[k];
if(a<b) {
int tmp = a;
a = b;
b = tmp;
}
sum += gcd(a,b);
}
}
System.out.println(sum);
}
}
static int gcd(int a, int b) {
if(a%b == 0) return b;
return gcd(b,a%b);
}
}
728x90
반응형
'알고리즘 > 백준' 카테고리의 다른 글
[문제] 백준 1476번 날짜 계산 (0) | 2021.02.16 |
---|---|
[문제] 백준 10972번 다음 순열 (0) | 2021.02.16 |
[문제] 백준 14503번 로봇 청소기 (0) | 2021.02.15 |
[문제] 백준 1967번 트리의 지름 (0) | 2021.02.15 |
[문제] 백준 2961번 도영이가 만든 맛있는 음식 (0) | 2021.02.15 |