题目大意:继上一篇#1286单独求解欧拉函数,这里要求两个数之间的欧拉函数值之和为多少?
解题思路:这里采取递推求解,在上一篇已经分析过。一般小数据量头可以直接递推求解,保存每一位的欧拉函数值。但如果数据量较大时,并不需要依次计算,可以使用筛法,即与求素数打表类似的解法。将该区间的欧拉函数值筛选出来,直接对给出区间进行相减即可得,详见code。
题目来源:http://acm.hdu.edu.cn/showproblem.php?pid=2824
code:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
#define ll __int64
const int MAXN = 3000000+10;
int a,b;
ll phi[MAXN];
void phi_table(){
memset(phi,0,sizeof(phi));
phi[1]=1;
for(int i=2;i<MAXN;i++){
if(!phi[i])
for(int j=i;j<MAXN;j+=i){
if(!phi[j]) phi[j]=j;
phi[j]=phi[j]/i*(i-1);
}
phi[i]+=phi[i-1]; //中间记录,每一个位置都存储为前面之和,这样我计算两者之间只需要相减即可得
}
}
int main(){
phi_table();
while(scanf("%d%d",&a,&b)!=EOF)
printf("%I64d\n",phi[b]-phi[a-1]);
return 0;
}