counts the integers in coprime to .
is multiplicative: when , and .
Computing it
Single value, :
long long phi(long long n) {
long long res = n;
for (long long p = 2; p * p <= n; p++)
if (n % p == 0) {
while (n % p == 0) n /= p;
res -= res / p; // res *= (1 - 1/p)
}
if (n > 1) res -= res / n;
return res;
}All values up to , :
vector<int> phi(N + 1);
iota(phi.begin(), phi.end(), 0);
for (int i = 2; i <= N; i++)
if (phi[i] == i) // i is prime
for (int j = i; j <= N; j += i) phi[j] -= phi[j] / i;A linear sieve computes it in alongside the smallest prime factor.
Euler’s theorem
Fermat’s little theorem is the case : .
Consequence: exponents can be reduced modulo :
When — the generalised theorem
This is what makes power towers computable: to evaluate , recurse on the exponent modulo , then , and so on. The chain reaches 1 in steps, so the recursion is shallow.
long long tower(vector<long long>& a, int i, long long m) {
if (m == 1) return 0;
if (i == (int)a.size()) return 1;
long long p = phi(m);
long long e = tower(a, i + 1, p);
return powmodSafe(a[i], e + p, m); // add phi(m) to stay in the safe range
}Key identities
| Identity | |
|---|---|
| the divisor sum | |
| for prime | |
| if even, if odd | |
| is even for | |
| sum of the coprime residues, for | |
| -sum: |
The divisor-sum identity is the one that keeps appearing. It says: partition by ; the class for has elements.
Where shows up
| Problem | Use |
|---|---|
| Count coprime pairs / fractions in lowest terms | — the Farey sequence length |
| Multiplicative order, primitive roots | the order divides |
| Modular inverse for composite | |
| Power towers | the generalised Euler theorem |
| Number of generators of a cyclic group of order | |
| Necklace / Burnside counting | |
| Length of the repeating decimal of | the multiplicative order of 10 mod , which divides |
| Counting lattice points visible from the origin | -based |
Farey / coprime counting
The number of fractions in lowest terms with is . To compute this sum for up to , use the Mertens-style recursion:
evaluated with divisor-block grouping and memoisation — with a sieve for small values. This is the standard technique for “sum a multiplicative function up to a huge ”.
See also: Möbius Function · Divisor Functions · Primitive Root