标签:
求单个数字的欧拉函数值的两种方法:
1 #include <iostream> 2 using namespace std; 3 4 int phi( int n ) 5 { 6 int ans = n; 7 for ( int i = 2; i * i <= n; i++ ) 8 { 9 if ( n % i == 0 ) 10 { 11 ans -= ans / i; 12 do 13 { 14 n = n / i; 15 } while ( n % i == 0 ); 16 } 17 } 18 if ( n != 1 ) 19 { 20 ans -= ans / n; 21 } 22 return ans; 23 } 24 25 int pphi( int n ) 26 { 27 int ans = 1; 28 for ( int i = 2; i * i <= n; i++ ) 29 { 30 if ( n % i == 0 ) 31 { 32 ans *= i - 1; 33 n = n / i; 34 while ( n % i == 0 ) 35 { 36 ans *= i; 37 n = n / i; 38 } 39 } 40 } 41 if ( n != 1 ) 42 { 43 ans *= n - 1; 44 } 45 return ans; 46 } 47 48 int main() 49 { 50 int t; 51 cin >> t; 52 while ( t-- ) 53 { 54 int n; 55 cin >> n; 56 cout << pphi(n) << endl; 57 } 58 return 0; 59 }
筛法求欧拉函数:
1 #include <iostream> 2 using namespace std; 3 4 const int N = 32768; 5 int phi[N]; 6 7 void init() 8 { 9 phi[0] = phi[1] = 1; 10 for ( int i = 2; i < N; i++ ) 11 { 12 phi[i] = i; 13 } 14 for ( int i = 2; i < N; i++ ) 15 { 16 if ( phi[i] == i ) 17 { 18 phi[i]--; 19 for ( int j = i + i; j < N; j += i ) 20 { 21 phi[j] -= phi[j] / i; 22 } 23 } 24 } 25 } 26 27 int main() 28 { 29 init(); 30 int t; 31 cin >> t; 32 while ( t-- ) 33 { 34 int n; 35 cin >> n; 36 cout << phi[n] << endl; 37 } 38 return 0; 39 }
模板题:hdu 1286 poj 1284
标签:
原文地址:http://www.cnblogs.com/huoxiayu/p/4470629.html