coding_test/BAEKJOON

백준 9417번 C++ 풀이

CodeJin 2022. 1. 4. 01:06

https://www.acmicpc.net/problem/9417

 

9417번: 최대 GCD

첫째 줄에 테스트 케이스의 개수 N (1 < N < 100)이 주어진다. 각 테스트 케이스는 한 줄로 이루어져 있으며, 양의 정수 M (1 < M < 100)개가 주어진다. 모든 수는 -231보다 크거나 같고, 231 -1보다 작거나

www.acmicpc.net

n개의 자연수를 입력받고, 두 수의 쌍중에서, 가장 큰 최대공약수를 출력하는 문제.

 

문자열로 받은 후에, 공백을 기준으로 문자열을 분리한 후에, 브루트포스로 가장 큰 최대공약수를 찾는다.

 

#include <iostream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;

int gcd (int a, int b) {
    return !b ? a : gcd(b, a % b);
}

int main () {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    
    int t;
    int maxGcd = -1;
    int temp;
    string line;
    string num;
    vector<int> v;

    cin >> t;
    cin.ignore();
    
    while (t--) {
        v.clear();
        maxGcd = -1;
        
        getline(cin, line);
        stringstream sstream(line);
        while (getline(sstream, num, ' ')) // 문자열 분리
            v.push_back(stoi(num));
        
        for (int i = 0; i < v.size() - 1; ++i) { // 완전탐색
            for (int j = i + 1; j < v.size(); ++j) {
                temp = gcd(v[i], v[j]);
                maxGcd = maxGcd < temp ? temp : maxGcd;
            }
        }
        cout << maxGcd << '\n';
    }
}