Advertisement
newb_ie

Euler Phi + Sieve

Mar 19th, 2021
291
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.18 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. const int maxN = 151622;
  5. int64_t isVisited[maxN / 64 + 200];
  6. vector<int64_t> primes;
  7. void Sieve_of_Eratosthenes(int limit){
  8.     limit += 100;
  9.     for(int64_t i = 3; i <= sqrt(limit) ; i += 2){
  10.         if(!(isVisited[i/64]&(1LL<<(i%64)))) {
  11.             for(int64_t j = i * i; j <= limit; j += 2 * i) {
  12.                 isVisited[j/64] |= (1LL<<(j%64));
  13.             }
  14.         }
  15.     }
  16.     primes.push_back(2);
  17.     for(int64_t i = 3; i <= limit; i += 2){
  18.         if(!(isVisited[i / 64] & (1LL << (i % 64)))) {
  19.             primes.push_back(i);
  20.         }
  21.     }
  22. }
  23.  
  24. int64_t Phi (int64_t n) {
  25.     if (n == 1) return 0;
  26.     int64_t res = n;
  27.     for (int64_t i : primes) {
  28.         if (i * i > n) break;
  29.         if (n % i == 0) {
  30.             while (n % i == 0) {
  31.                 n /= i;
  32.             }
  33.             res -= res / i;
  34.         }
  35.     }
  36.     if (n != 1) {
  37.         res -= res / n;
  38.     }
  39.     return res;
  40. }
  41.  
  42. int main () {
  43.      ios::sync_with_stdio(false);
  44.      cin.tie(nullptr);
  45.      cout.tie(nullptr);
  46.      int T = 1;
  47.      //~ cin >> T;
  48.      Sieve_of_Eratosthenes(maxN);
  49.      for (int test_case = 1; test_case <= T; ++test_case) {
  50.          int64_t n;
  51.          while (cin >> n and n > 0) {
  52.              cout << Phi(n) << '\n';
  53.          }
  54.      }
  55.      //cerr << "Time elapsed :" << clock() * 1000.0 / CLOCKS_PER_SEC << " ms" << '\n';
  56. }
  57.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement