欧拉函数Euler
在数论中,对正整数n,欧拉函数是小于或等于n的正整数中与n互质的数的数目。
一个数 N = p 1 α 1 p 2 α 2 p 3 α 3 . . . p k α k N\ =\ p_1^{α_1}p_2^{α_2}p_3^{α_3}...p_k^{α_k} N = p1α1p2α2p3α3...pkαk
那么在 1 − N 1-N 1−N中与 N N N互质的数的个数
ϕ ( N ) = N ∏ i = 1 k ( 1 − 1 p i ) \phi(N)\ =\ N\prod_{i=1}^k(1-\frac{1}{p_i}) ϕ(N) = N∏i=1k(1−pi1)
ϕ ( N ) = N ( 1 − 1 p 1 ) ( 1 − 1 p 2 ) . . . ( 1 − 1 p k ) \phi(N)\ =\ N(1-\frac{1}{p_1})(1-\frac{1}{p_2})...(1-\frac{1}{p_k}) ϕ(N) = N(1−p11)(1−p21)...(1−pk1)
int euler(int x)
{
int res = x;
for(int i=2;i<=x/i;++i)
{
if(x%i==0)
{
while(x%i==0) x/=i;
res /= i;
res *= (i-1); //res * (i-1/i)
}
}
if(x>1) res /= x , res *= (x-1);
return res;
}
筛法求欧拉函数
const int maxn = 1e6+5;
int pr[maxn],tot;
int phi[maxn]; //phi[i]表示φ(i)
bool st[maxn];
void get_eulers(int x)
{
phi[1] = 1;
for(int i=2;i<=x;++i)
{
if(st[i] == false)
{
pr[tot++] = i;
//i为素数
phi[i] = i-1;
}
for(int j=0;pr[j]*i <= x;++j)
{
st[pr[j]*i] = true;
if(i%pr[j]==0)
{
/*
i % primes[j] == 0时:primes[j]是i的最小质因子,也是primes[j] * i的最小质因子,
因此1 - 1 / primes[j]这一项在phi[i]中计算过了,只需将基数NN修正为primes[j]倍,
最终结果为phi[i] * primes[j]。
*/
phi[pr[j]*i] = phi[i]*pr[j];
break;
}
/*
i % primes[j] != 0:primes[j]不是i的质因子,只是primes[j] * i的最小质因子,
因此不仅需要将基数NN修正为primes[j]倍,还需要补上1 - 1 / primes[j]这一项,
因此最终结果phi[i] * (primes[j] - 1)。
*/
// phi[pr[j]*i] = phi[i]*pr[j]*(pr[j]-1/pr[j]);
phi[pr[j]*i] = phi[i]*(pr[j]-1);
}
}
}
例题
杭电hdu2824(The Euler function)
Problem Description
The Euler function phi is an important kind of function in number theory, (n) represents the amount of the numbers which are smaller than n and coprime to n, and this function has a lot of beautiful characteristics. Here comes a very easy question: suppose you are given a, b, try to calculate
(
a
)
+
(
a
+
1
)
+
.
.
.
.
+
(
b
)
(a)+ (a+1)+....+ (b)
(a)+(a+1)+....+(b)
Input
There are several test cases. Each line has two integers
a
,
b
(
2
<
a
<
b
<
3000000
)
.
a, b (2<a<b<3000000).
a,b(2<a<b<3000000).
Output
Output the result of
(
a
)
+
(
a
+
1
)
+
.
.
.
.
+
(
b
)
(a)+ (a+1)+....+ (b)
(a)+(a+1)+....+(b)
Sample Input
3 100
Sample Output
3042
线性筛代码:
#include <iostream>
#include <cstdio>
using namespace std;
const int maxn = 3000000;
int pr[maxn],tot;
long long phi[maxn];
bool st[maxn];
void get_euler()
{
phi[1]=1;
int n=3000000;
for(int i=2;i<n;++i)
{
if(!st[i]) pr[tot++]=i , phi[i]=i-1;
for(int j=0;pr[j]*i<n;++j)
{
st[pr[j]*i]=true;
if(i%pr[j]==0)
{
phi[pr[j]*i] = phi[i]*pr[j];
break;
}
phi[pr[j]*i] = phi[i]*(pr[j]-1);
}
}
}
int main()
{
get_euler();
for(int i=1;i<maxn;++i) phi[i]+=phi[i-1]; //转前缀和
int a,b;
while(~scanf("%d%d",&a,&b))
{
printf("%d\n",phi[b]-phi[a-1]);
}
return 0;
}
使用线性筛,在时间上比埃氏筛快2~4倍左右
埃式筛代码:
#include <iostream>
#include <cstdio>
using namespace std;
const int maxn = 3000000;
unsigned long long phi[maxn];
void get_euler() //埃式筛:每一个合数的所有质因子都会筛这个数一遍
{
phi[1]=1;
int n=maxn;
for(int i=2;i<n;++i) phi[i]=i;
for(int i=2;i<n;++i)
{
if(phi[i]==i)
{
for(int j=i;j<n;j+=i)
{
phi[j] = phi[j]/i*(i-1);
}
}
}
}
// main函数省略