Luogu P1593 因子和
题目
求\(A^B\)的因子和对\(9901\)取模后的结果
题解
对\(A\)分解质因数\(A=\sum p_{i}^{c_i}\)
那么\(A^B = \sum p_{i}^{c_i\times B}\)
考虑\(A^B\)的所有因数和可表示为\((1+p_{1}+p_{1}^{2}+...+p_{1}^{c_1 \times B}) \times (1+p_{2}+p_{2}^{2}+...+p_{2}^{c_2 \times B}) \times ... \times (1+p_{n}+p_{n}^{2}+...+p_{n}^{c_n \times B})\)
最后结果为若干等比数列和的乘积,但是等比数列求和涉及到除法,除法的取余运算涉及到逆元的知识,这里我们换个角度思考。
定义\(sum(p,c)=1+p+p^2+...+p^c\)
当\(c\)为奇数时\(sum(p, c) = 1+p+p^2+...+p^{\frac{c-1}{2}}+p^{\frac{c+1}{2}}+...+p^c=(1+p+...+p^{\frac{c-1}{2}})+p^{\frac{c+1}{2}} \times (1+p+...+p^{\frac{c-1}{2}})=(1+p^{\frac{c+1}{2}})\times sum(p, \frac{c-1}{2})\)
同理\(c\)为偶数时\(sum(p, c) = (1 + p^{\frac{c}{2}}) \times sum(p, \frac{c}{2} - 1) + p ^ c\)
分治求解即可
code
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const LL mod = 9901;
LL quickm(LL a, LL b) {
LL ans = 1ll;
for (; b; b >>= 1) {
if (b & 1) ans = (LL)(ans * a) % mod;
a = (LL)(a * a) % mod;
}
return ans % mod;
}
// x^y
// y为奇数 (1 + x^((y+1)/2)) * sum(x, (y-1)/2)
// y为偶数 (1 + x^(y/2)) * sum(x, y/2 - 1) + x ^ y
LL sum(LL x, LL y) {
if (y == 0) return 1;
if (y % 2 == 1) {
return (LL)(1 + quickm(x, (y+1)/2)) * sum(x, (y-1)/2) % mod;
} else {
return (LL)((1 + quickm(x, y/2)) * sum(x, (y/2)-1) + quickm(x, y)) % mod;
}
}
int main() {
int a, b;
scanf("%d%d", &a, &b);
if (a == 0) {
cout << 0 << endl;
return 0;
}
// 分解质因子
LL temp = a, res = 1;
for (int i = 2; i * i <= a; ++i) {
if (temp % i == 0) {
LL x = i, y = 0;
for (; temp % i == 0; temp /= i) ++y;
res = (res * sum(x, (LL)y * b)) % mod;
}
}
if (temp > 1)
res = res * sum(temp, b) % mod;
printf("%lld\n", res);
return 0;
}