kmjp's blog

競技プログラミング参加記です

Chokudai SpeedRun 002 : J - GCD β

難易度的には400ptぐらいでもいい気がしますが、一応やっていきます。
https://atcoder.jp/contests/chokudai_S002/tasks/chokudai_S002_j

問題

N個の正整数ペア(Ai,Bi)が与えられる。
各ペアから任意の1要素を選んだ時、そのN個の整数のGCDの最大値はいくつか。

解法

解の候補gはA[0]かB[0]の約数なので、それを総当たりしよう。
各iに対し、A[i]かB[i]のいずれかがgの倍数ならgは解となりうる。

int N;
ll A[202020],B[202020];

void solve() {
	int i,j,k,l,r,x,y; string s;
	
	cin>>N;
	FOR(i,N) cin>>A[i]>>B[i];
	ll g=A[0];
	
	int ma=1;
	for(x=1;x*x<=g;x++) if(g%x==0) {
		y=g/x;
		int ng1=0;
		int ng2=0;
		FOR(i,N) {
			if(A[i]%x && B[i]%x) ng1=1;
			if(A[i]%y && B[i]%y) ng2=1;
		}
		if(ng1==0) ma=max(ma,x);
		if(ng2==0) ma=max(ma,y);
	}
	g=B[0];
	for(x=1;x*x<=g;x++) if(g%x==0) {
		y=g/x;
		int ng1=0;
		int ng2=0;
		FOR(i,N) {
			if(A[i]%x && B[i]%x) ng1=1;
			if(A[i]%y && B[i]%y) ng2=1;
		}
		if(ng1==0) ma=max(ma,x);
		if(ng2==0) ma=max(ma,y);
	}
	cout<<ma<<endl;
	
}

まとめ

ちょっと雑な書き方をしてしまっている。