Given the N integers, you have to find the maximum GCD (greatest common divisor) of every possiblepair of these integers.InputThe first line of input is an integer N (1 < N < 100) that determines the number of test cases.The following N lines are the N test cases. Each test case contains M (1 < M < 100) positiveintegers that you have to find the maximum of GCD.OutputFor each test case show the maximum GCD of every possible pair.Sample Input310 20 30 407 5 12125 15 25Sample Output20125
主要是为了练习 set的使用,其实可以暴力两个for求gcd。
#include<iostream> #include<cstdio> #include<algorithm> #include<cstring> #include<cmath> #include<set> #define ll long long using namespace std; const int mx = 1000; int num[mx]; char str[10000]; set<int>s; int slove(int tol){ s.clear(); int te, qr,ob,ans = 0; for(int i = 0; i < tol; i++){ te = num[i]; qr = sqrt(te); for(int k = 1; k <= qr; k++) if(te%k == 0){ // cout<<"k="<<k<<endl; ob = *s.lower_bound(k); //必须加星号 if(ob == k) ans = max(k,ans); else s.insert(k); int gg = te/k; // cout<<"gg="<<gg<<endl; ob = *s.lower_bound(gg); //必须加星号 if(ob == gg) ans = max(gg,ans); else s.insert(gg); } } return ans; } int main(){ int n,T,va,tol,len; scanf("%d",&T); getchar(); while(T--){ gets(str); va = 0,tol = 0; len = strlen(str); for(int i = 0; i < len; i++) if(str[i]>='0'&&str[i]<='9') va = va*10 + str[i]-'0'; else{ num[tol++] = va; va = 0; } if(va != 0) num[tol++] = va; int ans=0; ans = slove(tol); cout<<ans<<endl; } //cout<<gcd(6,3)<<endl; return 0; }
暴力代码
#include<iostream> #include<cstdio> #include<algorithm> #include<cstring> #include<cmath> #define ll long long using namespace std; const int mx = 1000; int num[mx]; char str[10000]; int gcd(int a, int b){ int te; while(b){ te = a; a = b; b = te%b; } return a; } int main(){ int n,T,va,tol,len; scanf("%d",&T); getchar(); while(T--){ gets(str); va = 0,tol = 0; len = strlen(str); for(int i = 0; i < len; i++) if(str[i]>='0'&&str[i]<='9') va = va*10 + str[i]-'0'; else{ num[tol++] = va; va = 0; } if(va != 0) num[tol++] = va; /* for(int i = 0; i < tol; i++){ cout<<num[i]<<","<<endl; }*/ int ans=0; for(int i = 0; i < tol; i++) for(int j = i+1; j < tol; j++) ans = max(ans,gcd(num[i],num[j])); cout<<ans<<endl; } //cout<<gcd(6,3)<<endl; return 0; }