Four problems rated 1,700 to 1,800 that ask about divisors, inverses and coprime pairs for up to 10^5 queries. The move: build one table up to the largest value, then answer each query by reading it.
This tent holds four problems rated 1,700 to 1,800. Each one asks the same kind of question many times. It is a quotient under a prime modulus, the rounds to split a size, the distinct fractions up to a limit, or the number of coprime pairs.
The first solution does the arithmetic again for every query. For most of these it is correct and far too slow.
| Problem | The arithmetic per query | Its size at the limits |
|---|---|---|
| Averages under a prime modulus | a fast power for each count | 6 × 10^6 steps: fits, but the table is shorter |
| Splitting a shard down to single documents | trial division up to the square root | 10^8 divisions |
| Distinct playback patterns up to a size | a gcd for every fraction | 1.25 × 10^11 gcds |
| Route loops with no shared rhythm | a gcd for every pair | 2 × 10^10 gcds |
The common fix is to move the work out of the queries. Build a table once, up to the largest value, and let each query read it.
Exercise · Predict the output: The inverses modulo 11. The inverse of i modulo p is the number m with i × m ≡ 1. This fills inv[i] for i = 1 to 6 with p = 11, using the earlier entries only. What does it print?
p = 11
inv = [0] * 7
inv[1] = 1
for i in range(2, 7):
inv[i] = (p - (p // i) * inv[p % i] % p) % p
print(*inv[1:])The queries share their numbers. Ten thousand shard sizes below 10^6 all use the same few primes. So fill a table up to the largest value once, and each query costs one read or one short walk.
Find the largest value in the input, fill a table of that size with a sieve, and answer every query from the table.
A sieve fills such a table in about n log log n steps. For the smallest prime factor, walk the primes in order and, for each prime, write it into every multiple that is still unmarked. A size then splits by peeling: read its smallest prime, divide it out, repeat. A number below 10^6 has at most 19 prime factors, counted with repetition, so a query takes at most 19 steps.
The same shape gives Euler's phi. Start with phi[j] = j, and for each prime p subtract phi[j] // p from every multiple j. Then phi(b) counts the numbers up to b that are coprime to b, and a prefix sum of phi counts the fractions.
Each denominator b adds phi of b new fractions, so a prefix sum of phi counts the distinct fractions up to any limit.
Exercise · Find the bug: The share that is missed. This returns the number of different fractions a/b with 1 ≤ a ≤ b ≤ limit. It adds phi(b) for every b. Which line is wrong?
def distinct_patterns(limit):
phi = list(range(limit + 1))
for i in range(2, limit + 1):
if phi[i] == i:
for j in range(i, limit + 1, i):
phi[j] -= phi[j] // i
total = 0
for b in range(2, limit + 1):
total += phi[b]
return totalThe Academy lesson Bits and maths taught gcd, modular arithmetic and the basic sieve. Common classes felt taught what 10^8 steps feel like, and Prefix sums gave the running total. This tent keeps those tools and changes the setting: a table up to 10^6, for 10^5 queries, answered under a modulus or in 64 bits.
Three ideas are new. The first is the inverse table. Dividing under a prime modulus is multiplying by an inverse, and the recurrence fills the inverses of 1 to n in n steps, with no fast power.
The second is inclusion and exclusion over divisors. To count the pairs with gcd exactly one, count the multiples of every d. Then add or subtract the pairs sharing each d, by the sign of the Möbius function.
The third is a trap in that count. It is tempting to subtract the pairs that share a prime, once per prime. A pair that shares two primes is then subtracted twice.
Subtracting the pairs that share a prime, once per prime, removes a pair that shares two primes twice; add it back.
Exercise · Break it: The pair that shares two primes. This counts the pairs of different routes whose loop lengths have a gcd of 1. It starts from all pairs and subtracts, for each prime, the pairs of loops divisible by it. Find an input where it is wrong.
def coprime_pairs(loops):
n = len(loops)
count = {}
for x in loops:
d = 2
while d * d <= x:
if x % d == 0:
count[d] = count.get(d, 0) + 1
while x % d == 0:
x //= d
d += 1
if x > 1:
count[x] = count.get(x, 0) + 1
bad = 0
for c in count.values():
bad += c * (c - 1) // 2
return n * (n - 1) // 2 - bad| Limit | What it tells you |
|---|---|
| values up to 10^6, 10^5 of them | a table of 10^6 cells, built once |
| limits up to 5 × 10^5 | the sum of phi reaches 75,991,039,676: 64-bit integers |
| 10^5 routes | 4,999,950,000 pairs: a 32-bit count overflows |
| a prime modulus up to 10^9 + 7 | a product reaches about 10^18: reduce after every multiplication |
| 10^5 queries | read the input once, and print the answers once |
The full treatment is in Fast I/O and stress testing. Here the table is built once for the largest query, and the answers are collected and printed together. Prefix sums of phi need a 64-bit array.
import sys
def main():
data = sys.stdin.buffer.read().split()
q = int(data[0])
limits = [int(x) for x in data[1:1 + q]]
top = max(limits)
phi = list(range(top + 1))
for i in range(2, top + 1):
if phi[i] == i:
for j in range(i, top + 1, i):
phi[j] -= phi[j] // i
prefix = [0] * (top + 1)
for b in range(1, top + 1):
prefix[b] = prefix[b - 1] + phi[b]
sys.stdout.write("\n".join(str(prefix[n]) for n in limits) + "\n")
main()import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
int q = (int) in.nval;
int[] limits = new int[q];
int top = 0;
for (int i = 0; i < q; i++) {
in.nextToken();
limits[i] = (int) in.nval;
top = Math.max(top, limits[i]);
}
int[] phi = new int[top + 1];
for (int i = 0; i <= top; i++) phi[i] = i;
for (int i = 2; i <= top; i++) {
if (phi[i] == i) {
for (int j = i; j <= top; j += i) phi[j] -= phi[j] / i;
}
}
long[] prefix = new long[top + 1];
for (int b = 1; b <= top; b++) prefix[b] = prefix[b - 1] + phi[b];
StringBuilder out = new StringBuilder();
for (int n : limits) out.append(prefix[n]).append("\n");
System.out.print(out);
}
}#include <iostream>
#include <vector>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int q;
cin >> q;
vector<int> limits(q);
int top = 0;
for (int i = 0; i < q; i++) {
cin >> limits[i];
top = max(top, limits[i]);
}
vector<int> phi(top + 1);
for (int i = 0; i <= top; i++) phi[i] = i;
for (int i = 2; i <= top; i++) {
if (phi[i] == i) {
for (int j = i; j <= top; j += i) phi[j] -= phi[j] / i;
}
}
vector<long long> prefix(top + 1, 0);
for (int b = 1; b <= top; b++) prefix[b] = prefix[b - 1] + phi[b];
for (int n : limits) cout << prefix[n] << "\n";
}const data = require("fs").readFileSync(0, "utf8").split(/\s+/).filter(Boolean).map(Number);
const q = data[0];
const limits = data.slice(1, 1 + q);
const top = Math.max(...limits);
const phi = [];
for (let i = 0; i <= top; i++) phi.push(i);
for (let i = 2; i <= top; i++) {
if (phi[i] === i) {
for (let j = i; j <= top; j += i) phi[j] -= Math.floor(phi[j] / i);
}
}
const prefix = new Array(top + 1).fill(0);
for (let b = 1; b <= top; b++) prefix[b] = prefix[b - 1] + phi[b];
process.stdout.write(limits.map((n) => prefix[n]).join("\n") + "\n");On the sample 3 and 1 5 10, all four programs print 1, 10 and 32, one per line.
The slow twin builds every fraction a/b with exact fractions and counts the different ones. It is slow, and it does not use a sieve or a gcd, so it cannot share a mistake with the fast code.
import random
from fast import distinct_patterns
from slow import distinct_patterns as slow_patterns
for seed in range(1000):
n = random.Random(seed).randint(1, 30)
if distinct_patterns(n) != slow_patterns(n):
print("different at", n)
break
else:
print("all 1000 inputs agree")The run prints all 1000 inputs agree. Start the sum of phi at 2 instead of 1, and the very first random input fails: for 28 it gives 241 instead of 242.
At 1,600 to 1,800 the formula is known, and the work is choosing which table to build and how big it must be. Write the table and its size in one line before you code. Aim for about 30 minutes a problem, and keep 10 for the stress test.
The first two build a table over the divisors: inverses, then smallest prime factors. The last two, rated 1,800, add structure on top of a table: phi with a prefix sum, and inclusion and exclusion over common divisors.
For each problem, write the table, its size and the cost of a query in one line. Then write the slow twin on values up to 30, and stress test.
Checkpoint · Number theory for contests
Q1/5 There are 10^5 shard sizes, each up to 10^6. Why is trial division for every size a poor plan?
Answer: B
The table is built once in about n log log n steps. A size below 10^6 then splits in at most 19 steps.
Q2/5 For p = 11, what is the inverse of 3 modulo 11?
Answer: C
3 × 4 = 12, which is 1 modulo 11. The recurrence gives the same: 3 × inv[2] = 18, which is 7, and 11 - 7 = 4.
Q3/5 How many different fractions a/b with 1 ≤ a ≤ b ≤ 5 are there?
Answer: B
The sum of phi(1) to phi(5) is 1 + 1 + 2 + 2 + 4 = 10. The count 15 includes equal fractions such as 2/4 and 1/2.
Q4/5 A pair-count function subtracts, for each prime, the pairs of loops divisible by it. For the loops 6 and 6 what does it return?
Answer: C
The one pair is subtracted for the prime 2 and again for the prime 3: 1 - 2 = -1. The true answer is 0, because gcd(6, 6) = 6.
Q5/5 Why must the number of pairs among 10^5 routes be stored in a 64-bit integer?
Answer: B
A 32-bit signed integer stops at 2,147,483,647. The sum of phi up to 5 × 10^5 is 75,991,039,676, which is also too large.
Review cards from this lesson.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.