728x90
https://www.acmicpc.net/problem/9613
9613번: GCD 합
첫째 줄에 테스트 케이스의 개수 t (1 ≤ t ≤ 100)이 주어진다. 각 테스트 케이스는 한 줄로 이루어져 있다. 각 테스트 케이스는 수의 개수 n (1 < n ≤ 100)가 주어지고, 다음에는 n개의 수가 주어진
www.acmicpc.net
// 코드
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
37
38
39
40
41
42
43
44
45
46
47
48
49
|
import java.util.*;
import java.io.*;
public class Main{
public static int GCD(int A, int B) {
while(true) {
int r = A % B;
if(r == 0) {
return B;
}
A = B;
B = r;
}
}
public static void main(String[] args) throws Exception {
// Please Enter Your Code Here
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int T = Integer.parseInt(st.nextToken());
int[] myArr = null;
for(int i=0; i<T; i++) {
st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
if(n > 1) {
myArr = new int[n];
for(int j=0; j<n; j++) {
myArr[j] = Integer.parseInt(st.nextToken());
}
long gcdSum = 0;
for(int j=0; j<(n-1); j++) {
for(int k=j+1; k<n; k++) {
int A = Math.max(myArr[j], myArr[k]);
int B = Math.min(myArr[j], myArr[k]);
gcdSum += GCD(A, B);
}
}
System.out.println(gcdSum);
} else {
System.out.println(1);
}
}
}
}
|
cs |
반응형