UVa 10407 Simple division (一阶差分序列 & gcd)

10407 - Simple division

Time limit: 3.000 seconds

http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=1348


先求出原序列的一阶差分序列,然后求出所有非零元素的gcd即可。


完整代码:

/*0.022s*/

#include<cstdio>
#include<cstdlib>

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

int main()
{
	int a[1005];
	int tmp, tmp2, i, n, g;
	while (scanf("%d", &tmp), tmp)
	{
		for (i = 0; scanf("%d", &tmp2), tmp2; ++i)
			a[i] = tmp2 - tmp, tmp = tmp2;
		n = i;
		for (i = 0; a[i] == 0; ++i)
			;
		g = a[i++];
		for (; i < n; ++i)
			if (a[i]) g = gcd(a[i], g);
		printf("%d\n", abs(g));
	}
	return 0;
}

你可能感兴趣的:(C++,算法,ACM,gcd,uva)