HDU 4497 GCD and LCM 组合数学

题目链接:https://vjudge.net/problem/HDU-4497

题目思路:首先看题目,用测试数据想到了可以把最大公因数和最小公倍数分解质因数,然后对于每个质因数,例如2,最大公因数有2^1,最小公倍数有2^3,那么x,y,z分解质因数中要有一个x或y或z有2^1,有一个有2^3,还有一个随便取一个1~3之间的数,然后A(3,3),然后慢慢对所有质因数进行操作

AC代码

#include <iostream>
#include<bits/stdc++.h>
using namespace std;
template <typename T>
inline bool scan_d (T &ret) {
    char c;
    int sgn;
    if (c = getchar(), c == EOF) return 0; //EOF
    while (c != '-' && (c < '0' || c > '9') ) {
        if((c = getchar()) == EOF) return 0;
    }
    sgn = (c == '-') ? -1 : 1;
    ret = (c == '-') ? 0 : (c - '0');
    while (c = getchar(), c >= '0' && c <= '9') ret = ret * 10 + (c - '0');
    ret *= sgn;
    return 1;
}
template<typename T>
void print(T x) {
    static char s[33], *s1; s1 = s;
    if (!x) *s1++ = '0';
    if (x < 0) putchar('-'), x = -x;
    while(x) *s1++ = (x % 10 + '0'), x /= 10;
    while(s1-- != s) putchar(*s1);
}
template<typename T>
void println(T x) {
    print(x); putchar('\n');
}

set<int>ans;

int main()
{
    int g,l;
    int t;
    scan_d(t);
    while(t--)
    {
        ans.clear();
        map<int,int>cnt1;
        map<int,int>cnt2;
        scan_d(g);
        scan_d(l);
        for(int i=2;i*i<=g;++i)
        {
            while(g%i==0)
            {
                cnt1[i]++;
                g/=i;
            }
        }
        if(g>1)
            cnt1[g]++;
        for(int i=2;i*i<=l;++i)
        {
            while(l%i==0)
            {
                cnt2[i]++;
                l/=i;
            }
        }
        if(l>1)
            cnt2[l]++;
        for(auto pi:cnt1)
            ans.insert(pi.first);
        for(auto pi:cnt2)
            ans.insert(pi.first);
        long long result=1;
        for(auto pi:ans)
        {
            if(cnt2[pi]==cnt1[pi])
                continue;
            if(cnt2[pi]<cnt1[pi])
            {
                result=0;
                break;
            }
            if(cnt2[pi]>cnt1[pi])
                result*=(cnt2[pi]-cnt1[pi])*6;//化简前是(cnt2[pi]-cnt1[pi]-1)*6三个数全不同然后全排列+3(最后一个数与最小公因数的次数相同A(3,3)/2!)+3(最后一个数与最大公因数次数相同A(3,3)/2!)
        }
        println(result);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_36921652/article/details/82810873
今日推荐