题意:输入n 求 phi(2)+phi(3)+phi(4)+...+phi(n)
思路:用类似筛法的方式计算phi(1), phi(2), ..., phi(n) 再求前缀和
#include <cstdio> #include <cstring> #include <cmath> //欧拉phi函数 const int maxn = 1000010; typedef long long LL; int euler_phi(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; } LL phi[maxn]; void phi_table(int n) { for(int i = 2; i <= n; i++) phi[i] = 0; phi[1] = 0; 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 n; phi_table(1000000); for(int i = 2; i <= 1000000; i++) phi[i] += phi[i-1]; while(scanf("%d", &n) && n) printf("%lld\n", phi[n]); return 0; }
POJ 2478 Farey Sequence 筛选法求欧拉函数,布布扣,bubuko.com
POJ 2478 Farey Sequence 筛选法求欧拉函数
原文地址:http://blog.csdn.net/u011686226/article/details/25559207