题解:P10580 [蓝桥杯 2024 国 A] gcd 与 lcm

· · 题解

原题传送门

思路

前置知识:

快速幂

唯一分解定理

容斥原理

我们可以先将每个数除以 x,这样我们就可以得到一个最大公约数为 1,最小公倍数为 \dfrac{y}{x} 的数列。这时我们把 \dfrac{y}{x} 分解为多个质因数的乘积也就是 a_1^{k_1} \times a_2^{k_2}\dots \times a_m^{k_m} 这时我们来看每个质因数的贡献。

我们以 a_1 为例,因为这个数列的最小公约数为 1,所以至少有一个数不含 a_1 这个质因子,又因为这个数列的最小公倍数为 \dfrac{y}{x} 所以至少有一个数含 k_1 个 a_1。

我们先不考虑限制条件,因为每个数都可能包含 0 到 k_1 个 a_1,所以其对答案的贡献为 {(k_1+1)}^n,而限制条件也好解决,我们只需要减去所有数只含有 1 到 k_1 和 0 到 k_1-1 的情况,也就是 2 \times k_1^n 种可能,注意到 1 到 k_1-1 的情况减了两次,所以加上 {(k_1-1)}^n 就为该因子的贡献。

代码

#include<bits/stdc++.h>
#define int long long
#define inf 0x7f7f7f7f
#define mod 998244353
using namespace std;
const int maxn = 1e6 + 100;
inline int read() {
    int x=0,f=1;char ch=getchar();
    while (ch<'0'||ch>'9'){if (ch=='-') f=-1;ch=getchar();}
    while (ch>='0'&&ch<='9'){x=x*10+ch-48;ch=getchar();}
    return x*f;
}
inline void write(int x) {
    if(x < 0) x = ~(x - 1) , putchar('-');
    if(x > 9) write(x / 10);
    putchar(x % 10 + '0');
}
inline void writeh(int x) {
    write(x);
    putchar('\n');
}
inline void writek(int x) {
    write(x);
    putchar(' ');
}
int q , x , y , n , tot , c[maxn];
inline int ksm(int x , int k) {
    int ans = 1 , y = x;
    while(k) {
        if(k & 1) ans = (ans * y) % mod;
        y = (y * y) % mod;
        k >>= 1;
    }
    return ans;
}
inline void fenjie(int x) {
    tot = 0;
    for(int i = 2; i * i <= x; i++) {
        if(x % i == 0) {
            tot++;
            c[tot] = 0;//注意一定要清空
            while(x % i == 0) {
                c[tot]++;
                x /= i;
            }
        }
    }
    if(x > 1) c[++tot] = 1;
}
inline void work() {
    x = read();
    y = read();
    n = read();
    y = y / x;
    int ans = 1 , tmp;
    fenjie(y);
    for(int i = 1; i <= tot; i++) {
        tmp = ksm(c[i] + 1 , n);
        tmp = ((tmp - 2 * ksm(c[i] , n) + ksm(c[i] - 1 , n)) % mod + mod) % mod;
        ans = (ans * tmp) % mod;
    }
    writeh(ans);
}
signed main(){
    q = read();
    while(q--) work();
    return !("wjl1100 qwq");
}