Advertisement
Imran_Mohammed

Euler Totient or phi function

Mar 12th, 2021
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.32 KB | None | 0 0
  1. //In the name of Allah
  2.  
  3. // Euler totient or phi function:complexity( sqrt(n) /ln (sqrt(n) ) )
  4.  
  5. #include<bits/stdc++.h>
  6. using namespace std;
  7.  
  8. #define optimize() ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
  9. #define endl '\n'
  10.  
  11. //Prime Generation
  12. const long long mx = 1e6+123;
  13. bool is_prime[mx];
  14. vector<long long> prime;
  15.  
  16. void primegen ( long long n )
  17. {
  18.     for ( int i = 3; i <= n; i += 2 ) is_prime[i] = 1;
  19.  
  20.     int sq = sqrt ( n );
  21.     for ( int i = 3; i <= sq; i += 2 ) {
  22.         if ( is_prime[i] == 1 ) {
  23.             for ( int j = i*i; j <= n; j += ( i + i ) ) {
  24.                 is_prime[j] = 0;
  25.             }
  26.         }
  27.     }
  28.  
  29. is_prime[2]=1;
  30. prime.push_back(2);
  31.     for ( int i = 3; i <= n; i += 2 ) {
  32.         if ( is_prime[i] == 1 ) prime.push_back ( i );
  33.     }
  34. }
  35.  
  36. //prime Factorization
  37. int phi(long long n){
  38.    long long ret = n;
  39.     for( auto p:prime){
  40.         if( 1ll *p*p > n || n==0 )break;
  41.  
  42.         if(n%p == 0){
  43.         ret /= p;
  44.         ret *= (p-1);
  45.  
  46.             while(n%p == 0){
  47.                 n /= p;
  48.             }
  49.         }
  50.     }
  51.  
  52.     if(n > 1){
  53.         ret /= n;
  54.         ret *= (n-1);
  55.     }
  56.     return ret;
  57. }
  58.  
  59. //main function
  60. int main()
  61. {
  62.     optimize()
  63.  
  64.     primegen(1e6);
  65.  
  66.     long long n;
  67.     cin >> n;
  68.  
  69.     cout << phi(n) << endl;
  70.  
  71.     return 0;
  72. }
  73.  
  74.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement