Motivation Problem

Given a sequence of positive integers, say a, count number of ordered distinct triplets such that their greatest common divisor is 1.

Naive solution

\mathcal{O}(n^3\log{\text{max }a_{i}})
O(n3logmax ai)\mathcal{O}(n^3\log{\text{max }a_{i}})

Expected Solution

\mathcal{O(n\log{n})}
O(nlogn)\mathcal{O(n\log{n})}
\mathcal{O}({n\log{\text{max }a_{i}}})
O(nlogmax ai)\mathcal{O}({n\log{\text{max }a_{i}}})

Greatest Common Divisor

Euler's Algorithm

\text{Time Complexity: }\mathcal{O}(\log{\text{max }(a, b)})
Time Complexity: O(logmax (a,b))\text{Time Complexity: }\mathcal{O}(\log{\text{max }(a, b)})

Multiplicative Function

\text{An arithmetic function } f(n) : \mathbb{N}\rightarrow\mathbb{C} \text{ is multiplicative }
An arithmetic function f(n):NC is multiplicative \text{An arithmetic function } f(n) : \mathbb{N}\rightarrow\mathbb{C} \text{ is multiplicative }
\text{if for any relatively prime } n, m \in \mathbb{N}:
if for any relatively prime n,mN:\text{if for any relatively prime } n, m \in \mathbb{N}:
f(mn) = f(m)f(n).
f(mn)=f(m)f(n).f(mn) = f(m)f(n).

One Sieve to rule them all

int primes[N] = {1} // 1 a prime
int lowestPrime[N]
int phi[N]
int mu[N]

for i in [2 .. N]:
    if primes[i] is 1:
        lowestPrime[i] = i
        j = i
        while j <= N:
            primes[j] = 0
            if primes[j] is 1:
                lowestPrime[j] = i
                primes[j] = 0
            j += i
            
        phi[i] = i - 1
        mu[i] = -1
    else:
        if lowestPrime[i] is lowestPrime[i / lowestPrime[i]]:
            mu[i] = 0
            phi[i] = lowestPrime[i] * phi[i / lowestPrime[i]]
        else:
            mu[i] = -1 * mu[i / lowestPrime[i]]
            phi[i] = (lowestPrime[i] - 1) * phi[i / lowestPrime[i]]

Bonus

We can do all of the above in:

\mathcal{O}(n)
O(n)\mathcal{O}(n)

deck

By parv