Skip to main content

Möbius function

std::vector<int32_t> linear_sieve_with_mobius(int32_t n) {
std::vector<int32_t> primes;
std::vector<int32_t> lowest_prime(n, 0);
std::vector<int32_t> mobius(n); mobius[1] = 1;
for (int64_t i = 2; i < n; ++i) {
if (lowest_prime[i] == 0) {
primes.push_back(i);
lowest_prime[i] = i;
mobius[i] = -1;
}
for (auto const& p : primes) {
if (p > lowest_prime[i]) break;
if (auto j = i * p; j < n) {
lowest_prime[j] = p;
mobius[j] = (lowest_prime[i] == p) ? 0 : -mobius[i];
}
}
}
return mobius;
}

Time Complexity:

Theory

Definition 1

  • if n is a square-free positive integer with an even number of prime factors.
  • if n is a square-free positive integer with an odd number of prime factors.
  • if n has a squared prime factor.

Definition 2

Alternately, is a multiplicative function defined by .

Möbius Inversion Formula

The classic version states that if g and f are arithmetic functions satisfying

then

where is the Möbius function