欧拉函数被定义为小于或等于n的数中与n互质的个数。它的一般计算式是:phi(n) = n*(1-1/p1)*(1-1/p2)*...*(1-1/pk),其中p1...pk为n的所有质因子。
关于欧拉函数有如下几点性质:
1、phi(1) = 1
2、若n是质数,那么phi(n) = n-1
3、若n是质数x的k次幂,phi(n) = (x-1)*x^(k-1)
4、若m,n互质,那么phi(m*n) = phi(m)*phi(n)
5、若n是奇数,那么phi(2*n) = phi(n)
6、若x,y是质数,且n = x*y,那么phi(n) = (x-1)*(y-1)
6、小于n且与n互质的数的和为:n/2 * phi(n)
下面的代码求出了整数n的欧拉函数值:
#include <cmath>
int GetPhi(int n)
{
int m = sqrt(n+0.5);
int ans = n;
for(int i=2; i<=m; ++i) if(n%i == 0)
{
ans = ans/i * (i-1);
while(n%i == 0) n /= i;
}
if(n > 1) ans = ans/n * (n-1);
return ans;
}
下面的代码求出了1~n中所有数的欧拉函数值,并保存在了phi数组中:
const int MAXN = 3e6+5;
__int64 phi[MAXN];
void PhiTable(int n)
{
for(int i=2; i<=n; ++i)
phi[i] = 0;
phi[1] = 1;
for(int i=2; i<=n; ++i) if((!phi[i]))
for(int j=i; j<=n; j+=i)
{
if(!phi[j]) phi[j] = j;
phi[j] = phi[j]/i * (i-1);
}
}
下面的代码求出了1~n中所有数的欧拉函数值的前缀和,并保存在了f数组中:
const int MAXN = 3e6+5;
__int64 f[MAXN];
void SumPhiTable(int n)
{
f[1] = 1;
for(int i=2; i<n; ++i)
{
if(!f[i])
{
for(int j=i; j<n; j+=i)
{
if(!f[j]) f[j] = j;
f[j] = f[j]/i * (i-1);
}
}
f[i] += f[i-1];
}
}
下面具体来看一道例题,HDOJ:2824,传送门( 点击打开链接),题目如下:
The Euler function
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 3867 Accepted Submission(s): 1602
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)
Input
There are several test cases. Each line has two integers a, b (2<a<b<3000000).
Output
Output the result of (a)+ (a+1)+....+ (b)
Sample Input
3 100
Sample Output
3042
求a~b中所有数的欧拉函数值的和
分析:
可以先将所有数的欧拉函数值计算出来并保存,最后直接将要求范围内的数的欧拉函数值加起来即可。
源代码:
#include <cstdio>
#include <cstring>
const int MAXN = 3e6+5;
__int64 phi[MAXN];
void PhiTable(int n)
{
for(int i=2; i<=n; ++i)
phi[i] = 0;
phi[1] = 1;
for(int i=2; i<=n; ++i) if((!phi[i]))
for(int j=i; j<=n; j+=i)
{
if(!phi[j]) phi[j] = j;
phi[j] = phi[j]/i * (i-1);
}
}
int main()
{
int a, b;
PhiTable(3e6);
while(~scanf("%d%d", &a, &b))
{
__int64 ans = 0;
for(int i=a; i<=b; ++i) // 累加答案
ans += phi[i];
printf("%I64d\n", ans);
}
return 0;
}
其他相关的题目还有,HDOJ:1286,2588,3501。