UVA 11827 Maximum GCD

本文介绍了一个简单的算法竞赛题目——最大GCD问题,并提供了使用欧几里得算法求解的最大公约数计算方法。通过逐行读取输入并计算所有整数对之间的最大公约数来解决此问题。

V - Maximum GCD

UVA - 11827

#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<vector>
#include<set>
#include<map>
#include<queue>
#include<cmath>
using namespace std;
int gcd(int a, int b)
{
//    if(b == 0)
//        return a;
//    return gcd(b, a%b);
    return b?gcd(b,a%b):a;//最简版欧几里得定理
}
int main()
{
    int t;
    int a[110];
    char c;
    cin>>t;
    //while(getchar()!='\n');//可以吸收无用的回车符
    getchar();
    while(t--)
    {
        int cnt = 0;
        while((c = getchar())!='\n')
        {
            if(c >= '0' && c <= '9')
            {
                ungetc(c, stdin);//ungetc 把一个(或多个)字符退回到steam代表的文件流中,可以理解成一个“计数器”。
                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\n",max);

    }
    return 0;
}
//ungetc
//用 法
//int ungetc(int c, FILE *stream);
//形参:
//c: 要写入的字符;
//stream:文件流指针,必须是输入流不能是输出流
比如上面的程序你先输入数字25,scanf读到i中,加到sum中,然后你再输入,调用ch=getchar(),发现ch不是' '也不是'\n',而是一个数,比如’7‘,显然这是你要继续加到sum中的数,要用scanf读到i中,但是你已经将这个'7'用getchar读出来了,只好用ungetc再把这个'7'给退回去

很水的一道题,但是输入方式并不水,可以说学到了嘿嘿

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值