avatar
fireworks99
keep hungry keep foolish

GCD与LCM

UVA 11827

找任意两个数的最大公因数中最大的那个

此题难在输入

题目链接

Code

#include <cstdio>
#include <sstream>
#include <iostream>
#include <algorithm>
using namespace std;
#define ll long long

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

int lcm(int a, int b)
{
    return (a / gcd(a, b) * b);
}

int main()
{
    int t, n, ans = 0, a[105], cnt = 0;
    cin >> t;
    getchar();
    while(t--)
    {
        cnt = 0, ans = 0;
        string s, tem;
        getline(cin, s);
        stringstream ss(s);
        while(ss >> tem)
            a[cnt++] = atoi(tem.c_str());
        for(int i = 0; i < cnt; ++i)
            for(int j = i + 1; j < cnt; ++j)
                if(gcd(a[i], a[j]) > ans)
                    ans = gcd(a[i], a[j]);
        cout << ans << '\n';
    }
    return 0;
}

还可用ungetc

ungetc百科

ungetc

异或写的gcd

ll GCD(ll a, ll b)
{
    while(b ^= a ^= b ^= a %= b);
    return a;
}

世界之大无奇不有……

Site by Baole Zhao | Powered by Hexo | theme PreciousJoy