線性篩
歐拉篩本質上是在對每一個數找到它最小的質因數,然後把它篩除,複雜度
本文中所有的
PROOF:
From the code below we have that
Let
Q.E.D.
#include <cstdio>
#define R register
const int MaxN = 1000000
bool vis[MaxN];
int P[MaxN], tot;
int main()
{
for(R int i = 2; i <= MaxN; i++)
{
if(!vis[i]) P[++tot] = i, phi[i] = P[tot] - 1;
for(R int j = 1; j <= tot && P[j] * i <= MaxN; j++)
{
vis[i * P[j]] = 1;
if(i % P[j] == 0) break;
}
}
return 0;
}
歐拉函數 φ
歐拉函數:
Euler Theorem:
Theorem 1:
PROOF
Let
Q.E.D.
歐拉篩解決歐拉函數,
由前文可知,歐拉篩可以讓我們快速的找出每一個數的最小質因數。
由於歐拉函數是積性函數,所以我們只需要求出
PROOF:
Let
We conclude that
Q.E.D.
#include <cstdio>
#define R register
bool vis[1000010];
int P[1000010], tot, phi[1000010];
int main()
{
for(R int i = 2; i <= 1000000; i++)
{
if(!vis[i]) P[++tot] = i, phi[i] = P[tot] - 1;
for(R int j = 1; j <= tot && P[j] * i <= 1000000; j++)
{
vis[i * P[j]] = 1;
if(i % P[j] == 0)
{
phi[i * P[j]] = phi[i] * P[j];
break;
}
else phi[i * P[j]] = phi[i] * (P[j] - 1);
}
}
return 0;
}
莫比烏斯反演 μ
歐拉篩解決莫比烏斯函數,
莫比烏斯函數:
莫比烏斯函數可以用於解決形如:
同理,莫比烏斯函數也是一個積性函數,所以我們只需快速地求出
PROOF:
From the defination of Möbius inversion formula we have that iff
We conclude that
Q.E.D.
#include <cstdio>
#define R register
bool vis[1000010];
int P[1000010], tot, mu[1000010];
int main()
{
mu[1] = 1;
for(R int i = 2; i <= 1000000; i++)
{
if(!vis[i]) P[++tot] = i, mu[i] = -1;
for(R int j = 1; j <= tot && P[j] * i <= 1000000; j++)
{
vis[i * P[j]] = 1;
if(i % P[j] == 0)
{
mu[i * P[j]] = 0;
break;
}
else mu[i * P[j]] = -mu[i];
}
}
return 0;
}
參考文獻:
1.賈志鵬,《線性篩法與積性函數》。