邝斌带你飞之数论专题--Maximum GCD UVA

Given the N integers, you have to find the maximum GCD (greatest common divisor) of every possible
pair of these integers.
Input
The 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) positive
integers that you have to find the maximum of GCD.
Output
For each test case show the maximum GCD of every possible pair.
Sample Input

3
10 20 30 40
7 5 12
125 15 25

Sample Output
20
1
25

数据不大,直接暴力,这里学习的是这种输入方法


#include<map>
#include<queue>
#include<stack>
#include<vector>
#include<math.h>
#include<cstdio>
#include<sstream>
#include<numeric>//STL数值算法头文件
#include<stdlib.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#include<functional>//模板类头文件
using namespace std;

const int INF=1e9+7;
const int maxn=1010;
typedef long long ll;

int t;
string str;
int a[maxn];

int gcd(int a,int b)
{
    return b?gcd(b,a%b):a;
}

int main()
{
    scanf("%d
",&t);
    while(t--)
    {
        int i,j,maxx=0;
        getline(cin,str);
        stringstream ss(str);
        int n=0;
        while(ss>>a[n])
            n++;
        for(i=0; i<n-1; i++)
            for(j=i+1; j<n; j++)
                maxx=max(maxx,gcd(a[i],a[j]));
        printf("%d
",maxx);
    }
    return 0;
}


//方法二
int gcd(int a,int b)
{
    return b?gcd(b,a%b):a;
}
int main()
{
    int T;
    int a[105];
    char c;
    scanf("%d",&T);
    while (getchar() != '
');
    while(T--)
    {
        int cnt=0;
        while((c=getchar())!='
')
        {
            if(c>='0' && c<='9')
            {
                ungetc(c,stdin);//将字符c退回到输入流中
                scanf("%d",&a[cnt++]);
            }
        }
        int max=0;
        for(int i=0; i<cnt-1; i++)
        {
            for(int j=i+1; j<cnt; j++)
            {
                int t=gcd(a[i],a[j]);
                if(t>max) max=t;
            }
        }
        printf("%d
",max);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/nyist-xsk/p/7264850.html