标签:style blog os io for 2014 cti amp
定义:求小于n与n互素的整数个数。
推导公式:
ans = n(1-1/p1)(1-1/p2)..........(1-1/pk); 其中pi为n的质因子
#include<cstdio> #include<cstring> #include<iostream> #include<algorithm> #include<vector> #include<stack> #include<queue> #include<map> #include<set> #include<list> #include<cmath> #include<string> #include<sstream> #include<ctime> using namespace std; #define _PI acos(-1.0) #define INF (1 << 10) #define esp 1e-6 typedef long long LL; typedef unsigned long long ULL; typedef pair<int,int> pill; /*=========================================== 欧拉公式: ans = n * (1 - 1/p1)(1 - 1/p2)....(1 - 1/pk); ===========================================*/ int euler_phi(int n){ int m = (int)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; } int main(){ int n; while(scanf("%d",&n) != EOF){ int ans = euler_phi(n); printf("%d\n",ans); } return 0; }
拓展:求n以内的数的质因子的个数
方法:筛选法
#include<cstdio> #include<cstring> #include<iostream> #include<algorithm> #include<vector> #include<stack> #include<queue> #include<map> #include<set> #include<list> #include<cmath> #include<string> #include<sstream> #include<ctime> using namespace std; #define _PI acos(-1.0) #define INF (1 << 10) #define esp 1e-6 typedef long long LL; typedef unsigned long long ULL; typedef pair<int,int> pill; /*=========================================== 欧拉公式: ans = n * (1 - 1/p1)(1 - 1/p2)....(1 - 1/pk); ===========================================*/ #define MAXD 20000 int phi[MAXD]; void phi_table(int n){ memset(phi,0,sizeof(phi)); 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); } } return ; } int main(){ phi_table(1000); printf("%d\n",phi[1000]); return 0; }
标签:style blog os io for 2014 cti amp
原文地址:http://blog.csdn.net/u013451221/article/details/38513421