kyopro-lib

This documentation is automatically generated by online-judge-tools/verification-helper

View on GitHub

:x: Count coprime
(Mylib/Number/Prime/count_coprime.cpp)

Operations

Requirements

Notes

Problems

References

Depends on

Verified with

Code

#pragma once
#include <cstdint>
#include "Mylib/Number/Prime/prime_factorize.cpp"

namespace haar_lib {
  int64_t count_coprime(int64_t n, int64_t m) {
    const auto p = prime_factorize(m);
    const int k  = p.size();

    int64_t ret = 0;

    for (int i = 0; i < 1 << k; ++i) {
      int64_t s = 1;

      for (int j = 0; j < k; ++j) {
        if (i & (1 << j)) s *= p[j].first;
      }

      if (__builtin_popcount(i) % 2 == 1)
        ret -= n / s;
      else
        ret += n / s;
    }

    return ret;
  }
}  // namespace haar_lib
#line 2 "Mylib/Number/Prime/count_coprime.cpp"
#include <cstdint>
#line 3 "Mylib/Number/Prime/prime_factorize.cpp"
#include <utility>
#include <vector>

namespace haar_lib {
  auto prime_factorize(int64_t n) -> std::vector<std::pair<int64_t, int64_t>> {
    std::vector<std::pair<int64_t, int64_t>> ret;
    for (int64_t i = 2LL; i * i <= n; ++i) {
      if (n % i == 0) {
        int64_t c = 0;
        while (n % i == 0) {
          n /= i;
          ++c;
        }
        ret.emplace_back(i, c);
      }
    }
    if (n != 1) ret.emplace_back(n, 1);
    return ret;
  }
}  // namespace haar_lib
#line 4 "Mylib/Number/Prime/count_coprime.cpp"

namespace haar_lib {
  int64_t count_coprime(int64_t n, int64_t m) {
    const auto p = prime_factorize(m);
    const int k  = p.size();

    int64_t ret = 0;

    for (int i = 0; i < 1 << k; ++i) {
      int64_t s = 1;

      for (int j = 0; j < k; ++j) {
        if (i & (1 << j)) s *= p[j].first;
      }

      if (__builtin_popcount(i) % 2 == 1)
        ret -= n / s;
      else
        ret += n / s;
    }

    return ret;
  }
}  // namespace haar_lib
Back to top page