CF1025B Weakened Common Divisor

题目描述:

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 (a_1, b_1)(a1,b1) , (a_2, b_2)(a2,b2) , ..., (a_n, b_n)(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 , 55or 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.

(洛谷有中文题面)

算法标签:gcd

题目大意:

存在n对数,要求询问是否存在一个大于1的数使得这个数能被每一对数中的至少一个数整除。若不存在输出-1,否则输出任意一个满足条件的数。

思路:

对于每一对数计算两个数的lcm,再把每一对数得到的lcm取gcd,获得的数若为1则无解输出-1。否则必有解,因为我们要保证得到的数的所有因数必须仅属于一对数的其中一个数,所以我们获得的数的最小因数,即可保证其必然仅属于每一对数的其中一个。

以下代码:

#include<bits/stdc++.h>
#define il inline
#define LL long long
#define _(d) while(d(isdigit(ch=getchar())))
using namespace std;
int n;LL g;
il int read(){
    int x,f=1;char ch;
    _(!)ch=='-'?f=-1:f;x=ch^48;
    _()x=(x<<1)+(x<<3)+(ch^48);
    return f*x;
}
il LL gcd(LL x,LL y){
    return x==0?y:gcd(y%x,x);
}
il int cal(int x){
    for(int i=2;i*i<=x;i++){
        if(x%i==0)return i;
    }
    return x;
}
int main()
{
    n=read()-1;
    int a=read(),b=read();
    g=1ll*a*b/gcd(a,b);
    while(n--){
        a=read();b=read();
        g=gcd(g,1ll*a*b/gcd(a,b));
    }
    if(g==1)puts("-1");
    else{
        int k=gcd(g,a);
        if(k>1)printf("%d\n",cal(k));
        else{
            k=gcd(g,b);
            printf("%d\n",cal(k));
        }
    }
    return 0;
}
View Code

 

posted @ 2019-02-11 16:38  Jessiejzy  阅读(220)  评论(0编辑  收藏  举报