P3768 简单的数学题 [莫比乌斯反演+杜教筛]

本文深入探讨了杜教筛算法的实现细节,该算法是一种高效求解数论中积性函数前缀和的方法。通过代码示例展示了如何利用杜教筛优化计算过程,特别关注于Id^2函数的处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

传送门

 

 

 

用杜教筛筛就可以了(g 设为Id^2) 


#include<bits/stdc++.h>
#define N 10000050
#define LL long long
using namespace std;
LL P,n;
int prim[N],isp[N],tot; LL phi[N];
map<LL,LL> Phi;
LL inv2, inv6;
LL power(LL a, LL b){
	LL ans = 1;
	for(;b;b>>=1){ if(b&1) ans = (ans*a) % P; a = (a*a) % P;}
	return ans;
}
void prework(){
	inv2 = power(2, P-2);
	inv6 = power(6, P-2);
	phi[1] = 1;
	for(int i=2;i<=N-50;i++){
		if(!isp[i]) prim[++tot] = i, phi[i] = i-1;
		for(int j=1;j<=tot;j++){
			if(i * prim[j] > N - 50) break;
			isp[i * prim[j]] = 1;
			if(i % prim[j] == 0){
				phi[i * prim[j]] = phi[i] * prim[j];
				break;
			}
			phi[i * prim[j]] = phi[i] * (prim[j] - 1);
		}
	}
	for(int i=1;i<=N-50;i++) phi[i] = phi[i] % P * i % P * i % P;
	for(int i=2;i<=N-50;i++) phi[i] += phi[i-1], phi[i] %= P;
}
LL Sum(LL x){x %= P; return x * (x+1) % P * inv2 % P;}
LL G(LL x){ x %= P; return x * (x+1) % P * (x*2+1) % P * inv6 % P;}
LL getf(LL x){
	if(x<=N-50) return phi[x];
	if(Phi[x]) return Phi[x];
	LL ans = Sum(x); ans = (ans * ans) % P;
	for(LL l=2,r;l<=x;l=r+1){
		LL val = x/l; r = x/val;
		ans -= (G(r) - G(l-1)) % P * getf(val) % P;
		ans = (ans + P) % P; 
	} return Phi[x] = ans;
}
int main(){
	scanf("%lld%lld",&P,&n); prework();
	LL ans = 0;
	for(LL l=1,r;l<=n;l=r+1){
		LL val = n/l; r = n/val;
		LL tmp = Sum(val); tmp = (tmp * tmp) % P;
		ans += tmp * (getf(r) - getf(l-1)) % P;
		ans = (ans + P) % P;
	} printf("%lld",ans);	
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

FSYo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值