1. 程式人生 > >51 Nod 1244 莫比烏斯函數前n項和

51 Nod 1244 莫比烏斯函數前n項和

pos 莫比烏斯 mes temp spa 線性篩 col 代碼 typedef

積性函數前n項和必看好文

https://blog.csdn.net/skywalkert/article/details/50500009

遞歸計算的時候要用map記憶化一下,前面的打表會比較快一點。

AC代碼

#include<bits/stdc++.h>
using namespace std;
const int maxn=1e6+10;
typedef long long ll;
map<ll,ll> ma;
int check[maxn],prime[maxn],mu[maxn];
void Mobius(int N)//莫比烏斯函數線性篩
{
    int pos=0;mu[1]=1
; for (int i = 2 ; i <= N ; i++) { if (!check[i]) prime[pos++] = i,mu[i]=-1; for (int j = 0 ; j < pos && i*prime[j] <= N ; j++) { check[i*prime[j]] = 1; if (i % prime[j] == 0) { mu[i*prime[j]]=0
; break; } mu[i*prime[j]]=-mu[i]; } } for(int i=2;i<=N;i++) mu[i]+=mu[i-1]; } ll solve(ll a) { if(a<=1e6) //記憶化 return mu[a]; if(ma.count(a)) return ma[a]; ll temp=1; for(ll i=2;i<=a;) { ll t
=a/i; ll k=a/t; temp-=(k-i+1)*solve(t);//分段或者叫分塊加速一下 i=k+1; } return ma[a]=temp; } int main() { Mobius(1e6); ll a,b; cin>>a>>b; cout<<solve(b)-solve(a-1)<<endl; }

51 Nod 1244 莫比烏斯函數前n項和