题目链接:
http://codeforces.com/problemset/problem/1025/B
题目:
During the research on properties of the greatest common divisor (GCD) of a set of numbers, Ildar, a famous mathematician, introduced a brand new concept of the weakened common divisor (WCD) of a list of pairs of integers.
For a given list of pairs of integers (a1,b1)(a1,b1), (a2,b2)(a2,b2), ..., (an,bn)(an,bn) their WCD is arbitrary integer greater than 11, such that it divides at least one element in each pair. WCD may not exist for some lists.
For example, if the list looks like [(12,15),(25,18),(10,24)][(12,15),(25,18),(10,24)], then their WCD can be equal to 22, 33, 55 or 66 (each of these numbers is strictly greater than 11 and divides at least one number in each pair).
You're currently pursuing your PhD degree under Ildar's mentorship, and that's why this problem was delegated to you. Your task is to calculate WCD efficiently.
Input
The first line contains a single integer nn (1≤n≤1500001≤n≤150000) — the number of pairs.
Each of the next nn lines contains two integer values aiai, bibi (2≤ai,bi≤2⋅1092≤ai,bi≤2⋅109).
Output
Print a single integer — the WCD of the set of pairs.
If there are multiple possible answers, output any; if there is no answer, print −1−1.
Examples
Input
3
17 18
15 24
12 15
Output
6
Input
2
10 16
7 17
Output
-1
Input
5
90 108
45 105
75 40
165 175
33 30
Output
5
Note
In the first example the answer is 66 since it divides 1818 from the first pair, 2424from the second and 1212 from the third ones. Note that other valid answers will also be accepted.
In the second example there are no integers greater than 11 satisfying the conditions.
In the third example one of the possible answers is 55. Note that, for example, 1515 is also allowed, but it's not necessary to maximize the output.
题目大意:
给你一些数对,每个数对由(a[i],b[i])组成,定义WCD为 能整除所有数对中每组至少一个数 的数,求WCD。
分析:
分别对每一组数对求他们的lcm(最小公倍数),然后再对这些所有的lcm求得他们的GCD(最大公约数)。我们知道,每一个数都可以分解成素因子的乘积(唯一分解定理),那么,每个数对的lcm分解成的素因子,就包含了这两个数的所有素因子。那么,这些所有的lcm的GCD就是这些所有的lcm的公共的素因子的乘积。
那么,这个GCD跟我们要求的WCD有什么关系呢?显然,WCD是GCD的因子,那么GCD比WCD中多出的素因子是哪儿来的呢?在求lcm的过程中,两个数的素因子被合并在了一起,但是WCD中最多只能出现两个数的公共素因子。那么我们只需要消除这些影响就可以找到一组WCD的值了。
怎么消除呢?可以依次和每个a[i]和b[i]与GCD求gcd,如果gcd不等于1的话,就说明这个数和GCD有公共因子,然后我们就可以只保留这个公共因子,把其他的舍去,这样这个问题就解决了。
代码:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAXN=150000+100;
ll a[MAXN],b[MAXN];
int main()
{
int n;
scanf("%d",&n);
for(int i=0;i<n;i++)
scanf("%lld %lld",&a[i],&b[i]);
ll gcd=a[0]*b[0]/__gcd(a[0],b[0]);
for(int i=1;i<n;i++)
gcd=__gcd(gcd,a[i]*b[i]/__gcd(a[i],b[i]));
if(gcd==1)
{
printf("-1\n");
return 0;
}
ll temp;
for(int i=0;i<n;i++)
{
temp=__gcd(gcd,a[i]);
if(temp>1)
gcd=temp;
temp=__gcd(gcd,b[i]);
if(temp>1)
gcd=temp;
}
printf("%lld\n",gcd);
return 0;
}