AtCoder Beginner Contest 177 E - Coprime (数学)

-
题意:给你\(n\)个数,首先判断它们是否全都__两两互质__.然后再判断它们是否全都互质.
-
题解:判断所有数互质很简单,直接枚举跑个gcd就行,关键是第一个条件我们要怎么去判断,其实我们可以对所有数进行质因数分解,然后判断它们有无共同的质因子,如果有,那么就说明一定至少有一对数它们不是互质的,这样的话复杂度也在可接受的范围内.
-
代码
int n; int a[N]; bool st[N]; bool check(int x){ for(int i=2;i<=x/i;++i){ if(x%i==0){ if(st[i]) return false; while(x%i==0) x/=i; st[i]=true; } } if(x>1){ if(st[x]) return false; st[x]=true; } return true; } int main() { //ios::sync_with_stdio(false);cin.tie(0);cout.tie(0); n=read(); bool flag=true; for(int i=1;i<=n;++i){ a[i]=read(); if(!check(a[i])) flag=false; } int gcd=a[1]; for(int i=2;i<=n;++i){ gcd=__gcd(gcd,a[i]); } if(flag) puts("pairwise coprime"); else if(gcd==1) puts("setwise coprime"); else puts("not coprime"); return 0; }
𝓐𝓬𝓱𝓲𝓮𝓿𝓮𝓶𝓮𝓷𝓽 𝓹𝓻𝓸𝓿𝓲𝓭𝓮𝓼 𝓽𝓱𝓮 𝓸𝓷𝓵𝔂 𝓻𝓮𝓪𝓵
𝓹𝓵𝓮𝓪𝓼𝓾𝓻𝓮 𝓲𝓷 𝓵𝓲𝓯𝓮

浙公网安备 33010602011771号