B. Weakened Common Divisor
time limit per test
1.5 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
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
Copy
3
17 18
15 24
12 15
output
Copy
6
input
Copy
2
10 16
7 17
output
Copy
-1
input
Copy
5
90 108
45 105
75 40
165 175
33 30
output
Copy
5
Note
In the first example the answer is 66 since it divides 1818 from the first pair, 2424 from 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.
题目链接:http://codeforces.com/contest/1025/problem/B
题意是给了n组数,从每组数里挑一个数出来,求他们的因子,如果没有因子(也就是因子为1)的话就输出-1,如果有多个因子,输出一个就行。
一共有两种解法,一是我们先输入第一组的a和b,然后输入2-n组的x和y,分别更新a = gcd(a, x * y), b = gcd(b, x * y);当a和b都等于1的时候说明没有符合题意的因子,输出-1,否则输出a或b中不等于1的数的一个因子即可。第二种方法是我们分别求出a和b的质因子,然后暴力去枚举每一组数据。第二种方法要比第一种实现跑的快一点。看代码可能会更好理解一点。
#include<bits/stdc++.h>
using namespace std;
long long divsor(long long n)
{
for(int i=2; i*i<=n; i++)
if(n%i==0) return i;
return n;
}
int main()
{
long long n,a,b,c,d;
cin>>n>>a>>b;
while(--n)
{
cin>>c>>d;
a=__gcd(c*d,a),b=__gcd(c*d,b);
}
if (a!=1)cout<<divsor(a)<<endl;
else if (b!=1) cout<<divsor(b)<<endl;
else cout<<-1<<endl;
return 0;
}