Skip to the content.

:warning: number-theory/mobius-function.hpp

Depends on

Code

#pragma once

#include "math/lpf-table.hpp"

namespace MobiusFunction {
vector<int> table(int n) {
  vector<int> mu(n + 1, 1);
  mu[0] = 0;
  auto lpf = LPFTable(n);
  for (int x = 2; x <= n; x++) {
    int p = lpf[x];
    if (x / p % p == 0)
      mu[x] = 0;
    else
      mu[x] = -mu[x / p];
  }
  return mu;
}
};  // namespace MobiusFunction
#line 2 "number-theory/mobius-function.hpp"

#line 2 "math/lpf-table.hpp"

vector<int> LPFTable(int n) {
  vector<int> lpf(n + 1, 0);
  iota(lpf.begin(), lpf.end(), 0);
  for (int p = 2; p * p <= n; p += (p & 1) + 1) {
    if (lpf[p] != p) continue;
    for (int i = p * p; i <= n; i += p)
      if (lpf[i] == i) lpf[i] = p;
  }
  return lpf;
}
/**
 * @brief LPF Table
 */
#line 4 "number-theory/mobius-function.hpp"

namespace MobiusFunction {
vector<int> table(int n) {
  vector<int> mu(n + 1, 1);
  mu[0] = 0;
  auto lpf = LPFTable(n);
  for (int x = 2; x <= n; x++) {
    int p = lpf[x];
    if (x / p % p == 0)
      mu[x] = 0;
    else
      mu[x] = -mu[x / p];
  }
  return mu;
}
};  // namespace MobiusFunction
Back to top page