UVA 11827 Maximum GCD

来源:互联网 发布:linux命令进入e盘 编辑:程序博客网 时间:2024/06/06 14:04

题目链接:点击打开链接

题意:n组测试数据,每组数据任意m个数,求这些数所有的两两组合中最大的公因数。

分析:这题思路很容易想到,直接暴力就行了,主要在于输入的处理,因为没有具体给出每组多少个数,下面的代码中将会详细说明。

代码:

#include<cstdio>#include<iostream>#include<algorithm>using namespace std;int gcd(int a,int b){    if(b==0) return a;    else return gcd(b,a%b);}int main(){    int t;    cin>>t;    getchar();///吸收回车,防止gets函数读入。    while(t--){        char s[10000];        gets(s);        ///关键在于预处理        int tmp=0,num[1005],cnt=0;        for(int i=0;s[i]!='\0';i++){            if(s[i]==' ') num[cnt++]=tmp,tmp=0;            else tmp=tmp*10+s[i]-'0';        }        ///注意这里,应该是有些数据末尾存在空格。        if(tmp)        num[cnt++]=tmp;                int mx=0;        for(int i=0;i<cnt-1;i++)            for(int j=i+1;j<cnt;j++)                mx=max(mx,gcd(num[i],num[j]));        cout<<mx<<endl;    }}


#include<cstdio>#include<iostream>#include<algorithm>#include<sstream>using namespace std;int gcd(int a,int b){    if(b==0) return a;    else return gcd(b,a%b);}int main(){    int t;    cin>>t;    getchar();///吸收回车,防止gets函数读入。    while(t--){        char s[10000];        int arr[1000];        ///以c++流的方式再次读入。        string str;        getline(cin, str);        stringstream stream(str);        int cnt = 0;        while(stream>>arr[cnt])        {            cnt++;        }                int mx=0;        for(int i=0;i<cnt-1;i++)            for(int j=i+1;j<cnt;j++)                mx=max(mx,gcd(arr[i],arr[j]));        cout<<mx<<endl;    }}


#include<cstdio>#include<iostream>#include<algorithm>#include<sstream>using namespace std;int gcd(int a,int b){    if(b==0) return a;    else return gcd(b,a%b);}int main(){    int t;    ///cin>>t;    char c;    ///getchar();///吸收回车,防止gets函数读入。    scanf("%d\n",&t);    while(t--){        char s[10000];        int a[1000],cnt=0;        while((c=getchar())!='\n'){            if(c>='0' && c<='9'){                ungetc(c,stdin);//将字符c退回到输入流中                scanf("%d",&a[cnt++]);            }        }        int mx=0;        for(int i=0;i<cnt-1;i++)            for(int j=i+1;j<cnt;j++)                mx=max(mx,gcd(a[i],a[j]));        cout<<mx<<endl;    }}


原创粉丝点击