The Euler function
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)
Sample Input
3 100
3042
回顾一下欧拉函数的性质:小于或等于n的与n互质的整数数量为x(1-1/p1)(1-1/p2)(1-1/p3)(1-1/p4)…..(1-1/pn)
与n互质的所有数的和sum=n*[φ(n)/2]
一个数一个数的判断会超时,可以用类似于素数筛选的方法打表
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <iostream>
using namespace std;
#define maxn 3000010
long long phi[maxn+1];
void Euler() {
long long a,b,i,j;
for(i=1; i<=maxn; i++) phi[i]=i;
for(i=2; i<=maxn; i+=2) phi[i]/=2;
for(i=3; i<=maxn; i+=2)
if(phi[i]==i) {
for(j=i; j<=maxn; j+=i)
phi[j]=phi[j]-phi[j]/i;
}
}
int main() {
Euler();
long long a,b;
while(cin>>a>>b) {
long long sum=0; // sum的类型要为long long 不然会WA
for(int i=a; i<=b; i++)
sum+=phi[i];
cout<<sum<<endl;
}
return 0;
}