티스토리 뷰
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class Main {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int count = Integer.parseInt(in.readLine());
String[] cases = new String[count];
for(int i=0; i<count; ++i) {
cases[i] = in.readLine();
}
for(int i=0; i<count; ++i) {
String[] testCaseString = cases[i].split(" ");
int numberOfCases = Integer.parseInt(testCaseString[0]);
int[] testCase = new int[numberOfCases];
for(int j=1; j<=numberOfCases; ++j) {
testCase[j-1] = Integer.parseInt(testCaseString[j]);
}
//gcd 구하기
long temp = 0;
for(int a=0; a<numberOfCases-1; ++a) {
for(int b=a+1; b<numberOfCases; ++b) {
int first = testCase[a];
int second = testCase[b];
temp += gcd(first, second);
}
}
System.out.println(temp);
}
}
static int gcd(int a, int b) {
if(b == 0)
return a;
return gcd(b, a % b);
}
}
최종 결과를 출력하는 temp 변수의 자료형을 long으로 해주어야 했다.
func gcd(a: Int, b: Int) -> Int {
if b == 0 {
return a
}
return gcd(a: b, b: a % b)
}
let count = Int(readLine()!)!
var cases = [String]()
for _ in 0..<count {
cases.append(readLine()!)
}
for i in 0..<count {
var testCase = cases[i].split(separator: " ").map { Int($0)! }
let numberOfCases = testCase.first!
testCase.remove(at: 0)
var temp = 0
for a in 0..<numberOfCases-1 {
for b in a+1..<numberOfCases {
let first = testCase[a]
let second = testCase[b]
temp += gcd(a: first, b: second)
}
}
print(temp)
}
하지만 Swift에서는 그럴 필요가 없었다...
코드 길이도 훨씬 짧고 시간도 훨씬 덜 걸리는데ㅠㅠㅠ
'Algorithm > Baekjoon Online Judge' 카테고리의 다른 글
2745번 '진법 변환' (0) | 2018.07.31 |
---|---|
11005번 '진법 변환 2' (0) | 2018.07.31 |
1934번 '최소공배수' (0) | 2018.07.31 |
2609번 '최대공약수와 최소공배수' (0) | 2018.07.31 |
1912번 '연속합' (0) | 2018.07.30 |
댓글