Maximum GCD 读入

来源:互联网 发布:淘宝如何设置子账号 编辑:程序博客网 时间:2024/06/07 07:06


Maximum GCD


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


题意: 给你 n 个数求GCD();

关键在于对于每个测试样例,你不知道有多少个,有个很好的读入技巧。

  ungetc(c,stdin)    :    将你读到的字符回退到输入流中;

  

完美的解决了这个问题,但是我的codeblock 上竟然运行不了,不管了,反正能A,而且代码减少了很多。


代码:

#include<iostream>#include<cstdio>#define maxn 1010using namespace std;int gcd(int a,int b){    if(b==0)        return a;    return gcd(b,a%b);}int main(){    int  n;    int a[maxn];    int cnt;    char c;    scanf("%d",&n);    while(getchar()!='\n');    while(n--)    {        cnt=0;        while((c=getchar())!='\n')        {            if(c>='0'&&c<='9')            {                ungetc(c,stdin);                scanf("%d",&a[cnt++]);            }        }            int mx=-1;        for(int i=0;i<cnt-1;i++)            for(int j=i+1;j<cnt;j++)        {            int tt=gcd(a[i],a[j]);            if(tt>mx)                mx=tt;        }        cout<<mx<<endl;    }    return 0;}