문제) 백준 - 수학 - 공약수
https://www.acmicpc.net/problem/5618
5618번: 공약수
첫째 줄에 n이 주어진다. n은 2 또는 3이다. 둘째 줄에는 공약수를 구해야 하는 자연수 n개가 주어진다. 모든 자연수는 108 이하이다.
www.acmicpc.net
숫자들의 모든 공약수를 구하는 문제였습니다. 모든 숫자들에 대해 최대 공약수를 구하여 그 최대 공약수의 약수들을 출력하면 해결할 수 있습니다.
C++ 소스코드)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<bits/stdc++.h> | |
#define ll long long | |
#define INF 987654321 | |
#define MAX 4002 | |
using namespace std; | |
typedef pair<int, double> p; | |
int N; | |
int arr[MAX]; | |
int solve(int a, int b){ | |
if(a > b) swap(a, b); | |
if(b % a == 0) return a; | |
return solve(b % a, a); | |
} | |
int main() { | |
ios_base::sync_with_stdio(0); | |
cin.tie(0); cout.tie(0); | |
cin >> N; | |
for(int i = 0; i < N; ++i) | |
cin >> arr[i]; | |
int gcd = arr[0]; | |
for(int i = 1; i < N; ++i) | |
gcd = solve(gcd, arr[i]); | |
for(int i = 1; i <= gcd; i++) | |
if(gcd % i == 0) | |
cout << i << endl; | |
return 0; | |
} |
반응형
'PS(Problem Solving) > 백준_BOJ' 카테고리의 다른 글
[백준] 4096번 - 팰린드로미터 (C++) 문제 및 풀이 (0) | 2022.02.22 |
---|---|
[백준] 21922번 - 학부 연구생 민상 (C++) 문제 및 풀이 (0) | 2022.02.21 |
[백준] 3584번 - 가장 가까운 공통 조상 (C++) 문제 및 풀이 (0) | 2022.02.19 |
[백준] 6118번 - 숨바꼭질 (C++) 문제 및 풀이 (0) | 2022.02.19 |
[백준] 2302번 - 극장 좌석 (C++) 문제 및 풀이 (0) | 2022.02.18 |
댓글