컴퓨터 공학 기초/알고리즘 ( algorithm )
N개의 수에 대한 최대공약수 구하기
JongSeok_12
2020. 4. 22. 20:19
유클리드호제법을 이용하여 먼저 0번째와 1번째의 최대공약수를 구한뒤 구한 공약수와 다음 번째 수의 최대공약수를 구하는 방식으로 요소의 마지막 즉 N번째 까지 연산을 수행하게 되면 N개의 숫자의 공통 된 최대공약수를 구할 수 있다.
풀이
// HelloNew_C+.cpp : 콘솔 응용 프로그램에 대한 진입점을 정의합니다.
//
#include "stdafx.h"
#include<iostream>
#include<stdio.h>
#include<string>
#include<stdio.h>
#include<stdbool.h>
int gcd(int a, int b){
int tmp;
while (b > 0){
tmp = a;
a = b;
b = (tmp % a);
}
return a;
}
using namespace std;
int main(){
int n, s, nData;
int res = 0;
int *nList;
cin >> n >> s;
nList = new int[n];
for (int i = 0; i < n; ++i){
cin >> nData;
nList[i] = abs(nData - s);
}
res = nList[0];
for (int i = 1; i < n; ++i){
res = gcd(res, nList[i]);
}
cout << res << "\n";
}