SGU 499. Greatest Greatest Common Divisor - Gemini Boy - ACM之路~

SGU 499. Greatest Greatest Common Divisor

Gemini posted @ 2013年9月16日 15:11 in 题解 with tags sgu , 932 阅读

链接:http://acm.sgu.ru/problem.php?contest=0&problem=499

给出n(1<=n<=100000)个数,每个数的范围是1<=a[i]<=1000000,现在求n个数任意俩个数的gcd最大是多少。

做法是枚举答案,然后用类似于素数筛法的方法判定是否存在。复杂度O(n*logn)。

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

const int maxn = 1000010;

int n, maxx, a[100100], pos[maxn];

void init() {
	scanf("%d", &n);
	for (int i = 1; i <= n; i++) {
		scanf("%d", &a[i]);
		pos[a[i]] = i;
		maxx = max(a[i], maxx);
	}
	maxx += 2;
}

bool check(int x) {
	int res = 0;
	for (int i = x; i < maxx; i += x) {
		if (res > 1) break;
		if (pos[i]) res++;
	}
	if (res > 1)
		return true;
	else
		return false;
}

void work() {
	for (int i = maxx - 2; i >= 1; i--) {
		if (check(i) == true) {
			printf("%d\n", i);
			return ;
		}
	}
}

int main() {
	init();
	work();
}

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter
Host by is-Programmer.com | Power by Chito 1.3.3 beta | © 2007 LinuxGem | Design by Matthew "Agent Spork" McGee