1. 程式人生 > >Change the world by program.

Change the world by program.

莫比烏斯函式定義

μ(n)={1(n=0)(1)k(n=p1p2...pk,pi!=pj)0(others)

莫比烏斯函式計算

直接計算,只需要對n做一次唯一分解就可以了,複雜度 O(n)

#include<bits/stdc++.h>
using namespace std;

const int maxn=100005;

int main(){
    int n,m,k;
    while(scanf("%d",&n)==1){
        m=sqrt
(n)+0.5; k=0; bool ok=true; for(int i=2;i<=m;++i){ if(n%i==0){ int tmp=0; while(n%i==0){ n/=i; ++tmp; } if(tmp>1){ ok=false; break
; } else k+=tmp; } } if(n>1) ++k; if(ok) printf("%d\n",(k&1)?-1:1); else puts("0"); } return 0; }

線性篩選

#include<bits/stdc++.h>
using namespace std;

const int maxn=10000005;

bool vis[maxn];
int prim[maxn];
int
mu[maxn]; int cnt; void get_mu(int n){ mu[1]=1; for(int i=2;i<=n;i++){ if(!vis[i]){ prim[++cnt]=i; mu[i]=-1; } for(int j=1;j<=cnt && prim[j]*i<=n;j++){ vis[prim[j]*i]=1; if(i%prim[j]==0) break; else mu[i*prim[j]]=-mu[i]; } } }

莫比烏斯函式的常用性質

d|nμ(d)={1(n=1)0() d|nμ(d)d=phi(n)n

反演公式

對於函式 F(n)f(n) 滿足

F(n)=d|nf(d) 那麼就有 f(n)=d|nu(d)F(nd) 或者若滿足 F(n)=n|df(d) 就有 f(n)=n|du(dn)F(d)