P4549 【模板】裴蜀定理

题目链接

思路

模板题,裴蜀定理

裴蜀定理

(d=gcd(a ,b)),则存在整数 (x,y) 使得 (ax+by = d.),所以 (gcd(a,b)|d)

这道题我们可以看做成裴蜀定理的一个拓展,
当只有两个数 (a,b) 时,(d) 的最小值就是 (gcd(A_1,A_2)),多个数时以此类推,
(d = gcd(A_1,A_2,A_3,A_4,…,A_n)) 是最小值,此时要注意如果 (A_i) 是负数,我们需要将它转成正数

代码

#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
int n ,a ,ans = 1;
int gcd (int r1 ,int r2) {
	while (r2) {
		r1 %= r2;
		swap (r1 ,r2);
	}
	return r1;
}
int main () {
	scanf ("%d",&n);
	scanf ("%d",&ans);
	ans = abs (ans);
	for (int q = 1;q < n;++ q) {
		scanf ("%d",&a);
		a = abs (a);
		ans = gcd (ans ,a);
	}
	printf ("%d
",ans);
	return 0;
}

cb
原文地址:https://www.cnblogs.com/tuscjaf/p/13834013.html