我看隔壁数学系搞的不错,术语极大丰富,各种人话基本消灭,逻辑严谨、体系顺序也受重视,如果加上讲的是 oi 内容,数学课本就是我们理想中的 oi 讲稿。
:::info[英文版/English]
Local Structure of the Integers and Finite Summation of Arithmetic Functions
Conventions
This text rests on ordinary set theory and the constructions of the integers and rational numbers. Finite sets, maps, equivalence relations, finite sequences, induction, and the theorem of finite recursion are taken as established. Real logarithms, integrals, and elementary asymptotic estimates are used only in complexity proofs. Write
When l>r, set [l,r]=\varnothing. An empty sum is 0, and an empty product is 1. The notation [P] denotes the indicator of the proposition P: it is 1 when the proposition holds and 0 otherwise. Unless otherwise specified, divisors are positive and primes are positive primes; moduli are always positive integers, and remainders are always the least nonnegative representatives. The notation p^e\parallel n means p^e\mid n and p^{e+1}\nmid n. Integer square roots and other root expressions used as bounds are interpreted with the explicitly indicated rounding. An unsubscripted \log is the natural logarithm; changing to any fixed base in an asymptotic operation count affects only the constant.
All rings are commutative and have an identity; the particular uses of groups, units, and residue classes are defined in the text. The degenerate case of modulus 1 is allowed. A general coefficient ring is denoted by R, and integers are mapped into R by the canonical unital homomorphism. Division in a ring uses the inverses of units. Ordinary multiplication, pointwise multiplication, and Dirichlet convolution are distinguished throughout; the last is consistently denoted by *. Equalities of formal series mean coefficientwise equality unless convergence conditions are supplied separately.
Computational conventions. Time bounds count elementary arithmetic operations, and storage bounds count integers or ring elements. If integers, addresses, moduli, and intermediate results can be represented exactly in a constant number of machine words, the corresponding additions, subtractions, multiplications, divisions, comparisons, rounding operations, and random accesses are counted as elementary operations; the bit complexity of arbitrary-precision arithmetic is accounted for separately. The costs of operations on ring elements and their storage are specified in each construction. Algorithmic complexity includes binary exponentiation, inversion, modulus factorization, local function evaluation, and preprocessing.
Hash-table lookups are charged at their expected cost; error probabilities and orbit models for randomized algorithms are described in the corresponding chapters.
Within each chapter, definitions, lemmas, propositions, theorems, corollaries, constructions, and examples share one sequence numbered “chapter.item”; equations are numbered separately. Chapters follow the order of mathematical dependence: divisibility and residue-class structures come first, followed by convolution of arithmetic functions, and finally finite representations, sieves, and lattice-point sums. Algorithm names are retained at the corresponding constructions for comparison with the original notes; a page correspondence, editorial corrections, and supplementary sources appear at the end.
Chapter I — Divisibility and Ideals of the Integers
§1 Divisibility and Division with Remainder
Definition 1.1. For a,b\in\mathbf Z, one says that a divides b, and writes a\mid b, if there exists q\in\mathbf Z such that b=aq. For n>0, put
D(n)=\{d\in\mathbf N_{>0}:d\mid n\}.
\tag{1.1}
By definition, every integer divides 0, whereas 0\mid b if and only if b=0. For n>0, the pairing of factors d\mapsto n/d is an involution on D(n).
Proposition 1.2. For integers a,b,c, divisibility is transitive; if a\mid b and a\mid c, then a\mid ub+vc for all u,v\in\mathbf Z; if a\mid b and b\mid a, then |a|=|b|. For t\ne0,
a\mid b\iff ta\mid tb.
\tag{1.2}
Proof. The first two assertions follow by substitution in the definition of divisibility. If a,b are both nonzero, the equalities b=aq and a=br give qr=1, so q,r\in\{1,-1\}; if either is zero, both are zero. The reverse implication in (1.2) uses cancellation for multiplication in the integers. \square
Theorem 1.3 (Division with remainder). Let m>0 and a,d\in\mathbf Z. There is a unique pair of integers (q,r) satisfying
a=qm+r,\qquad d\le r<d+m.
\tag{1.3}
Proof. Taking q=\lfloor(a-d)/m\rfloor and r=a-qm proves existence. If (q',r') is another such pair, then m(q-q')=r'-r and |r'-r|<m; hence both sides are zero. \square
When d=0, the resulting r is denoted by a\bmod m. Any m consecutive integers have distinct remainders, which therefore run through 0,\ldots,m-1: the difference of two of these integers has absolute value less than m, so they can be congruent only if they are equal.
§2 Ideals of the Integers and Greatest Common Divisors
Definition 1.4. An ideal of the ring of integers is a nonempty subset I\subseteq\mathbf Z with the following properties: if x,y\in I, then x-y\in I; if x\in I and t\in\mathbf Z, then tx\in I. For a finite family of integers a_1,\ldots,a_r, put
This is the smallest ideal containing all the a_i. The ideal generated by the empty family is, by convention, \{0\}.
Theorem 1.5. Every ideal of the integers has a unique expression d\mathbf Z, where d\in\mathbf N.
Proof. If I=\{0\}, take d=0. Otherwise, I contains a positive integer; let d be the least such integer. For any a\in I, division with remainder gives a=qd+r with 0\le r<d. Since r\in I, minimality forces r=0. Thus I\subseteq d\mathbf Z; the reverse inclusion follows from the ideal property. If d\mathbf Z=e\mathbf Z, the generators divide one another; since d,e\ge0, one has d=e. \square
Definition 1.6. The greatest common divisor of a finite family of integers is the nonnegative generator of the ideal they generate; it is denoted by \gcd(a_1,\ldots,a_r). Two integers are relatively prime if their greatest common divisor is 1. In particular, \gcd(0,0)=0.
Theorem 1.7 (Bézout). Let d=\gcd(a_1,\ldots,a_r). Then d\mid a_i for every i, and there exist integers u_i such that
d=\sum_{i=1}^r u_i a_i.
\tag{1.5}
Every common divisor divides d. Consequently, unless the family consists entirely of zeros, d is the greatest positive common divisor in the usual order; the equation \sum_i a_i x_i=c has an integer solution if and only if d\mid c.
Proof. The equality (a_1,\ldots,a_r)=d\mathbf Z gives the first two assertions. A common divisor divides every integer linear combination, and hence divides d. The last assertion is equivalent to c\in d\mathbf Z, including the case d=0. \square
If \gcd(a,b)=1 and b\mid ac, then b\mid c. If also a\mid c, then ab\mid c.
Proof. The first equality follows from (a,b)=(b,a-qb), and the second from multiplying the generated ideal by t. Choose ua+vb=1 and multiply by c to obtain b\mid c. If c=at, then b\mid at implies b\mid t, whence ab\mid c. \square
Construction 1.9 (Extended Euclidean algorithm). Apply division with remainder successively to |a|,|b| until the remainder is zero. The last nonzero remainder is \gcd(a,b); if both inputs are initially zero, return 0 directly. If the recursive call has obtained
bx'+(a-qb)y'=d,
\tag{1.7}
return x=y' and y=x'-qy', so that ax+by=d. Finally, adjust the coefficients according to the signs of the original inputs.
Proof. Equation (1.6) preserves the greatest common divisor, and the strictly decreasing nonnegative remainders ensure termination. Back-substitution gives the stated coefficients. Let u>v be consecutive positive remainders. If v\le u/2, a halving has already occurred; otherwise, the next remainder is u-v<u/2. Thus the size is at least halved every two steps, and the number of divisions is O(1+\log(\min(|a|,|b|)+1)). \square
Remark. This bound counts integer divisions; it does not include coefficient sizes or the bit costs of integer multiplication and division. Successively taking greatest common divisors of several integers gives a result independent of the grouping, since the generated ideal is the same.
§3 Primes and Unique Factorization
Definition 1.10. A prime is a positive integer with exactly two positive divisors. An integer greater than 1 that is not prime is called composite. For a prime p and a positive integer n, put
Lemma 1.11. If a prime p divides ab, then p\mid a or p\mid b.
Proof. If p\nmid a, then \gcd(p,a) is a positive divisor of p different from p, and hence equals 1. Apply Proposition 1.8. \square
Theorem 1.12 (Unique factorization). Every n>0 has a unique expression
n=\prod_p p^{\nu_p(n)},
\tag{1.9}
in which only finitely many exponents are nonzero; n=1 corresponds to the empty product.
Proof. Proceed by induction on n. If n>1 is not prime, write n=uv with 1<u,v<n and factor u,v separately to obtain existence. Given two factorizations, any prime factor on the left divides some prime factor on the right by Lemma 1.11, so these factors are equal. Cancel this factor and apply induction to obtain uniqueness. \square
Definition 1.13. The least common multiple of a nonempty finite family of positive integers is its least positive common multiple; it is denoted by \operatorname{lcm}(a_1,\ldots,a_r).
The corresponding minimum and maximum formulas hold for every nonempty finite family of positive integers.
Proof. The divisibility criterion follows directly from unique factorization. Each exponent of a common divisor is at most the corresponding minimum, and these minima do give a common divisor; the argument for common multiples is analogous. Finally, use \min(s,t)+\max(s,t)=s+t. \square
Corollary 1.15. If positive integers a_1,\ldots,a_r are pairwise relatively prime and their product is the kth power of a positive integer, where k>0, then each a_i is the kth power of a positive integer.
Proof. Any prime occurs in at most one a_i. Its exponent in the full product is divisible by k, so its exponent in that a_i is also divisible by k. \square
§4 Congruences and Linear Equations
Definition 1.16. For m>0, integers a,b are congruent modulo m if m\mid a-b; one writes a\equiv b\pmod m. The equivalence class of an integer a is denoted by [a]_m. The set of these classes is denoted by \mathbf Z/m\mathbf Z, with addition and multiplication defined by
Proposition 1.17. Congruence is an equivalence relation. The operations in (1.11) are independent of the representatives and make \mathbf Z/m\mathbf Z a commutative ring with identity. If a positive integer d satisfies d\mid a,b,m, then
a\equiv b\pmod m
\iff a/d\equiv b/d\pmod{m/d}.
\tag{1.12}
For any integer c, let g=\gcd(c,m). Then
ca\equiv cb\pmod m
\iff a\equiv b\pmod{m/g}.
\tag{1.13}
Proof. The equivalence relation and the ring operations follow from the compatibility of divisibility with addition and multiplication. Equation (1.12) is cancellation in the integer equality a-b=tm. Write c=gc' and m=gm', so that \gcd(c',m')=1; Proposition 1.8 gives m'\mid c'(a-b) if and only if m'\mid a-b. \square
Remark. Cancelling a nonunit factor in a congruence generally requires changing the modulus as well. The ring modulo 1 has one element, [0]_1=[1]_1; all integers are congruent modulo 1.
Theorem 1.18 (Linear congruences). Let m>0 and d=\gcd(a,m). The equation
ax\equiv b\pmod m
\tag{1.14}
has a solution if and only if d\mid b. If ua+vm=d and d\mid b, then all integer solutions are
x=u(b/d)+t(m/d),\qquad t\in\mathbf Z.
\tag{1.15}
Consequently, there are exactly d solution classes modulo m.
Proof. The original equation is equivalent to the existence of an integer solution of ax+my=b. Theorem 1.7 therefore gives the solvability criterion and a particular solution. The difference of two solutions satisfies a(x-x_0)\equiv0\pmod m; apply (1.13). A complete residue system of length m contains exactly d representatives spaced by m/d. \square
§5 Combining Congruence Conditions
Theorem 1.19 (Chinese remainder theorem). Let m_1,\ldots,m_r be pairwise relatively prime positive integers, and let M=\prod_i m_i. The map
is a ring isomorphism. In particular, for any prescribed a_i, the system x\equiv a_i\pmod{m_i} has exactly one solution class modulo M.
Proof. Put M_i=M/m_i and use Bézout's theorem to choose u_i such that u_iM_i\equiv1\pmod{m_i}. Then
x=\sum_i a_i u_iM_i
\tag{1.17}
satisfies every equation: in the ith component, the ith term gives a_i and all other terms vanish. If two integers satisfy the same conditions, each m_i divides their difference; pairwise relative primality implies that M divides their difference. The map plainly preserves the ring operations and is therefore an isomorphism. A component with modulus 1 imposes no condition and may be omitted. \square
Theorem 1.20 (Combining two arbitrary moduli). Let M,N>0 and d=\gcd(M,N). The system
x\equiv A\pmod M,\qquad x\equiv B\pmod N
\tag{1.18}
has a solution if and only if d\mid B-A. When it is solvable, choose uM+vN=d and put
so that all solutions are given by x\equiv A+Mt_0\pmod L.
Proof. Write x=A+Mt. The problem becomes Mt\equiv B-A\pmod N. Theorem 1.18 gives the solvability criterion and the unique class of t modulo N/d. Changing t by one period changes x by L, and L=\operatorname{lcm}(M,N). \square
Construction 1.21 (ExCRT). Start with (A,M)=(0,1), and successively combine the current class x\equiv A\pmod M with the next congruence condition by Theorem 1.20. After each step, normalize A to [0,M-1]. If a step is incompatible, the system has no solution; otherwise, the final class is the set of all integer solutions.
Proof. The induction invariant is that the current residue class is exactly the solution set of the equations already processed. Theorem 1.20 preserves this invariant. The empty system has all integers as its solution set, in agreement with the initial state. \square
Remark. The combined modulus is the least common multiple of the moduli already processed. Divide by the greatest common divisor before multiplying, using an integer representation that accommodates the resulting product. If all intermediate moduli are at most L, then r combinations use O(r\log(L+1)) integer divisions; the bit costs of arbitrary-precision integers are counted separately.
§6 Two Existence Problems on Residue Classes
Example 1.22 (Xiaokai's Doubt). Let a,b>1 and \gcd(a,b)=1. The greatest nonnegative integer that cannot be written as ax+by with x,y\in\mathbf N is
ab-a-b.
\tag{1.20}
Proof. The remainders of 0,b,\ldots,(a-1)b modulo a are distinct, so every class contains exactly one of these terms jb. Within that class, the representable nonnegative integers are exactly jb+ta with t\in\mathbf N: if n=ax+by, write y=j+sa with 0\le j<a; then n=jb+a(x+sb)\ge jb. The converse is immediate. Thus the integers in that class below jb are not representable, and the greatest candidate is jb-a. Taking the maximum over all classes gives (a-1)b-a. Since a,b>1 are relatively prime, this number is nonnegative and hence belongs to the required set. \square
Remark. If a=1 or b=1, every nonnegative integer is representable, so there is no greatest nonrepresentable nonnegative integer. Equation (1.20) then gives -1, which can only be used as a separately prescribed sentinel value. If a,b are not relatively prime, infinitely many nonnegative integers are not representable.
Example 1.23 (CF338D, GCD Table). Given positive integers a_1,\ldots,a_k and upper bounds n,Y, determine whether there exist
If this system has no solution, neither does the original problem. Otherwise, all its solutions are y\equiv y_0\pmod L. Take the least positive representative y_*=y_0 if y_0>0, or y_*=L if the normalized representative is y_0=0. The original problem is solvable if and only if
Thus, whenever an original solution exists, x may be replaced by L. Moreover, adding or subtracting L from y preserves all these greatest common divisors. Hence the least positive representative suffices to test both the bound and the equalities. The converse is verified by (x,y)=(L,y_*). \square
Remark. For a contiguous segment of length k within an n\times m table, the boundary condition is y+k-1\le m, so Y=m-k+1; if Y<1, there is no solution. The condition y\le m in the abbreviated slide statement corresponds to Y=m. Computation of L may stop as soon as L>n is established. Test the resulting candidate by the greatest-common-divisor equalities in (1.23).
Chapter II — Finite Operations in Residue Class Rings
§1 Units, Inverses, and Powers
Definition 2.1. A unit of a commutative ring with identity R is an element having a multiplicative inverse. The set of units is denoted by R^\times; it is an abelian group under ring multiplication. For m>0, put
For an element a of any monoid, set a^0=1, including the case of the zero ring and the case a=0 in a ring.
Proposition 2.2. The class [a]_m is a unit if and only if \gcd(a,m)=1. Its inverse, when it exists, is unique; if the extended Euclidean algorithm gives ua+vm=1, the inverse is [u]_m.
Proof. Invertibility is equivalent to solvability of ax\equiv1\pmod m; apply Theorem 1.18. If ax=ay=1, then x=x(ay)=(xa)y=y. \square
Remark. The group U_1 has one element, and \varphi(1)=1. For a prime p, every nonzero residue class is a unit, so \mathbf F_p=\mathbf Z/p\mathbf Z is a field. For a general composite modulus, a nonzero element need not be invertible.
Construction 2.3 (Binary exponentiation). For a monoid element a and e\in\mathbf N, maintain (z,b,t), initially (1,a,e). While t>0, put z\leftarrow zb if t is odd, and then put b\leftarrow b^2 and t\leftarrow\lfloor t/2\rfloor. Return z.
Proof. The invariant is zb^t=a^e. Write t=2q+\epsilon, where \epsilon\in\{0,1\}. After one update, the product is zb^\epsilon(b^2)^q, equal to its previous value. At termination, t=0, so z=a^e. The number of multiplications is O(1+\log(e+1)). \square
Remark. The algorithm requires only associativity and therefore also applies to matrices. Modular multiplication uses exact integer products followed by reduction, or an equivalent implementation without overflow. Exponent 0 gives the identity element, whose normalized representative modulo 1 is still 0.
Construction 2.4 (Batch inversion). Let a_1,\ldots,a_r be units of R. Put P_0=1 and P_i=P_{i-1}a_i. Compute P_r^{-1} once, and then, for i=r down to 1, compute
Proof. Multiplying the two formulas by a_i and P_{i-1}, respectively, gives the identity. The procedure uses one inversion and O(r) multiplications. \square
Proposition 2.5. For a prime p and 1<i<p, put q=\lfloor p/i\rfloor and r=p\bmod i. Then
i^{-1}\equiv-q\,r^{-1}\pmod p.
\tag{2.3}
Thus the inverses of 1,\ldots,p-1 may be computed recursively from 1^{-1}=1.
Proof. Since p=qi+r, one has qi\equiv-r\pmod p. Here 1\le r<i<p because p is prime. Multiplication by i^{-1}r^{-1} gives the result. \square
Remark. This recurrence uses invertibility of nonzero residues modulo a prime. For a composite modulus, even if i is a unit, the remainder m\bmod i may not be a unit; for example, when m=8,i=3, the remainder is 2.
§2 Unit Groups and Reduction of Exponents
Theorem 2.6 (Euler). If \gcd(a,m)=1, then
a^{\varphi(m)}\equiv1\pmod m.
\tag{2.4}
In particular, if p is prime and p\nmid a, then a^{p-1}\equiv1\pmod p and a^{-1}\equiv a^{p-2}\pmod p.
Proof. Multiplication by [a]_m permutes the finite set U_m. Taking the product of all its elements gives
Proof. The units modulo p^\alpha are precisely the residue classes not divisible by p, of which there are p^\alpha-p^{\alpha-1}. The Chinese remainder theorem identifies units modulo m with families of units in the prime-power components, so their cardinalities multiply. \square
Theorem 2.8 (Reduction of exponents for nonunits). Let m>0, a\in\mathbf Z, and e\in\mathbf N. If \gcd(a,m)=1, the exponent may be replaced by e\bmod\varphi(m). For arbitrary a, if e\ge\varphi(m), then
a^e\equiv a^{\varphi(m)+(e\bmod\varphi(m))}\pmod m.
\tag{2.7}
If e<\varphi(m), the original exponent is retained.
Proof. The assertion is automatic for m=1. Consider each full prime-power component p^\alpha\mid m. If p\nmid a, then \varphi(p^\alpha)\mid\varphi(m), and Euler's theorem permits changes of the exponent by multiples of \varphi(m). If p\mid a, then a^t is zero modulo p^\alpha for t\ge\alpha. Moreover,
where the last inequality follows from the inductive inequality 2^{\alpha-1}\ge\alpha. Hence both sides of (2.7) vanish in this component. Combine the componentwise conclusions by the Chinese remainder theorem. The unit case follows directly from Theorem 2.6. \square
Remark. In the noncoprime case, choose the exponent according to the threshold in Theorem 2.8. For example, 2^2\equiv0\pmod4, whereas 2^{2\bmod\varphi(4)}=2^0\equiv1\pmod4. In a recursive computation of a power tower, retain both the exponent modulo \varphi(m) and whether it has reached \varphi(m); treat a zero exponent according to a^0=1.
§3 Local Computation of Binomial Coefficients
Definition 2.9. For n\in\mathbf N and k\in\mathbf Z, let \binom nk be the number of k-element subsets of an n-element set, with value 0 when k<0 or k>n. Thus, in the polynomial ring over the integers,
(1+X)^n=\sum_{k=0}^n\binom nkX^k.
\tag{2.9}
For 0\le k\le n, ordering the elements of the subset and of its complement separately gives the integer identity n!=\binom nk k!(n-k)!.
Lemma 2.10. In a commutative ring of prime characteristic p,
(u+v)^p=u^p+v^p.
\tag{2.10}
Proof. For 0<j<p, the integer identity j!\binom pj=p(p-1)\cdots(p-j+1) implies p\mid j!\binom pj. Since p\nmid j!, Lemma 1.11 gives p\mid\binom pj. Thus all intermediate terms in the binomial expansion vanish. \square
Theorem 2.11 (Lucas). Let p be prime, and let n=\sum_i n_ip^i and k=\sum_i k_ip^i be the base-p expansions, with 0\le n_i,k_i<p. Then
\binom nk\equiv\prod_{i\ge0}\binom{n_i}{k_i}\pmod p.
\tag{2.11}
Proof. Repeated application of Lemma 2.10 in \mathbf F_p[X] gives
(1+X)^n=\prod_i(1+X^{p^i})^{n_i}.
\tag{2.12}
The exponent selected from each factor on the right has the form j_ip^i, where 0\le j_i\le n_i<p. These exponents add without carrying. Hence the only way to obtain X^k is to take j_i=k_i in every position; if k_i>n_i in any position, the coefficient is zero. Comparison of coefficients proves the assertion. \square
Remark. The factorials and inverse factorials of 0,\ldots,p-1 can be precomputed in O(p) time and space, after which each evaluation uses O(1+\log_p(n+1)) digit operations. This method applies when a table of length p can be stored. For n\ge p, the factorial n! is zero modulo p and has no multiplicative inverse.
Theorem 2.12 (Legendre). For a prime p and n\in\mathbf N, let s_p(n) denote the sum of the base-p digits of n. Then
Proof. Each 1\le t\le n contributes \nu_p(t) to the total exponent, namely one for every j\ge1 satisfying p^j\mid t. Interchanging these two finite summations gives the first equality. If n=\sum_i n_ip^i, then
Proposition 2.13. Let t_1+\cdots+t_r=n, where t_i\in\mathbf N. The multinomial coefficient
\frac{n!}{t_1!\cdots t_r!}
\tag{2.15}
is odd if and only if the binary addition of the t_i involves no carries: their sets of binary 1 positions are pairwise disjoint and have union equal to the set of 1 positions of n.
Proof. By Theorem 2.12, its 2-adic valuation is \sum_i s_2(t_i)-s_2(n). Combining two copies of 2^j into one copy of 2^{j+1} decreases the total digit sum by exactly 1. After all carries are performed, the digit sum is s_2(n). Thus the difference is zero if and only if no carry is needed. \square
§4 Prime-Power Moduli and Reduced Factorials
Definition 2.14. Fix a prime p and define positive integers
U_p(n)=\frac{n!}{p^{\nu_p(n!)}},\qquad
G_p(n)=\prod_{\substack{1\le i\le n\\p\nmid i}}i,
\quad n\in\mathbf N.
\tag{2.16}
Both are 1 when n=0, and both are relatively prime to p.
Proposition 2.15. The following integer identity holds:
U_p(n)=G_p(n)U_p(\lfloor n/p\rfloor).
\tag{2.17}
Proof. Partition the factors of n! into those not divisible by p and the factors p,2p,\ldots,\lfloor n/p\rfloor p. Removing one factor p from each factor in the latter part leaves \lfloor n/p\rfloor!. Removing all its remaining factors p gives exactly U_p(\lfloor n/p\rfloor). \square
Construction 2.16. Let q=p^\alpha, where \alpha\ge1. Precompute
Substituting this formula into (2.17) gives a recursive computation of U_p(n)\bmod q.
Proof. In every complete interval of length q, the factors not divisible by p correspond modulo q to those in the first block. The final partial block corresponds to 1,\ldots,r. The recursive argument is divided by p at each step and therefore eventually reaches 0. \square
Theorem 2.17 (Binomial coefficients modulo a prime power). Let 0\le k\le n and q=p^\alpha. Put
e=\nu_p(n!)-\nu_p(k!)-\nu_p((n-k)!).
\tag{2.20}
If e\ge\alpha, then \binom nk\equiv0\pmod q; otherwise,
Proof. Since the binomial coefficient is an integer, e\ge0. Separate the powers of p in the three factorials and cancel the common factors p in the integers to obtain
\binom nk\,U_p(k)U_p(n-k)=p^eU_p(n).
\tag{2.22}
The two U_p factors on the left are relatively prime to q and are therefore invertible modulo q, giving (2.21). If e\ge\alpha, the right-hand side is zero. \square
Construction 2.18 (Binomial coefficients for an arbitrary modulus). For M>1, first obtain the factorization M=\prod_i p_i^{\alpha_i}, compute each prime-power component by Theorem 2.17, and combine them by the Chinese remainder theorem. For M=1, return the normalized remainder 0 directly. This construction is commonly called ex-Lucas.
Remark. The cost of prime factorization is counted separately. For a component q, the table (2.18) requires O(q) time and space. A direct implementation using binary exponentiation at each recursive level computes one corresponding reduced factorial in O((1+\log_p(n+1))(1+\log(n+1))) modular multiplications. If a table of length q exceeds available storage, another method for computing G_p may be used. To evaluate the binomial coefficient, first separate the prime powers in the integers, then invert the units in the denominator.
§5 Parity Counting and Binary Recurrences
Example 2.19 (gym102586E). Given distinct nonnegative integers A_1,\ldots,A_k, count modulo 2 the ordered sequences of length n whose entries are chosen from these k values and whose sum is S. In \mathbf F_2[X], put
P(X)=\sum_{j=1}^kX^{A_j}.
\tag{2.23}
The required answer is [X^S]P(X)^n. If n=\sum_{i=0}^{\ell-1}n_i2^i, then
P(X)^n=\prod_{i:n_i=1}P(X^{2^i}).
\tag{2.24}
Proof. In the expansion of P(X)^n, each ordered choice contributes exactly one monomial, whose exponent is the sum. In characteristic 2, Lemma 2.10 gives P(X)^{2^i}=P(X^{2^i}), yielding (2.24). Proposition 2.13 gives another interpretation: each binary 1 position of n is assigned to exactly one occurrence count; multinomial coefficients involving carries are all even. \square
Construction 2.20 (Carry states). Let A=\max_j A_j, let n>0, and let \ell be the binary length of n. Denote the ith binary digit of S by s_i. Define f_i(c)\in\mathbf F_2 to be the parity of the number of choices satisfying
among the lowest i positions, where j_t is chosen only when n_t=1. Initially f_0(0)=1 and all other entries are zero. If n_i=0, take only a=0 at each state; if n_i=1, take a=A_1,\ldots,A_k successively. Only when c+a\equiv s_i\pmod2 perform the update
The final answer is f_\ell(\lfloor S/2^\ell\rfloor); entries outside the array range are treated as zero.
Proof. Add n_i2^ia to the left-hand side of (2.25) and use S\bmod2^{i+1}=(S\bmod2^i)+s_i2^i to obtain the update. Once the parity condition is satisfied, the new carry is nonnegative. If 0\le c\le A and 0\le a\le A, then 0\le(c+a-s_i)/2\le A, so all reachable states lie in [0,A]. After all digits of n have been processed, the full sum equals S if and only if the remaining carry is \lfloor S/2^\ell\rfloor. \square
Remark. For n=0, there is exactly one empty sequence, so the answer is [S=0]. A direct implementation uses O((k+1)(A+1)\ell) Boolean operations and O(A+1) space. The states may be stored as a bitset: when n_i=1, first take the exclusive or of the shifts by all A_j, then retain and compress the odd or even positions according to s_i. The intermediate indices extend at most to 2A. If a machine word contains w bits, the shifts and exclusive-or operations use O(k\lceil(A+1)/w\rceil\ell) word operations; ordinary compression requires an additional O((A+1)\ell) time.
Chapter III — Cyclic Subgroups and Integer Factorization
§1 Orders and Primitive Roots
Definition 3.1. Let G be a finite group and g\in G. The order of g is the least positive integer d such that g^d=1, denoted by \operatorname{ord}(g). The subgroup consisting of all integer powers of g is denoted by \langle g\rangle. If G=\langle g\rangle, then G is called cyclic and g a generator. A primitive root modulo m is a generator of U_m.
Proposition 3.2. Every element of a finite group has an order. If its order is d, then
Proof. Finiteness implies that two terms of 1,g,g^2,\ldots are equal; cancellation gives a positive power equal to 1. Write any integer t as qd+r with 0\le r<d. Then g^t=1 if and only if r=0, which gives (3.1). The left cosets of \langle g\rangle are either equal or disjoint, and left multiplication gives a bijection between each coset and the subgroup. Thus these sets of size d partition G, and d\mid|G|. \square
Lemma 3.3. A nonzero polynomial of degree r over a field has at most r roots. If elements u,v of an abelian group have relatively prime orders a,b, respectively, then uv has order ab.
Proof. If c is a root of a polynomial, division by X-c has zero remainder. Induction on the degree gives the root bound. For the second assertion, (uv)^{ab}=1. If (uv)^t=1, then u^t=v^{-t} belongs to both \langle u\rangle and \langle v\rangle; its order divides both a,b, and hence is 1. Therefore a\mid t and b\mid t, so ab\mid t. \square
Theorem 3.4. Every finite subgroup of the multiplicative group of a field is cyclic. In particular, a primitive root modulo p exists for every prime p.
Proof. Let G be the finite subgroup, and let e be the least common multiple of all element orders. For each q^\alpha\Vert e, choose an element whose order contains the full factor q^\alpha; raising it to a suitable integer power gives an element of order exactly q^\alpha. By Lemma 3.3, multiplying these elements of pairwise relatively prime orders gives an element of order e, so e\le|G|. On the other hand, every x\in G satisfies x^e=1, and the root bound over a field gives |G|\le e. Thus e=|G|, and the constructed element generates G. \square
Remark. In the preceding proof, if g has order d, then g^t has order d/\gcd(d,t); this follows directly by finding the least positive solution of d\mid ts. The unit group for a composite modulus need not be cyclic. For example, all four units modulo 8 have square 1, so there is no element of order 4.
Proposition 3.5. Let g\in G. Suppose g^D=1 and the prime divisors of D are known. Then \operatorname{ord}(g)=D if and only if
g^{D/q}\ne1\quad\text{for every prime }q\mid D.
\tag{3.2}
Proof. The order d divides D. If d<D, then D/d>1; choose a prime q\mid D/d. It follows that d\mid D/q, so g^{D/q}=1. The converse follows immediately from d=D. \square
Construction 3.6. Given a unit g\in U_m and the prime factorization of \varphi(m), start with D=\varphi(m). For each prime q\mid D, as long as g^{D/q}=1, put D\leftarrow D/q. The final D is the order of g.
Proof. Each change preserves the condition that the true order divides D. At termination, every test in (3.2) holds, so D is the true order. \square
§2 Discrete Logarithms and Block Search
Definition 3.7. Given g,h in a finite group G, the discrete logarithm problem asks for x\in\mathbf N such that g^x=h. It is solvable if and only if h\in\langle g\rangle; when solvable, all integer solutions form one class modulo \operatorname{ord}(g).
Construction 3.8 (BSGS). Suppose \operatorname{ord}(g)\le N is known, with N\ge1, and put B=\lceil\sqrt N\rceil. Store
g^j\longmapsto j\quad(0\le j<B),
\tag{3.3}
retaining only the smallest j when a key occurs more than once. For i=0,1,\ldots,\lfloor(N-1)/B\rfloor in this order, look up
h(g^{-B})^i.
\tag{3.4}
If a value j is found and iB+j<N, return x=iB+j. If the search ends without finding one, there is no solution.
Proof. Every 0\le x<N has a unique expression iB+j with 0\le j<B. The equality g^x=h is equivalent to g^j=h(g^{-B})^i. Whenever the problem is solvable, it has a solution 0\le x<\operatorname{ord}(g)\le N, so the search is exhaustive. Blocks are examined in increasing order of i, and the smallest j is returned within each block. Thus the first valid candidate is the least nonnegative solution. \square
Remark. With a hash table supporting expected constant-time lookup, the number of group operations and the expected lookup cost are both O(\sqrt N); space is O(\sqrt N), with one additional inversion. If a comparison tree or binary search on a sorted table is used, the corresponding logarithmic factors must be included. For units modulo m, one may take N=m without first factoring m; a smaller known upper bound for the order permits a smaller table. If the target is not a unit and the base is a unit, the equation has no solution.
Construction 3.9 (A table for bounded powers of a fixed base). Suppose powers of a fixed g are required repeatedly, with all exponents satisfying 0\le e<K. Put B=\lceil\sqrt K\rceil, and precompute g^j and g^{iB} for 0\le j<B and 0\le i\le\lfloor(K-1)/B\rfloor, respectively. For a query, write e=iB+j and return the product of the two table entries.
Proof. Associativity gives g^{iB+j}=g^{iB}g^j. The two tables are constructed by successive multiplication by g and g^B, respectively. Preprocessing and space are O(\sqrt K), and each query requires one multiplication. \square
§3 Reduction for a Nonunit Base
Construction 3.10 (exBSGS). Given m>0 and integers a,b, find the least nonnegative solution of a^x\equiv b\pmod m. Maintain an integer t, a positive integer M, and normalized representatives B,C modulo M, initially
t=0,\qquad M=m,\qquad B=b\bmod m,\qquad C=1\bmod m.
\tag{3.5}
At each iteration, perform the following steps in order.
If B=C, return t.
Put g=\gcd(a,M). If g=1, solve a^y\equiv BC^{-1}\pmod M by BSGS; return t+y if a solution exists, and otherwise report that there is no solution.
If g>1 and g\nmid B, report that there is no solution.
and continue. The right-hand sides of (3.6) use the variables before the update; finally normalize B' modulo M'.
Proof. Maintain three induction invariants: all x<t have been excluded; C is a unit modulo M; and, for every x\ge t, the original equation is equivalent to
Ca^{x-t}\equiv B\pmod M.
\tag{3.7}
They plainly hold initially. The first step tests exactly x=t. If it fails, only x-t\ge1 remains to be considered. If g\nmid B, the left-hand side is divisible by g and the right-hand side is not, so there is no solution. If g\mid B, cancel one factor g by (1.12) to obtain
C(a/g)a^{x-t-1}\equiv B/g\pmod{M/g},
\tag{3.8}
which is precisely the updated condition. Since \gcd(a/g,M/g)=1 and the old C remains a unit modulo M/g, the new C' is also a unit. If g=1, cancel C and apply BSGS; its least solution plus t is the least solution of the original equation. Each reduction at least halves M, so the procedure terminates. \square
Remark. When m=1, the initial values already satisfy B=C=0, giving x=0. When a=0, first test exponent 0 according to the convention 0^0=1; thereafter, x=1 is possible only when the target remainder is 0. At each iteration, multiply the accumulated coefficient by the current a/g. There are at most O(\log(m+1)) reductions. With the direct Euclidean cost, this stage uses O(\log^2(m+1)) integer divisions, followed by O(\sqrt m) modular multiplications and expected hash-table operations for BSGS.
§4 Two Exponential Equations
Example 3.11 (P4884). Given a prime m\ge7 and 0<k<m, find the least positive integer n such that the decimal repunit satisfies
1+10+\cdots+10^{n-1}\equiv k\pmod m.
\tag{3.9}
The integer identity 9(1+10+\cdots+10^{n-1})=10^n-1, together with invertibility of 9 modulo m, makes the original condition equivalent to
10^n\equiv9k+1\pmod m.
\tag{3.10}
Since m\ne2,5, the base 10 is a unit and BSGS applies. There is no solution if the target is zero, or if it does not belong to \langle10\rangle.
Proof. Multiplication by the unit 9 gives the equivalence of the two congruences. Moreover, 0<k<m and m\ne3 imply 9k+1\not\equiv1\pmod m. Hence the least nonnegative solution of (3.10), if it exists, is already positive. \square
Remark. For more general inputs, if the target is 1, the least nonnegative solution is 0 and the least positive solution is the order of the base. Alternatively, write n=t+1 and find the least nonnegative t satisfying 10^t\equiv(9k+1)10^{-1}. When the modulus has a common factor with 9, multiplication of (3.9) by 9 gives a necessary condition; test the resulting candidates in the original congruence.
Example 3.12 (CF1106F). Let p=998244353. Given b_1,\ldots,b_k, suppose a sequence in \mathbf F_p^\times satisfies
Given n>k and m\in\mathbf F_p^\times, find f_k for which f_n=m. Choose the primitive root g=3 and write f_i=g^{z_i}. The exponents belong to \mathbf Z/(p-1)\mathbf Z and satisfy
z_i=\sum_{j=1}^k b_jz_{i-j}\pmod{p-1}.
\tag{3.12}
Let T be the k\times k matrix whose first row is (b_1,\ldots,b_k), whose subdiagonal entries are 1, and whose remaining entries are 0. Then
Proof. A primitive root makes z\mapsto g^z an isomorphism from the additive group \mathbf Z/(p-1)\mathbf Z to the multiplicative group \mathbf F_p^\times. Thus products correspond to sums, and powers to integer multiples. The matrix implements (3.12) at each step; among the initial exponents, only z_k can be nonzero, yielding (3.14). The solution classes of the linear congruence are distinct, and injectivity of the primitive-root parametrization makes the d values in (3.15) distinct as well. \square
Remark. Primality of the given constant is used as a known property of the problem; p-1=2^{23}\cdot7\cdot17. Binary exponentiation verifies
none of which equals 1, so Proposition 3.5 proves that 3 is a primitive root. Matrix operations are performed modulo the composite integer p-1, and (3.14) is solved by Theorem 1.18. Naive matrix multiplication and BSGS together use O(k^3\log(n+1)+\sqrt p) basic arithmetic and expected lookup operations. If A=0, the solvability condition is exactly B=0, and all p-1 nonzero initial values are then possible.
§5 Primality Testing
Lemma 3.13. In \mathbf F_p, the only possible solutions of x^2=1 are x=1 and x=-1.
Proof. One has (x-1)(x+1)=0, and a field has no zero divisors. For p=2, the two expressions denote the same element. \square
Definition 3.14. Let n>2 be odd, and write uniquely n-1=2^s d, where d is odd and s\ge1. For an integer a, if
a^d\equiv1\pmod n
\quad\text{or}\quad
a^{2^rd}\equiv-1\pmod n
\text{ for some }0\le r<s,
\tag{3.17}
then n is said to pass the strong pseudoprime test to base a.
Proposition 3.15. If n is an odd prime and n\nmid a, then it passes the test (3.17).
Proof. Fermat's theorem gives a^{2^sd}=1. Consider the chain of squares a^d,a^{2d},\ldots,a^{2^sd}. If the first term is not 1, take the first position where 1 occurs. The preceding term is a square root of 1 different from 1, and hence is -1 by Lemma 3.13; its index is less than s. \square
Construction 3.16 (Miller–Rabin). For the integer n to be tested, first reject n<2, accept n=2, and reject even integers greater than 2. For each chosen base a, normalize its representative modulo n; if the selection rule ensures 1\le a<n, it can be tested directly. If 1<\gcd(a,n)<n, a witness to compositeness has been found. Otherwise, compute v=a^d\bmod n. If v=1 or v=-1, the round passes. In all other cases, square at most s-1 more times; pass if -1 occurs, and declare the input composite if it never occurs.
Proof. This procedure tests exactly (3.17). Proposition 3.15 shows that a valid base never causes a prime to be declared composite. If repeated squaring produces 1 from an element other than \pm1, Lemma 3.13 itself supplies a witness to compositeness. \square
Remark. One round requires O(\log n) modular multiplications. Rabin's counting theorem for strong pseudoprimes states that, for every odd composite n, at most one quarter of the bases in 1,\ldots,n-1 pass (3.17); see M. O. Rabin, Probabilistic Algorithm for Testing Primality, 1980, Theorem 1. Consequently, for t independently and uniformly selected bases, the probability that a fixed composite passes all rounds is at most 4^{-t}. This probability is calculated for a fixed composite and random bases.
A further classical result gives a deterministic range: for 2\le n<2^{64}, testing the bases
2,3,5,7,11,13,17,19,23,29,31,37
\tag{3.18}
in succession suffices to determine primality. This follows because the least integer that is a strong pseudoprime to all twelve prime bases is 318665857834031151167461>2^{64}; see J. Sorenson and J. Webster, Strong Pseudoprimes to Twelve Prime Bases, Theorem 1.1. An implementation may first handle inputs at most 37, after which all these bases lie in [1,n-1]; alternatively, reduce the bases and skip zero remainders. Modular multiplication for unsigned 64-bit inputs uses a wider product representation or a dedicated modular-multiplication implementation.
§6 Extracting Factors from Collisions
Construction 3.17 (One Pollard–Rho attempt). For an odd composite n, choose an integer c and an initial value x_0, and put, in \mathbf Z/n\mathbf Z,
F(x)=x^2+c.
\tag{3.19}
Starting with x=y=x_0, repeatedly put x\leftarrow F(x) and y\leftarrow F(F(y)), and compute
d=\gcd(x-y,n).
\tag{3.20}
If d=1, continue; if 1<d<n, return d; if d=n, the attempt has failed, so choose new parameters and retry.
Proposition 3.18. Every value returned by Construction 3.17 is a nontrivial factor of n. If a prime divisor p\mid n satisfies x\equiv y\pmod p, then p\mid d.
Proof. The first assertion follows from the definition of the greatest common divisor and the return condition. The second holds because p divides both x-y and n. \square
Remark. The nontrivial factor returned may be prime or composite. The algorithm iterates modulo the known integer n to seek collisions modulo an unknown prime divisor p. Since F is an integer polynomial, reduction of its orbit modulo n to modulo p gives an orbit of the same polynomial. The slow and fast pointers detect cycles in the orbit of a map on a finite set. If they coincide modulo n, then (3.20) gives n, and the attempt is treated as unsuccessful.
Construction 3.19 (Recursive factorization). For n>0, return the empty family if n=1. If the primality test confirms that n is prime, return n. Otherwise, extract a factor d, factor d and n/d separately, and combine their prime factors with multiplicities. Factors 2 may first be removed directly.
Proof. Provided each extracted factor satisfies 1<d<n, both subproblems are strictly smaller. Inductively, the product of the returned factors is n. When all leaves are indeed prime, unique factorization ensures that the output is correct and that the multiplicities are unique. \square
Remark. In a model approximating the orbit modulo p by a random mapping, the birthday-collision heuristic predicts a collision after about O(\sqrt p) iterations. If p is the least prime divisor of the composite integer n, then p\le\sqrt n, giving a heuristic iteration scale of O(n^{1/4}). This approximation replaces the actual quadratic-polynomial family by uniformly random mappings. The integer divisions and bit costs of the greatest common divisor computed at each iteration are counted separately. Degenerate parameters lead to new choices of c,x_0; one may also impose an iteration limit on each attempt.
With a Miller–Rabin base set having a deterministic input range, the recursive stopping criterion is deterministic within that range. With random bases, errors in primality testing can propagate to the final factorization. Extracted factors can be checked by exact division; verification of a complete prime factorization checks both the product and the primality of each factor.
Construction 3.20 (Batch greatest common divisors). Suppose a collision search produces consecutive differences \Delta_1,\ldots,\Delta_b. First compute
If d=1, the block yields no factor, so proceed to the next block. If 1<d<n, return d directly. If d=n, return to the start of this block, regenerate the \Delta_j, and compute d_j=\gcd(\Delta_j,n) one at a time; return as soon as 1<d_j<n. If the entire block yields no nontrivial factor, the current parameters have failed, so restart.
Proof. An integer product is relatively prime to n if and only if every factor is relatively prime to n: the forward implication follows because each factor divides the product, and the reverse follows from the prime-divisor criterion. Thus skipping a block with d=1 loses no factor. If 1<d<n, then d itself is a valid factor, whether it comes from one difference or several. If d=n, it does not follow that every difference has greatest common divisor n with n. For example, with n=15 and differences 3,5, the reduced product is zero, while each difference yields a factor. Replaying the block individually recovers factors merged by the product. \square
Remark. Reset Q to 1 for each block. The orbit state at the start of the block and its length suffice for replay. Batching normally uses one greatest-common-divisor call per b differences, with additional calls during replay after failure. Reducing the product modulo n at each step preserves the greatest common divisor in (3.21). A zero difference makes the batch product zero and triggers replay.
Construction 3.21 (Brent's segmented orbit). Fix F(x)=x^2+c\pmod n and a maximum block length b\ge1. Put y=x_0 and r=1. One outer iteration is as follows.
Save x=y, then advance y by r consecutive steps.
Over the next r steps, produce a difference x-y after each advance. Group at most b steps into each block and test it by Construction 3.20. Save the start of each block and its actual number of steps for replay.
Return if a nontrivial factor is found; restart if the current parameters are declared unsuccessful. Otherwise, put r\leftarrow2r and repeat the outer iteration.
An advance means the assignment y\leftarrow F(y). Every difference and product may immediately be normalized modulo n.
Proposition 3.22. Every return from Construction 3.21 gives a valid factorization. For any p\mid n, suppose the orbit modulo p has a preperiod of length \mu and a cycle of length \lambda. If the fixed reference point x of a segment is already in the cycle and r\ge\lambda, then at least one difference produced in that segment is divisible by p.
Proof. Correctness of the returned factor follows from Construction 3.20. Once the fixed reference point x lies in the cycle, any subsequent \lambda consecutive orbit points include the residue class of x modulo p. The segment tests r\ge\lambda consecutive points, so at least one collision modulo p occurs. As r doubles, the orbit index of the reference point increases and eventually exceeds \mu; provided no restart occurs, one eventually also has r\ge\lambda. \square
Remark. Simultaneous collisions modulo several prime factors, or an orbit that closes too early modulo n, may yield d=n, in which case the search restarts. Brent's segmentation keeps the reference point unchanged throughout a segment, facilitating batch products and replay; it changes constants and the frequency of greatest-common-divisor calls, while its iteration scale is still estimated heuristically by the preceding random model. A returned factor may contain only part of a prime-factor multiplicity; recursively factoring the remaining quotient recovers the rest.
Chapter IV — Arithmetic Functions and Convolution
§1 Algebra Indexed by Multiplication of Positive Integers
Throughout this chapter, R is a commutative ring with identity. Integer coefficients are interpreted through the unique unital ring homomorphism \mathbf Z\to R; unless otherwise stated, all divisors are positive. Division in a ring means only multiplication by an inverse known to exist.
Definition 4.1. An arithmetic function over R is a map f:\mathbf N_{>0}\to R. Let \mathcal A_R denote the set of all such functions. Define pointwise addition and Dirichlet convolution on this set by
Put \varepsilon(1)=1_R and \varepsilon(n)=0_R for n>1. Pointwise multiplication is denoted separately by fg; it is a different operation from f*g.
Proposition 4.2. Under pointwise addition and convolution, \mathcal A_R is a commutative ring with identity, whose multiplicative identity is \varepsilon.
Proof. Every positive integer has only finitely many divisors, so the sums in the definition exist. Commutativity follows from (a,b)\mapsto(b,a). Associativity follows from two groupings of the same finite sum:
Distributivity follows term by term from distributivity in R. Finally, convolution with \varepsilon leaves only the term with a=1 or b=1. \square
Theorem 4.3. A function f\in\mathcal A_R is invertible under convolution if and only if f(1) is a unit of R. In that case its inverse g=f^{*-1} is unique and is determined by the recurrence
Proof. If f*g=\varepsilon, evaluation at 1 gives f(1)g(1)=1_R, proving necessity. Conversely, n/d<n in (4.3), so g can be defined in increasing order of n. Substitution into the convolution gives f*g=\varepsilon. Uniqueness of the inverse follows from associativity. \square
In the ring of integer-valued arithmetic functions, the condition is f(1)=\pm1; in the residue class ring modulo M, it is \gcd(f(1),M)=1.
§2 Multiplicativity and Local Data at Prime Powers
Definition 4.4. A function f is multiplicative if f(1)=1_R and f(ab)=f(a)f(b) for coprime positive integers a,b. The function f is completely multiplicative if this equality holds for all positive integers a,b.
When R is nonzero, the requirement f(1)=1_R excludes the zero function and makes the empty product agree with the value at 1. In a ring with zero divisors, one cannot derive this condition by arbitrarily cancelling a nonzero function value.
Proposition 4.5. A multiplicative function is uniquely determined by its values at all prime powers. More precisely, given any family c_{p,e}\in R, where p ranges over the primes and e\ge1, there exists a unique multiplicative function satisfying f(p^e)=c_{p,e}, and
f(n)=\prod_{p\mid n}c_{p,\nu_p(n)}.
\tag{4.4}
It is completely multiplicative if and only if c_{p,e}=c_{p,1}^{\,e} for all p,e.
Proof. The fundamental theorem of arithmetic expresses n uniquely as a product of pairwise coprime prime powers. Thus (4.4) is necessary, and the formula directly defines a multiplicative function. Complete multiplicativity allows one to remove a factor p repeatedly. Conversely, additivity of prime exponents ensures that function values multiply when any two integers are multiplied. \square
Proposition 4.6. The pointwise product, Dirichlet convolution, and convolution inverse of multiplicative functions are multiplicative.
Proof. The assertion for pointwise products follows directly from the definition. If \gcd(m,n)=1, every divisor of mn is uniquely of the form ab, where a\mid m and b\mid n. Hence
For the inverse, prescribe g(p^e) by (4.3) for each prime p, then extend these values to a multiplicative function by Proposition 4.5. The convolution f*g is multiplicative, takes the value 1_R at 1, and takes the value 0_R at every positive power of a prime. It therefore equals \varepsilon. \square
If f is multiplicative, its Bell series jointly determine f; checking prime powers suffices to verify equality of two multiplicative functions.
Proof. The divisors of p^e are precisely 1,p,\ldots,p^e, so the coefficient of X^e on either side is \sum_{j=0}^ef(p^j)g(p^{e-j}). The last assertion follows from Proposition 4.5. \square
For a general arithmetic function, the prime-power data and other values such as f(6) may be prescribed independently.
Write \operatorname{id}=\operatorname{id}_1 and \tau=\sigma_0. Define the integer-valued functions \varphi and \mu by
\varphi(n)=|\{a\in[1,n]:\gcd(a,n)=1\}|,
\qquad
\mu(n)=
\begin{cases}
(-1)^r,&n\text{ is a product of }r\text{ distinct primes},\\
0,&\text{the square of some prime divides }n.
\end{cases}
\tag{4.9}
The empty-product convention gives \varphi(1)=\mu(1)=1. Mapping these integer values into R gives the R-valued functions used in this chapter.
The functions \mathbf1, \operatorname{id}_k, and \varepsilon are completely multiplicative; \mu is multiplicative, but in general is not completely multiplicative. By definition, \sigma_k=\operatorname{id}_k*\mathbf1. Hence \sigma_k is multiplicative, and
The two formulas in (4.10) give sums of powers of divisors and divisor counts, respectively. Finite geometric sums are valid over any R; a quotient involving p^k-1 is evaluated by exact integer division, or by multiplication by the inverse when the denominator is a unit of R.
The last expression is first interpreted in the rational numbers; its value is an integer. The function \varphi is multiplicative.
Proof. Classify a\in[1,n] by d=n/\gcd(a,n). Writing a=(n/d)b gives b\in[1,d] and \gcd(b,d)=1, so the class indexed by d has \varphi(d) elements. This proves the convolution identity. Among the integers in the interval for a prime power, those not coprime to p^e are exactly the multiples of p, of which there are p^{e-1}. When m,n are coprime, the Chinese remainder theorem gives a bijection between the invertible residue classes modulo mn and the product of the sets of invertible residue classes modulo m,n, respectively. Thus \varphi(mn)=\varphi(m)\varphi(n). The product formula now follows from the prime-power formula. \square
Proof. If n has r distinct prime factors, the nonzero terms correspond precisely to subsets of these prime factors, and their sum is (1-1)^r. For n=1, only the empty subset occurs, contributing 1. Substitute n=\gcd(a,b) to obtain the last equality. \square
Theorem 4.12 (Divisor inversion). For any f,g\in\mathcal A_R, the following two identities are equivalent:
Proof. The first identity is g=f*\mathbf1. Convolve both sides with \mu, and use associativity and (4.12) to obtain the second. The reverse implication is the same. \square
Inversion does not require f,g to be multiplicative. Multiplicativity permits reconstruction from local data, whereas inversion is an invertible operation in the convolution ring; the two have different roles.
Theorem 4.13 (Finite inversion over multiples). Fix N\ge1, and let f,g:[1,N]\to R. The following two identities are equivalent:
The two linear transformations commute, since both compositions group terms by the product jk. The reverse implication therefore holds as well. \square
A finite truncation or finite support makes the sums over multiples finite, so that (4.14) is defined over any coefficient ring.
Proposition 4.14 (Completely multiplicative weights). If t is completely multiplicative, the map T_t(f)=tf preserves addition, convolution, and the convolution identity. In particular,
Proof. When ab=n, one has t(a)t(b)=t(n), which can be taken outside the finite sum. Then take f=\mathbf1 and g=\mu. \square
No invertibility of the individual values t(n) is required. If t is merely multiplicative, a,b need not be coprime, and the first step is invalid.
Theorem 4.15 (Weighted inversion of sums with floor arguments). Let t be completely multiplicative, and let F,G:\mathbf N\to R satisfy F(0)=G(0)=0. Then
Proof. For positive integers i,j, one has \lfloor\lfloor n/i\rfloor/j\rfloor=\lfloor n/(ij)\rfloor. Indeed, for an integer q, the inequality qj\le\lfloor n/i\rfloor is equivalent to qij\le n. Consequently, the composition of the two summation operators with floor arguments is the operator with coefficients t*(\mu t). By (4.16), this composition is the identity operator. \square
Here F,G may be arbitrary sequences; multiplicativity is unnecessary. Taking prefix sums of a convolution identity naturally leads to this form of inversion.
§4 Formal Dirichlet Generating Functions
Definition 4.16. Introduce formal symbols \mathsf e_n for n\ge1, with the rule \mathsf e_a\mathsf e_b=\mathsf e_{ab}. A formal Dirichlet series is an expression
Addition is defined term by term, and multiplication by the preceding rule. One may also write n^{-s} for \mathsf e_n; in this section, s is only a formal notation indicating multiplication of indices.
The coefficient of a fixed \mathsf e_n involves only finitely many factorizations of n. Thus multiplication requires no convergence condition, and
Introduce a variable X_p for each prime p, and put \mathsf e_n=\prod_pX_p^{\nu_p(n)}. Each monomial involves only finitely many variables; in the product of two formal sums, any prescribed monomial admits only finitely many decompositions. In this precise formal sense, convolution may also be regarded as multivariate multiplication in coordinates given by prime exponents.
Theorem 4.17 (Formal Euler product). Suppose f(1)=1_R. Then f is multiplicative if and only if the following identity holds coefficient by coefficient:
Proof. The coefficient of \mathsf e_n on the right is \prod_{p\mid n}f(p^{\nu_p(n)}). Except for the prime factors of n, every factor must contribute its constant term f(1)=1_R. Thus only finitely many choices are involved in this coefficient. Compare coefficients and apply Proposition 4.5. \square
These denominators all have constant term 1_R and hence are invertible in R[[X]]. For complex s, an analytic interpretation of these formal series requires convergence and a valid interchange of sums.
§5 Prefix Transforms on the Divisibility Order
Definition 4.18. For f:[1,N]\to R, define the divisor zeta transform and the multiple zeta transform by
The partial order here is divisibility. Prime exponents give its coordinates: a\mid b if and only if \nu_p(a)\le \nu_p(b) for every prime. The two transforms are therefore finite downward and upward accumulations, respectively, in these coordinates.
Construction 4.19. Suppose the primes not exceeding N are known. Initialize A[n]=f(n). Enumerate the primes p\le N one at a time; for each p, in the increasing order i=1,2,\ldots,\lfloor N/p\rfloor, perform
A[ip]\leftarrow A[ip]+A[i].
\tag{4.23}
After all operations, A=Z_\downarrow f. To recover the original array, enumerate the primes in reverse order and, for each p, perform A[ip]\leftarrow A[ip]-A[i] in the order i=\lfloor N/p\rfloor,\ldots,1.
Proof. Fix p and write each index uniquely as mp^e, where p\nmid m. Increasing i performs a one-dimensional prefix sum along each chain
$$
A[n]=\sum_{\substack{d\mid n\\n/d\text{ has all its prime factors in }P}}f(d).
\tag{4.24}
$$
After all primes have been processed, this is the required result. Recovery replaces every addition assignment by subtraction in reverse order, undoing all operations one by one. $\square
The inverse transform implements convolution with \mu directly through adjacent differences along the chains; the specified traversal direction propagates contributions through the prime powers in dependency order.
Construction 4.20. For the transform over multiples, again initialize A=f. For each prime p, in the order i=\lfloor N/p\rfloor,\ldots,1, perform
A[i]\leftarrow A[i]+A[ip].
\tag{4.25}
The result is Z_\uparrow f. For the inverse, enumerate the primes in reverse order and, for each prime, perform A[i]\leftarrow A[i]-A[ip] in increasing order of i.
Proof. Again decompose the indices into chains mp^e, now taking suffix sums along each chain. By induction on the processed primes, A[n] is the sum of f(m) over all n\mid m\le N such that every prime factor of m/n belongs to the processed set. Correctness of the inverse follows by undoing the operations one by one. \square
ring additions or subtractions and use O(N) storage. The bound for the sum of reciprocals of primes will be proved in Proposition 6.3. Enumerating all multiples of every integer directly requires \sum_{d\le N}\lfloor N/d\rfloor=O(N\log(N+1)) operations. The algorithm accumulates along the prime coordinates of the divisibility relation one coordinate at a time and applies to arbitrary input arrays.
Chapter V — Summation over Finite Hyperbolic Regions
§1 Quotient-Value Sets and Their Closure
In this chapter, summation indices range over finite sets. Floors, comparisons, and endpoint calculations are performed in the integers; weights may lie in a commutative ring R with identity. For an arithmetic function f, write
Proof. For any q\in\mathbf N, the condition q\le\lfloor\lfloor a/b\rfloor/c\rfloor is equivalent to qbc\le a, and hence to q\le\lfloor a/(bc)\rfloor. The two sides are therefore equal. If m=\lfloor n/b\rfloor and 1\le c\le m, then bc\le n, so \lfloor m/c\rfloor=\lfloor n/(bc)\rfloor\in D_n. \square
The latter conclusion keeps the states arising in recursive prefix-sum computations within a single finite set. It is the basis for organizing states in the sublinear sieves considered later.
Proposition 5.3. Put u=\lfloor\sqrt n\rfloor. Then
Proof. The equality \lfloor n/i\rfloor=q is equivalent to q\le n/i<q+1, that is, n/(q+1)<i\le n/q. Taking integer endpoints gives the result. \square
Starting with l=1, successively compute q,r, process [l,r], and put l=r+1. This visits all maximal quotient blocks exactly once. If the upper limit is L\le n, simply truncate r to \min(r,L).
§2 Decomposition into Quotient Blocks
Theorem 5.5. Let f:[1,n]\to R and g:D_n\to R. Then
where the sum on the right runs over maximal quotient blocks. If each evaluation of S_f and g costs O(1), the summation requires O(\sqrt n) arithmetic operations and O(1) additional storage cells. Preprocessing, such as the construction of prefix tables, and its storage must be counted separately.
Proof. The argument of g is constant on each block, so its value can be taken outside the sum over that block. The blocks are disjoint and cover [1,n], and their number is bounded by Proposition 5.3. \square
Proposition 5.6. For n,i\ge1, one has \lceil n/i\rceil=\lfloor(n-1)/i\rfloor+1. Consequently, for n\ge1,
If a summand depends simultaneously on \lfloor a_1/i\rfloor,\ldots,\lfloor a_t/i\rfloor, a common refinement is obtained by computing the right endpoints of the respective quotient blocks at each step and taking their minimum.
Proof. Euclidean division verifies the first equality directly; the second separates the term i=n. In a common refinement, the dependence of the summand on these quotient values remains unchanged as long as none of them changes. The first change of any quotient value occurs immediately after the current common block. \square
Use (5.6) for positive quotient values. If a_j<i, the corresponding quotient is zero and remains zero thereafter; its right endpoint is taken to be the overall upper limit of the sum. For fixed t, the number of common blocks is at most the sum of the numbers of blocks in the individual partitions, and hence is O(\sum_j\sqrt{a_j}+t).
§3 The Hyperbola Identity
Proposition 5.7. For f,g\in\mathcal A_R and n\in\mathbf N,
Proof. The first equality assigns each ordered pair (a,b) with product k\le n to the term indexed by k; the second fixes the first coordinate. All sets are finite, so the order of summation may be interchanged. \square
Theorem 5.8 (Dirichlet hyperbola identity). Let u,v\in\mathbf N satisfy
Proof. In the region H_n=\{(a,b)\in\mathbf N_{>0}^2:ab\le n\}, the inequalities a\ge u+1 and b\ge v+1 cannot both hold. Thus the two subregions a\le u and b\le v cover H_n. Their intersection is exactly [1,u]\times[1,v], since uv\le n. Inclusion–exclusion for these two finite sets gives (5.11). \square
Corollary 5.9. One may take u=v=\lfloor\sqrt n\rfloor. Alternatively, choose any 1\le u\le n and put v=\lfloor n/u\rfloor. If individual function values and prefix values are available in constant time, evaluation of (5.11) costs O(u+v), or O(\sqrt n) for the symmetric choice.
Proof. The symmetric choice plainly satisfies (5.10). For the other choice, uv\le n<u(v+1)<(u+1)(v+1). Count the terms to obtain the bound. \square
Quotient blocks and the hyperbola decomposition partition the same finite product region in different ways. The former uses interval sums of one function and the prefix function of the other; the latter uses prefix values on both sides. If the evaluation costs on the two sides differ, an asymmetric choice of u,v may give a more suitable actual cost.
§4 Summation Examples Involving Divisors and Remainders
Example 5.10 (Mathematical formulation of P3935). Compute the prefix sum of the divisor-counting function, D(n)=\sum_{k=1}^n\tau(k). Since \tau=\mathbf1*\mathbf1,
Proof. The first sum counts ordered pairs (d,e) satisfying de\le n; the second equality is the symmetric case of Theorem 5.8. \square
The two expressions can be evaluated using quotient blocks or direct enumeration up to the square root, respectively. Both take O(\sqrt n) time and O(1) extra space. If the required sum is over [L,U], the answer is D(U)-D(L-1). The bound in the original slides reaches 1.6\times10^{14}; use an integer type that accommodates the result and intermediate products.
Example 5.11 (Mathematical formulation of P2261). For n,k\in\mathbf N, compute
Proof. Euclidean division gives k\bmod i=k-i\lfloor k/i\rfloor; the quotient is zero when i>k. Within a block, apply the formula for the sum of an arithmetic progression. \square
The complexity is O(1+\min(n,\sqrt k)), with O(1) extra space. Division by 2 in (5.14) is exact integer division. For an even modulus, first cancel the integer factor, then reduce modulo that modulus.
Example 5.12 (Mathematical formulation of ARC068E). Given N integer intervals [l_j,r_j]\subseteq[1,M], determine, for every d\in[1,M], how many of them contain at least one positive multiple of d.
The contribution of the j-th interval to the answer is
Proof. There are \lfloor r_j/d\rfloor positive multiples not exceeding r_j, exactly \lfloor(l_j-1)/d\rfloor of which lie to the left of the interval. Their difference counts the multiples in the interval; the contribution records only whether this number is positive. \square
For each interval, form common blocks for the two quotients. If a common block [a,b] satisfies (5.15), add one to \Delta[a] and subtract one from \Delta[b+1] in a difference array for the answers. After processing all intervals, take prefix sums. This takes O(N\sqrt M+M) time and O(M) space. For any fixed d, each interval contributes at most once, even if it contains several multiples.
Construction 5.13 (Decomposition by length for the same example). Let \ell_j=r_j-l_j+1 be the interval length. Process d=1,2,\ldots,M in increasing order. Insert all intervals satisfying \ell_j<d into an array supporting addition of one on an interval and point queries, and let c_d(x) denote the current coverage count at each position. Then
Proof. Any d consecutive integers contain exactly one multiple of d, so an interval of length at least d necessarily contributes. An interval of length less than d contains at most one multiple. Hence summing coverage counts over the multiples counts every contributing short interval exactly once. \square
Bucket the intervals by length, and use a Fenwick tree to maintain prefix sums of the difference array. Each interval is inserted once, and each insertion or query costs O(\log(M+1)). Since \sum_{d\le M}\lfloor M/d\rfloor=O(M\log(M+1)), the total complexity is O(N\log(M+1)+M\log^2(M+1)), with O(N+M) space. This gives a definite bound in addition to the quotient-block solution in the slides and is suitable when both N and M are large.
Example 5.14 (Mathematical formulation of P2260). For n,m\ge1, compute
Proof. Equation (5.18) deletes i=j from the rectangular index set. Equation (5.19) expands (n-iq_n)(m-iq_m) and sums term by term. \square
Using \sum_{i=1}^xi=x(x+1)/2 and \sum_{i=1}^xi^2=x(x+1)(2x+1)/6, each block requires a constant number of arithmetic operations. Thus the total complexity is O(\sqrt n+\sqrt m), with O(1) extra space; this bound does not require n,m to have the same order of magnitude. The original problem uses modulus 19940417. One may cancel 2,6 exactly among the integer factors before reduction, or use modular inverses after verifying invertibility.
§5 Combining Inversion with Quotient Blocks
Example 5.15 (Mathematical formulation of P6156). Fix a positive integer k. For several values n\le N, compute
Q_k(n)=\sum_{i=1}^n\sum_{j=1}^n
(i+j)^k\gcd(i,j)\mu^2(\gcd(i,j))
\quad\text{in }R=\mathbf Z/2^{32}\mathbf Z.
\tag{5.20}
Put t=de and interchange the finite sums. Since d^{k+1}e^k=t^kd, the coefficient of F_k(\lfloor n/t\rfloor) is t^k\sum_{d\mid t}d\mu^2(d)\mu(t/d)=h(t). \square
Proposition 5.16. Both g,h are multiplicative, and
Proof. The function \operatorname{id}\,\mu^2 is multiplicative, so its convolution with \mu is multiplicative. Its pointwise product with the completely multiplicative function \operatorname{id}_k gives the multiplicativity of h. At a prime p, the Bell series of \operatorname{id}\,\mu^2 is 1+pX. Multiplication by the Bell series 1-X of \mu gives 1+(p-1)X-pX^2, proving (5.24).
For (5.26), classify by s=a+b. There are s-1 ordered pairs when 2\le s\le x+1, and 2x-s+1 when x+2\le s\le2x. On the other hand, the coefficient of s^k in T_k(2x)-2T_k(x) is s-1 for 1\le s\le x and 2x-s+1 for x+1\le s\le2x, agreeing with these counts. \square
Equation (5.26) gives preprocessing using only addition, subtraction, and multiplication: compute s^k for s\le2N, accumulate to obtain U_k,T_k, and then compute F_k(x) for x\le N. This procedure applies in the ring modulo 2^{32}.
The linear sieve of Chapter VI can use (5.24) to compute g in O(N) operations and obtain the prefix table H(x)=\sum_{t\le x}h(t) of h. Equation (5.22) then becomes
requiring O(\sqrt n) time per query. If each s is exponentiated separately by binary exponentiation, preprocessing takes O(N\log(k+1)) time. Using the complete multiplicativity of s\mapsto s^k, one may instead compute p^k only for primes p\le2N, then multiply at every transition of the linear sieve. This gives O(N+\pi(2N)\log(k+1)) for that part. All tables together occupy O(N) space.
Chapter VI — Prime Sieves on Finite Intervals
§1 Eliminating Composite Numbers
Lemma 6.1. Every composite integer x\ge2 has a prime factor not exceeding \sqrt x.
Proof. Write x=ab with 1<a\le b<x. Then a\le\sqrt x, and any prime factor of a has the required property. \square
Construction 6.2 (Sieve of Eratosthenes). For N\in\mathbf N, create a Boolean array P[0],\ldots,P[N]. Set entries 0,1 to false wherever those indices exist, and all other entries to true. Scan p=2,3,\ldots,\lfloor\sqrt N\rfloor: if P[p] is true, set the entries at
p^2,p^2+p,p^2+2p,\ldots\le N
\tag{6.1}
to false. At the end, the indices whose entries remain true are exactly the primes not exceeding N.
Proof. Every marked integer has a factor p and is at least p^2, so it is composite. Conversely, let p be the least prime factor of a composite integer x. By Lemma 6.1, p\le\sqrt x\le\sqrt N, and x/p\ge p. Hence x is marked when p is processed. Primes are never marked, so the flag at p is true when the scan reaches it. \square
It suffices to start at p^2: a composite multiple less than p^2, written as ap, has a<p and has already been processed by a prime factor of a. In an implementation, the loop condition can be written as p\le N/p to avoid overflow from computing p^2 first.
The second inequality follows from -\log(1-y)\ge y for 0<y<1. Expanding the finite product of convergent geometric series by unique factorization gives a subseries of the positive-term series \sum_{n\ge1}n^{-s}. Thus the product is at most
Substitution into (6.3) proves the result. A convergent real series with s>1 is used here only to estimate complexity; its convergence has already been ensured by the integral bound. \square
Corollary 6.4. Construction 6.2 takes O(N\log\log(N+2)) time and O(N) space.
Proof. Initialization and the final scan take O(N) time. Each prime p causes at most \lfloor N/p\rfloor markings, so Proposition 6.3 gives the total bound. \square
§2 Sieving and Factorization on an Interval
Construction 6.5 (Segmented prime sieve). Given 1\le L\le U and the primes not exceeding \lfloor\sqrt U\rfloor, initialize a Boolean array on [L,U]. For each prime p in the list, start at
and mark all multiples of p not exceeding U. If 1\in[L,U], also mark 1 as nonprime. The remaining elements are exactly the primes in the interval.
Proof. The lower bound p^2 prevents removal of the prime p itself. Every composite integer x in the interval has a least prime factor p\le\sqrt U and satisfies x\ge p^2, so it is necessarily marked. The other elements cannot be removed incorrectly by the construction. \square
Put W=U-L+1 and B=\lfloor\sqrt U\rfloor. If the prime list is already available, the scan takes
with O(W) extra space. Constructing the base prime list additionally requires O(B\log\log(B+2)) time and O(B) space. The term \pi(B) in (6.6) counts the scan of the base prime list.
Construction 6.6 (Complete factorization of the integers in an interval). For every x\in[L,U], store a residual value a_x=x and an initially empty factor list. For each prime p\le B, visit all its multiples x in the interval, starting at \lceil L/p\rceil p. Repeatedly set a_x\leftarrow a_x/p until p\nmid a_x, recording the number of divisions. After all primes have been processed, if a_x>1, append a_x to the factor list as a prime factor of exponent one.
Proof. Every division is exact integer division. When a prime factor p is processed, its entire exponent in x is removed; earlier removal of other prime factors does not change that exponent. If the final a_x>1 were still composite, it would have a prime factor not exceeding \sqrt{a_x}\le\sqrt U, contradicting the removal of all such prime factors. Nor can the square of the residual prime factor divide x: that prime would then not exceed \sqrt U, again contradicting its having been completely removed. \square
Starting at the first multiple in the interval also records the factor p when x=p. For x=1, no division is performed and the factor list is empty.
For each x, the number of divisions is at most \lfloor\log_2x\rfloor. A direct uniform upper bound is therefore
O\bigl(\pi(B)+W\log(U+1)\bigr)
\tag{6.7}
integer operations, in addition to preprocessing the base prime list. Space for outputting all prime factors and exponents must be included. A coarse bound is O(W\log(U+1)); processing subsequent tasks for each integer immediately can reduce the amount retained for later use.
§3 Generating Each Composite Integer Uniquely
Definition 6.7. For n\ge2, let \operatorname{lpf}(n) denote the least prime factor of n. The canonical generating pair of a composite integer x is
Construction 6.8 (Linear sieve). Initialize \operatorname{lpf}[2..N]=0 and an empty prime list. Scan i=2,3,\ldots,N: if \operatorname{lpf}[i]=0, set \operatorname{lpf}[i]=i and append i to the prime list. Then enumerate the primes p in the list in increasing order. As long as
set \operatorname{lpf}[ip]=p. Terminate the current inner loop when the conditions cease to hold.
Theorem 6.9. Construction 6.8 produces the correct least-prime-factor table and generates each composite integer exactly once. Its time and space requirements are both O(N).
Proof. Any generating pair satisfies p\le\operatorname{lpf}(i), so the least prime factor of ip is exactly p; the assigned value is correct. Conversely, for a composite integer x, take its canonical generating pair (i,p). Since i<x, the index i is processed before the scan reaches x. Moreover, p\le\operatorname{lpf}(i)\le i, so p is already in the prime list and satisfies the conditions of the inner loop. Thus x must be generated. Any pair generating x must have p=\operatorname{lpf}(x) and hence i=x/p, so the generation is unique.
Consequently, an index i not yet generated is precisely a prime. The number of successful inner-loop iterations equals the number of composite integers, with at most one additional termination test per outer index. Initialization and prime insertion are also linear, giving total time O(N). \square
A common implementation first generates ip and then exits immediately if p\mid i. Since the primes are in increasing order and the first prime dividing i is \operatorname{lpf}(i), this is equivalent to (6.9).
§4 Propagating Function Values Along Canonical Factorizations
Construction 6.10. For each i\ge2, maintain the unique factorization
and store c_i,e_i and p^{e_i}. For a prime i=p, take c_i=1,e_i=1. A transition i\mapsto ip in the linear sieve has only two cases:
\begin{array}{c|c|c|c}
\text{Condition}&c_{ip}&e_{ip}&\text{Power of the least prime factor}\\ \hline
p<\operatorname{lpf}(i)&i&1&p\\
p=\operatorname{lpf}(i)&c_i&e_i+1&p^{e_i+1}
\end{array}
\tag{6.11}
Proposition 6.11. Let f be multiplicative. Suppose that establishing the local state at each prime costs C_p, and that the local state for f(p^{e+1}) can be obtained from that for f(p^e) in O(1) operations. Then the linear sieve can use
f(i)=f(c_i)f(p^{e_i})
\tag{6.12}
to compute all f(1),\ldots,f(N) at total cost O(N+\sum_{p\le N}C_p) and with O(N) space, provided that each local state occupies O(1) storage cells.
Proof. The two factors in the canonical factorization are coprime, so (6.12) is valid. The first type of transition uses only the local value already established at the prime. The second extends an existing local state, and the function value at c_i<i is already known. Each composite integer requires one constant-time step; adding the prime initialization costs gives the stated bound. \square
Retaining f(c_i) and the local prime-power state computes f(i) by multiplication and applies over any coefficient ring. The total cost is the sum of canonical generation and local-state computation costs.
Example 6.12 (\mu and \varphi). Initialize \mu(1)=\varphi(1)=1. At primes, put \mu(p)=-1 and \varphi(p)=p-1. In a transition of the linear sieve,
\mu(ip)=
\begin{cases}
-\mu(i),&p\nmid i,\\
0,&p\mid i,
\end{cases}
\qquad
\varphi(ip)=
\begin{cases}
(p-1)\varphi(i),&p\nmid i,\\
p\varphi(i),&p\mid i.
\end{cases}
\tag{6.13}
Proof. If p\nmid i, use multiplicativity. If p\mid i, then ip has the square factor p^2, so \mu(ip)=0. At the same time, increasing p^e to p^{e+1} changes the local value of \varphi from (p-1)p^{e-1} to (p-1)p^e. \square
The condition in the second branch is p\mid i, where i is the index before multiplication by the prime p.
Example 6.13 (Sums of powers of divisors). Fix k\in\mathbf N. For the local prime power in (6.10), maintain
Proof. The first two equalities respectively increase an exponent and add a summand; the third uses multiplicativity for the coprime factorization. \square
For k=0, it suffices to store e_i, and the formula becomes \tau(i)=\tau(c_i)(e_i+1). For k=1, store p^{e_i} and its geometric sum. Both functions can be computed in O(N) time. For an arbitrary input k, the prime initialization values p^k can be computed by binary exponentiation; Proposition 6.11 gives total cost O(N+\pi(N)\log(k+1)). Over the integers, one may also use the exact quotients \tau(i)/(e_i+1) or \sigma_1(i)/B_{p,e_i}; over a general coefficient ring, use the multiplicative recurrence (6.15).
Construction 6.14 (General form with prescribed prime-power values). Suppose all values f(p^e) for p^e\le N have been supplied and can be queried in constant time. Maintain the data in (6.10) and compute f(i) directly by (6.12). The additional time and space are both O(N).
Proof. Each step of the canonical factorization adds only one prime factor, and the local value can be read directly from the table. The prime powers are distinct integers in [1,N], so the local table contains at most N-1 entries. The cost of constructing it has been separated from this construction. \square
The enumeration by cp^e used in the slides can also be expressed through this canonical factorization; its total cost is the sum of integer generation and prime-power data preparation costs.
§5 An Application of Factorization on a Short Interval
Example 6.15 (Mathematical formulation of the strengthened Haitang and Math problem). Given 1\le n\le10^{12}, determine the number of solutions of
1\le m\le n,\qquad n\bmod m=S(m)
\tag{6.16}
in positive integers m, where S(m) is the sum of the decimal digits of m.
Within the given range, S(m)\le108: a positive integer below 10^{12} has at most twelve digits, and the endpoint 10^{12} has digit sum 1. Since a remainder is less than the divisor, every solution also satisfies 1\le S(m)<m.
Proposition 6.16. Put B=\min(108,n-1). The solutions of (6.16) are in bijection with the accepted candidates in the following procedure: enumerate s\in[1,B], enumerate the positive divisors m of n-s, and retain those satisfying
S(m)=s,\qquad m>s
\tag{6.17}
as candidates.
Proof. If m solves the original problem, put s=S(m). Then n-s is a positive multiple of m, and s<m\le n, so s\le n-1. Conversely, if m\mid n-s and 0<s<m, the equality n=(n-s)+s is the Euclidean division decomposition with divisor m and remainder s. Together with S(m)=s, it gives the original equality. Moreover, m\le n-s<n, so the range condition holds automatically. Each m corresponds to the unique value s=S(m) and is not counted again for a different s. \square
It therefore suffices to factor all integers in [n-B,n-1] simultaneously. There are at most 108 positive integers in this interval; Construction 6.6 with a list of primes not exceeding 10^6 gives their factorizations. If n=1, then B=0, the candidate set is empty, and the answer is zero.
Once the factorization x=\prod_{j=1}^{r}p_j^{e_j} is known, enumerate its divisors through the Cartesian product map
Unique factorization ensures that this is a bijection. Successively adjoining each prime power enumerates all divisors in O(\tau(x)) multiplications. Computing each digit sum takes O(\log(n+1)) integer divisions; in the original range there are at most twelve digits, with the endpoint handled separately.
With the base prime list already preprocessed, a sufficient upper bound for one query is
The three terms respectively count the scan of the base primes, divisions during factorization of the interval, and checks of all candidate divisors. Divisor enumeration is charged according to the sum of divisor counts over the entire short interval. Multiple queries may share the prime list up to 10^6; the residual values on each interval and the candidate checks are handled separately for each query.
Chapter VII — Convolution and Division on Quotient-Value Sets
Write the prefix sum of an arithmetic function f as F(x)=\sum_{1\le n\le x}f(n), and set F(0)=0. The indexed finite family (F(v))_{v\in\mathcal Q_N} is called the quotient-value representation of f at N, corresponding to the block sieve in the lecture notes. Here \mathcal Q_N is precisely D_N from Chapter V. The indexing retains the correspondence between arguments and values for lookup in the operations below.
Proposition 7.2. There is a disjoint decomposition
In particular, |\mathcal Q_N|=s+K\le2s. If v\in\mathcal Q_N and 1\le d\le v, then \lfloor v/d\rfloor\in\mathcal Q_N.
Proof. For 1\le t\le s, take i=\lfloor N/t\rfloor\ge t. From ti\le N<t(i+1) we obtain t\le N/i<t+t/i\le t+1, so t is a quotient value. The values greater than s are precisely those obtained from i\le K; in this range, successive values of N/i differ by at least 1, so their floors are distinct. Finally, if v=\lfloor N/i\rfloor, then
Whenever the right-hand side is positive, it still belongs to \mathcal Q_N. \square
A small quotient value can be addressed directly by v, and a large one by \lfloor N/v\rfloor. Thus the quotient-value table can be represented by two arrays of length O(\sqrt N), supporting worst-case constant-time queries.
Proposition 7.3. For an integer 0\le t\le N, write r_N(t)=|\mathcal Q_N\cap[1,t]|. Then
Proof. In the second case, a large quotient value satisfies \lfloor N/i\rfloor\le t if and only if i>N/(t+1). Count such indices in [1,K] and add all s small quotient values. \square
§2 Prefix Representations of Convolution
Proposition 7.4. Let h=f*g, with respective prefix sums H,F,G. For x\ge1 and u=\lfloor\sqrt x\rfloor,
Proof. Write H(x) as \sum_{ab\le x}f(a)g(b). If a,b>u, then ab\ge(u+1)^2>x. Every admissible pair therefore satisfies a\le u or b\le u, and the part counted twice is exactly [1,u]^2. \square
Construction 7.5. Given only the values of F,G on \mathcal Q_N, the quotient-value representation of H can be computed using O(N^{3/4}) ring operations and O(\sqrt N) storage cells.
Proof. Since [1,s]\subseteq\mathcal Q_N, successive differences give all the required values f(a),g(a). Apply (7.5) for every x\in\mathcal Q_N; Proposition 7.2 ensures that the remaining prefix queries are available. The total operation count is bounded by a constant multiple of
\sum_{x\in\mathcal Q_N}\sqrt x
\le\sum_{x\le s}\sqrt x+
\sum_{i\le K}\sqrt{N/i}=O(N^{3/4}).
\tag{7.6}
Estimate each sum by comparison with an integral. \square
Proposition 7.6. Suppose, in addition, that h(1),\ldots,h(B) and their prefix sums can be computed at total cost P(B), where \sqrt N\le B\le N. The remaining quotient values can then be computed by (7.5), at total cost
O\bigl(P(B)+N/\sqrt B\bigr).
\tag{7.7}
Proof. Quotient values greater than B have the form \lfloor N/i\rfloor, with i<N/B. Their total evaluation cost is at most
The small quotient values have already been obtained by preprocessing. \square
Remark. If a linear-time method is also available for precomputing the first B values and their prefix sums, so that P(B)=O(B), taking B\asymp N^{2/3} gives O(N^{2/3}). Construction 7.5 applies to two given quotient-value tables; with this additional preprocessing method, formula (7.7) applies.
§3 Division for Convolution
Theorem 7.7. Suppose h=f*g and g(1) is a unit in the coefficient ring. Then F is uniquely determined by
Proof. Summing over the second factor gives H(x)=\sum_{b\le x}g(b)F(\lfloor x/b\rfloor). Separate the term b=1 and multiply by g(1)^{-1} to obtain (7.8). Every unknown prefix on its right-hand side has argument at most \lfloor x/2\rfloor, so the values of F are uniquely determined in increasing order. Formula (7.9) follows by factoring out the common value on a constant interval. \square
Construction 7.8. Suppose G(x),H(x) can be evaluated with a constant number of elementary operations, and F(1),\ldots,F(B) can be precomputed in linear time. Memoized evaluation of (7.8)–(7.9) on quotient values greater than B is called the Du Jiao sieve. For \sqrt N\le B\le N, its time and space bounds are, respectively,
O(B+N/\sqrt B),\qquad O(B+N/B).
\tag{7.10}
Proof. The recursive argument strictly decreases, so the computation terminates; Proposition 7.2 ensures that a computation starting at N visits only its quotient values. Each large state is evaluated once, processing at most O(\sqrt x) constant intervals. Sum over these states using the estimate from Proposition 7.6. Small states are looked up in the precomputed table, and there are at most N/B large states. \square
Taking B=\lceil N^{2/3}\rceil, capped at N, gives the bound O(N^{2/3}). For evaluations of G,H that take more than constant time, multiply the operation count by the corresponding evaluation costs.
Example 7.9. Write M(x)=\sum_{n\le x}\mu(n) and \Phi(x)=\sum_{n\le x}\varphi(n). From \mu*\mathbf1=\varepsilon and \varphi*\mathbf1=\operatorname{id}, for x\ge1 we have
Both expressions can be evaluated by Construction 7.8. The rational expression here is first evaluated as an integer, then mapped into the coefficient ring; this evaluation method also applies to even moduli.
§4 Completely Multiplicative Weights
Proposition 7.10. Let w be completely multiplicative, and let wf denote pointwise multiplication. Then
(wf)*(wg)=w(f*g).
\tag{7.12}
Proof. For every d\mid n, we have w(d)w(n/d)=w(n), which can therefore be factored out of the convolution sum. \square
Proof. Substitute \gcd(i,j)=\sum_{d\mid i,\ d\mid j}\varphi(d), interchange the finite sums, and put i=du,j=dv to obtain (7.13). Applying Proposition 7.10 with w(n)=n^2 gives
Theorem 7.7 and \sum_{i\le x}i^3=T(x)^2 then give (7.14). \square
In (7.14), an interval weight is a difference of sums of squares; in (7.13), it is F(r)-F(l-1). Compute F by the Du Jiao sieve and then perform one quotient-block summation to obtain the computation required by P3768 in the lecture notes. Modulo a prime p>3, both 2,6 are invertible; for other moduli, the integer identities still permit cancellation before reduction.
Chapter VIII — Prime Weights and Decomposition by the Least Prime Factor
§1 A Finite Process for Removing Composite Numbers
Definition 8.1. Let w be completely multiplicative, and let p_1<p_2<\cdots be the sequence of primes. Put
Proof. The difference between the two stages consists exactly of the composite numbers whose least prime factor is p. They are uniquely expressible as pm, where m\ge p and \operatorname{lpf}(m)\ge p. Evaluating (8.1) at \lfloor v/p\rfloor\ge p and subtracting the smaller primes already retained enumerates precisely these m. Complete multiplicativity gives w(pm)=w(p)w(m), including when p\mid m. If v<p^2, there is no composite number to remove. \square
Construction 8.3. Initialize A(v)=\sum_{n=2}^{v}w(n) on \mathcal Q_N. Process primes p\le\sqrt N in increasing order; for each prime, apply (8.2) to the quotient values satisfying v\ge p^2 in decreasing order. On completion, A(v)=P_w(v).
Proof. Within a round, \lfloor v/p\rfloor<v. Thus, when updating in decreasing order of v, the smaller argument on the right still holds its value from the preceding round. Proposition 7.2 ensures that this argument is present in the table. Induction using Proposition 8.2 establishes the invariant at every stage. At completion, every composite n\le v\le N has a prime factor at most \sqrt N and has therefore been removed; primes have been retained throughout. \square
Obtain P_w(p-1) from a separate prefix table for the small primes already enumerated. Initialize by subtracting w(1)=1 from the full prefix sum, so that the candidate set starts at 2.
§2 Operation Counts
Lemma 8.4. Let \pi(x) denote the number of primes not exceeding x. Then \pi(x)=O(x/\log x) for x\ge2.
Proof. For an integer m\ge2, the product of all primes in (m,2m] divides \binom{2m}{m}<4^m. Taking logarithms bounds the number of primes in this interval by O(m/\log m). Partition (\sqrt x,x] into dyadic intervals: each denominator is \Omega(\log x), and the numerators sum to O(x). There are at most \sqrt x primes not exceeding \sqrt x. Combining the bounds proves the assertion; rounding affects only absolute constants. \square
Proposition 8.5. The number of updates in Construction 8.3 is
Proof. Put L=N^{1/4}. The contribution from p\le L is at most 2\sqrt N\pi(L)=O(N^{3/4}/\log N). For p>L, all required quotient values exceed \sqrt N, and their number is at most N/p^2. Grouping the primes into intervals (2^jL,2^{j+1}L] and applying Lemma 8.4 gives
The cost of generating the small primes and computing all initial values and local weights must be added to this bound. If these costs are O(\sqrt N) and weight evaluation and ring operations are elementary operations, the overall bound remains (8.3), with O(\sqrt N) space.
Example 8.6. For fixed k\ge0, take w(n)=n^k. The initial value is the power sum \sum_{n\le v}n^k-1. Since k is fixed, it can be evaluated by an integer-valued polynomial of fixed degree with rational coefficients, performing exact cancellation in the integers before mapping into the coefficient ring; alternatively, interpolation may be used over a suitable coefficient field. Construction 8.3 yields all values \sum_{p\le v}p^k. The expression required by P5493 in the lecture notes,
then requires only O(\sqrt N) table queries. If f(p)=\sum_{k=0}^{d}c_kp^k, compute the d+1 tables of sums of powers of primes separately and combine them linearly to obtain P_f(v)=\sum_{p\le v}f(p); for fixed d, only the constant changes. Polynomial interpolation is performed in a coefficient field or residue class ring in which all the denominators involved are invertible.
§3 Reconstructing a Multiplicative Function
Definition 8.7. Let f be multiplicative and define
Proof. The first term gives the contribution of primes. Every composite n has a unique least prime factor p_k>p_j, with p_k^2\le n. If n=p_k^t, where t\ge2, it occurs exactly in the second summand for e=t-1. Otherwise, it is uniquely expressible as p_k^eu, where e\ge1, u>1, and \operatorname{lpf}(u)>p_k; its contribution is f(p_k^e)f(u) by multiplicativity. In this case p_k^{e+1}<n\le x, so the first summand enumerates it exactly once. The cases are pairwise disjoint. \square
Given the prime-weight table, (8.6) defines a finite recursion with increasing least prime factors, constituting the reconstruction stage of the Min_25 method. The integer argument strictly decreases, while the lower bound on prime factors strictly increases; the unit contribution 1 is added only at the outermost level.
Remark. The total cost of the Min_25 method consists of prime-table construction and recursive reconstruction. Proposition 8.5 counts the former; §5 counts the latter through its recursive states and prime-power branches. Chapter IX gives another reconstruction procedure and its operation bound under the same polynomial condition at primes.
§4 The Inverse Process in the Completely Multiplicative Case
Theorem 8.9. Let g be completely multiplicative. Suppose the values of P_g on \mathcal Q_N and the weights at primes p\le\sqrt N are known. Set A(v)=P_g(v). Process the small primes p in decreasing order; for each prime, process quotient values satisfying v\ge p^2 in increasing order, applying
On completion, 1+A(v)=\sum_{n\le v}g(n). The number of updates is the same as in (8.3).
Proof. Fix a round p=p_j. By Proposition 8.2, restoring A_{j-1}(v) requires A_{j-1}(\lfloor v/p\rfloor). With increasing v, the smaller argument has either already been restored in this round or was unchanged because it is less than p^2. Thus (8.7) undoes the round entry by entry. Undoing all rounds in decreasing prime order finally restores A_0(v)=\sum_{2\le n\le v}g(n). \square
This process inverts the triangular transformation by reversing the loop order. Formula (8.7) uses only addition, subtraction, and multiplication, so it also applies when g(p)=0.
§5 An Independent Count of the Recursion Tree
Proposition 8.10. Let P^+(d) denote the greatest prime factor of d>1, and put
Starting at S_f(N,0), evaluate (8.6) directly by depth-first recursion without merging equal states. If local function values and prime-prefix queries have constant cost, the recursive stage uses O(1+C(N)) operations. Moreover, C(N)=o(N); a coarse explicit upper bound is O(N/\sqrt{\log N}).
Proof. A recursive path selects complete prime powers in strictly increasing prime order; denote their product by d. If the last selected power is p^e, the loop condition is exactly dp\le N, and p=P^+(d). Conversely, for an integer satisfying dP^+(d)\le N, every initial product of its prime-power factors also satisfies the corresponding loop condition. Unique factorization therefore gives a unique recursive path. Thus the nonroot calls are indexed precisely by the set in (8.8). Each call computes its prime contribution at constant cost; every successful exponent iteration produces a child call. Every prime branch entered contains at least one successful exponent iteration, so its final exponent-loop check is amortized against a child call. Each function call has only a constant number of additional outer-loop termination checks, proving the operation bound.
Fix Y\ge2. If P^+(d)>Y, then d\le N/Y; if P^+(d)\le Y, then d uses at most \pi(Y) primes, each with exponent at most \lfloor\log_2N\rfloor. Consequently,
First let N\to\infty, then let the fixed Y\to\infty, to obtain C(N)=o(N). Taking Y=\sqrt{\log N} and using \pi(Y)\le Y, the logarithm of the second term is O(\sqrt{\log N}\log\log N)=o(\log N), so that term is eventually less than N^{1/2}; the first term is N/\sqrt{\log N}. \square
This gives a sublinear bound for the recursion. The next chapter gives another complete reconstruction procedure with a fixed-power operation bound.
Chapter IX — Sparse Convolution Supported on Powerful Numbers
§1 Local Differences
Definition 9.1. A positive integer d is called powerful if every prime p dividing d satisfies p^2\mid d. Denote the set of such integers by \mathcal P, with the convention 1\in\mathcal P. These are the powerful numbers of the lecture notes.
Theorem 9.2. Let f,g be multiplicative functions satisfying f(p)=g(p) for every prime p. There is a unique multiplicative function h such that f=g*h, and h(d)\ne0 implies d\in\mathcal P.
Proof. Since g(1)=1, its convolution inverse exists and is multiplicative. Thus h=g^{-1}*f exists, is unique, and is multiplicative. Comparing the two sides at a prime gives f(p)=g(p)+h(p), so h(p)=0. If a prime factor p occurs in d with exponent exactly one, then h(d)=h(p)h(d/p)=0. \square
Proposition 9.3. Given the local values f(p^e),g(p^e), the values of h can be computed successively from
The intermediate terms cancel in pairs, and uniqueness proves the assertion. \square
The telescoping sum uses only addition, subtraction, and multiplication, so it applies when f(p)=0, in coefficient rings with zero divisors, and for composite moduli.
§2 Counting and Enumerating the Support
Lemma 9.4. Every d\in\mathcal P has a unique expression
Proof. For each positive prime exponent e in d, if e is even, give that prime exponent e/2 in a and 0 in b; if e is odd, then e\ge3, and the corresponding exponents are (e-3)/2 and 1. Parity at each prime also proves uniqueness. Hence
Finally, group the terms by 2^j\le d<2^{j+1}. Each group's weighted sum is O(1), and there are O(\log(2X)) groups. \square
Construction 9.5. First list the primes not exceeding \sqrt N. A recursive state (d,j,z) records a powerful number d formed from chosen primes not exceeding p_j, together with its weight z=h(d). Starting from (1,0,1), first output (d,z). For every k>j satisfying dp_k^2\le N, successively take all e\ge2 with dp_k^e\le N, and enter
(dp_k^e,k,z\,h(p_k^e)).
\tag{9.5}
Proof. Along each path, the primes strictly increase and all exponents are at least 2, so every output is powerful. Conversely, the factorization of a powerful number into increasing primes with their unique exponents determines its unique generation path. The parent state's integer is coprime to the newly added prime power, so multiplicativity ensures the correct weight. Each edge produces a new node; prime enumeration at each node adds only a constant number of final boundary checks. Thus, when local values are available in constant time, the enumeration cost is of the same order as the number of outputs. \square
In an implementation, test p\le\lfloor\sqrt{N/d}\rfloor before entering a branch, and use division to test whether another multiplication by p is possible, avoiding overflow before the test. Even when z=0, correctness does not depend on skipping the branch; if zero in the coefficient ring can be recognized in constant time, all descendants may be pruned.
§3 A Single Prefix Sum
Theorem 9.6. Under the hypotheses of Theorem 9.2, write G(x)=\sum_{n\le x}g(n). Then
If every required value of G and every local value h(p^e) is available in constant time, then, once the small primes are known, F(N) can be computed with O(\sqrt N) elementary operations.
Proof. Interchanging the finite sums in f=g*h gives F(N)=\sum_{d\le N}h(d)G(\lfloor N/d\rfloor). Remove the terms outside the support by Theorem 9.2, then apply Lemma 9.4 and Construction 9.5. \square
Remark. Choosing the auxiliary function g has two parts: obtaining sparse support through g(p)=f(p), and determining how to compute its prefix sums G. For a completely multiplicative choice, Theorem 8.9 recovers the prefix sums; when a simple convolution relation is available, the methods of Chapter VII apply.
Example 9.7. Fix an integer c\ge0, and let the multiplicative function q satisfy
q(p^e)=p^{c\lfloor e/2\rfloor}.
\tag{9.7}
Take g=\mathbf1. By (9.2), h(p^{2j+1})=0, whereas
h(p^{2j})=p^{cj}-p^{c(j-1)}\qquad(j\ge1).
Define the multiplicative function J_c by the local values J_c(p^j)=p^{cj}-p^{c(j-1)}, and set J_c(1)=1. Then
Proof. The function h can be nonzero only at squares, and h(a^2)=J_c(a). Substitute this fact and G(x)=x into (9.6). \square
The values of J_c can be computed by a linear sieve using J_c(p)=p^c-1 and
J_c(ip)=
\begin{cases}
p^cJ_c(i),&p\mid i,\\
(p^c-1)J_c(i),&p\nmid i
\end{cases}
Thus, for fixed c and with the cost of computing p^c included, the time and space required by (9.8) are both O(\sqrt N). Only addition, subtraction, and multiplication occur, so the computation can be performed directly in \mathbf Z/2^{32}\mathbf Z. This gives the auxiliary function for the PN example in the lecture notes.
§4 Recovering All Quotient Values Simultaneously
Lemma 9.8. Fix 1\le d\le N, and put M=\lfloor N/d\rfloor. Then
For q\in\mathcal Q_M, the corresponding preimage is exactly
\mathcal Q_N\cap[dq,\min(N,d(q+1)-1)].
\tag{9.10}
Proof. For v=\lfloor N/i\rfloor, we have \lfloor v/d\rfloor=\lfloor M/i\rfloor; the nonzero values correspond to i\le M. This proves the equality of image sets. The description of the preimage follows directly from integer division. \square
Construction 9.9. Suppose \mathcal Q_N has been indexed in increasing order as v_1<\cdots<v_L, and G(v) is known. Initialize a zero array \Delta of length L+1. Enumerate each (d,h(d)) and put M=\lfloor N/d\rfloor; then enumerate q\in\mathcal Q_M and set
Perform \Delta_a\leftarrow\Delta_a+c and \Delta_{b+1}\leftarrow\Delta_{b+1}-c. Finally, take one ordinary prefix sum, setting
F(v_i)=\sum_{j=1}^{i}\Delta_j.
\tag{9.12}
Formula (7.4) computes ranks in constant time; (7.2) enumerates each \mathcal Q_M without repetition. Proposition 7.2 guarantees q\in\mathcal Q_N, so every G(q) is available for lookup.
Theorem 9.10. Construction 9.9 correctly recovers the entire quotient-value representation of F. When local weights and queries have constant cost, its time, excluding the construction of G, is O(\sqrt N\log(2N)), and its space is O(\sqrt N).
Proof. For fixed d, (9.10) partitions all v\ge d into disjoint intervals of consecutive indices according to equal quotients. The difference-array updates add exactly h(d)G(\lfloor v/d\rfloor) to every such v. Summing over all d gives correctness by Theorem 9.6. The number of interval updates is
The final prefix accumulation and the enumeration of powerful numbers both take O(\sqrt N). Only the quotient-value table, the difference array, the small-prime table, and the recursion stack need to be retained. \square
Applying Theorem 9.6 independently to each quotient value yields only the general bound O(N^{3/4}) from (7.6). The improvement in (9.13) comes from accumulating identical contributions over intervals.
§5 A Complete Reconstruction Procedure
Theorem 9.11. Let f be multiplicative, and suppose f(p)=\sum_{k=0}^{D}c_kp^k at primes. Assume that D is fixed, the required local prime-power values are available in constant time, and sums of fixed powers can be evaluated in constant time. Then the quotient-value representation of f can be computed in
elementary operations, using O((D+1)\sqrt N) space.
Proof. Perform the following finite constructions in order.
For k=0,\ldots,D, use Construction 8.3 to compute the prime power sums, then combine them linearly into P_f(v).
Define the completely multiplicative function g by g(p)=f(p); thus P_g=P_f. Obtain G(v) by Theorem 8.9.
Define h by (9.2), and enumerate its powerful-number support by Construction 9.5.
Obtain all F(v) by Construction 9.9.
The preceding propositions establish the correctness of each stage. Adding the costs in Proposition 8.5 and Theorem 9.10 gives the result. \square
Thus the polynomial condition at primes is used only to construct the prime-weight table; deviations at higher prime powers are carried separately by h. This explains why the prime-weight sieve, its inverse process, and the PN correction can be combined.
Chapter X — Divisibility Matrices and Sums in Two Variables
§1 The Matrix of the Divisibility Relation
Definition 10.1. Fix n\ge1, and let E be the n\times n integer matrix
E_{ij}=[j\mid i].
\tag{10.1}
It is lower triangular with every diagonal entry equal to 1. For an arithmetic function a, put b=\mathbf1*a.
In particular, its determinant is \prod_{d=1}^{n}a(d).
Proof. The (i,j) entry on the right is \sum_{d\mid i,\ d\mid j}a(d)=b(\gcd(i,j)). Since \det E=1, taking determinants of the matrix product proves the remaining assertion. \square
Proposition 10.3. The matrix E is invertible over the integers, with
(E^{-1})_{ij}=[j\mid i]\mu(i/j).
\tag{10.3}
Proof. The (i,j) entry of the product of the two matrices is [j\mid i]\sum_{d\mid i/j}\mu(d)=[i=j]. \square
Elimination on the divisibility matrix is therefore a finite linear representation of Möbius inversion. Formula (10.3) directly gives an integer elimination transformation that can be applied entrywise in the coefficient ring.
§2 Matrices with Integer Weights
Example 10.4. Let A_{ij}=ij\gcd(i,j). Define the lower triangular integer matrix
Every diagonal entry of L equals 1, so the determinant identity follows. \square
This factorization holds entrywise over the integers. Left multiplication by L^{-1} gives the upper triangular matrix
(L^{-1}A)_{ij}=[i\mid j]ij\varphi(i),
\tag{10.5}
which is exactly the elimination result used in P6384 in the lecture notes. To implement it solely by elementary row operations, process i in increasing order and, for k=2,\ldots,\lfloor n/i\rfloor, subtract k times row i from row ki. The multiplier k corresponds to the original matrix's row weight i. The notes' method of first dividing out row and column weights and then eliminating is also valid over the rationals; (10.4) is itself an integer identity and can be mapped directly into a residue class ring.
§3 The Multiplicative Relation between GCD and LCM
Theorem 10.5. Suppose f(1)=1. The function f is multiplicative if and only if, for all positive integers a,b,
Proof. If f is multiplicative, factor a,b into primes. For each prime p, the local factors on the two sides are f(p^u)f(p^v) and f(p^{\min(u,v)})f(p^{\max(u,v)}), respectively, and are equal. Conversely, for coprime a,b, the right-hand side is f(1)f(ab)=f(ab), proving multiplicativity. \square
This assertion requires neither complete multiplicativity nor nonzero function values.
Example 10.6. Let \omega(n) denote the number of distinct prime factors of n, with \omega(1)=0. For t\in\{0,1\}, put
Proof. The right-hand side of the first identity counts squarefree divisors, with each distinct prime factor independently included or omitted. Both sides of the second identity are multiplicative. At p^e, the right-hand side is 1 for e=0,1, and 1+\mu(p)=0 for e\ge2, agreeing with the left-hand side. \square
The inner sum, enumerated by a, is exactly D_t(\lfloor N/k^2\rfloor). All sums are finite, so interchanging their order requires no convergence assumptions. \square
Construction 10.10. Put r=\lfloor\sqrt x\rfloor. Then
For t=0,1, this gives an exact algorithm using O(\sqrt x) elementary operations.
Proof. Apply Proposition 7.4 symmetrically, taking both functions to be a\mapsto a^t. \square
First compute \mu(k) by a linear sieve, then apply (10.11) term by term. Formula (10.10) can thereby be evaluated with O(\sqrt N\log(2N)) elementary operations, because
This gives a complete baseline implementation against which to check more advanced algorithms. The largest parameters in the lecture notes call for an improvement to the inner lattice-point sum; the next chapter develops this geometric step.
Chapter XI — The Lattice Boundary of a Hyperbola and Weighted Summation
§1 From Row-by-Row Enumeration to Rational Directions
This chapter supplies the geometric algorithm omitted from the final example in the original lecture notes. Fix N\ge1, and write
The variables x,y in the sum are positive integers. The hyperbola method in the preceding chapter computes \lfloor N/y\rfloor one row at a time. The alternative representation in this chapter combines a consecutive group of rows into a rectangle and a triangle with a rationally sloped hypotenuse, and then evaluates their weights together.
We use the subdivision by rational directions developed in the original papers, together with a polygonal chain of lattice points lying strictly above the hyperbola. All update formulas and an executable program are given here. The sources of the method are Section 4 of Zhu Zhenting's Some Special Problems in Summing Arithmetic Functions and Richard Sladkey's original paper.
Definition 11.1. A point (X,Y)\in\mathbf Z_{>0}^2 is an exterior point if XY>N. A lattice point with positive coordinates satisfying XY\le N is an interior point; lattice points on the hyperbola are included among the interior points. A primitive direction pointing downward and to the right is written as
The nonnegative pair (p,q) is used for storage; the second component is negated only when applying the direction to a point.
Definition 11.2. Two directions L=(p,q) and R=(r,s) are adjacent directions if
qr-ps=1.
\tag{11.3}
They satisfy q/p>s/r. Their mediant direction is defined as M=L+R=(p+r,q+s).
Proposition 11.3. Equation (11.3) implies that M is primitive and that both (L,M) and (M,R) are pairs of adjacent directions. If the absolute slope of a primitive direction (a,b) lies strictly between s/r and q/p, there are unique positive integers u,v such that
(a,b)=u(p,q)+v(r,s).
\tag{11.4}
In particular, a\ge p+r and b\ge q+s.
Proof. Both new determinants equal the original determinant. If an integer divides both p+r and q+s, it divides q(p+r)-p(q+s)=1. Since their determinant is -1, the two directions form a basis of \mathbf Z^2; solving the linear equations gives integer coordinates. The strict inequalities between the slopes make both coordinates positive. \square
Repeated insertion of mediant directions gives the Stern–Brocot search among rational numbers, with comparisons performed on integer directions.
§2 Four Moments of a Triangle
Definition 11.4. For a primitive direction (p,q), define the lattice-point set in a closed triangle by
Lemma 11.5. Suppose that L=(p,q) and R=(r,s) satisfy (11.3). The lattice-point set \mathcal T(p+r,q+s) can be assembled from three parts: \mathcal T(p,q); the translate of \mathcal T(r,s) by (p,-q); and the rectangle
The first two parts overlap exactly once, at (p,-q); the rectangle is disjoint from both.
Proof. The triangle between the two smaller hypotenuses and the larger hypotenuse has area 1/2. Since the determinant of the two directions is \pm1, a linear transformation invertible over the integers maps this small triangle to the triangle with vertices (0,0),(1,0),(1,1). The latter has no lattice points other than its three vertices. Replacing the two smaller hypotenuses by the larger one therefore adds no lattice points. The remaining parts follow by comparing their boundaries row by row or column by column. \square
Proposition 11.6. Denote the moments in the left and right records by (C_L,U_L,V_L,W_L) and (C_R,U_R,V_R,W_R), respectively, and put
Indeed, for fixed 1\le u<p, the vertical coordinate ranges from -q to -\lfloor qu/p\rfloor-1, whose sum is
## §3 The Contribution of an Edge
Let a primitive edge run from the exterior point $P=(X,Y)$ to the exterior point $Q=(X+p,Y-q)$. Its required boundary property is defined precisely as follows: every point of the translated lattice-point set $P+\mathcal T(p,q)$ other than $P,Q$ is an interior point. Primitivity means that the only lattice points on the edge are its two endpoints, both of which are exterior points.
**Proposition 11.7.** Suppose that the edge has the property above and that the last row processed by the preceding boundary lies above $Y$. The entire set of interior points it determines with vertical coordinate in $[Y-q,Y-1]$ is the union of the rectangle
$$
[1,X-1]\times[Y-q,Y-1]
\tag{11.13}
$$
and the translated set $P+\mathcal T(p,q)$, with the exterior endpoints $P,Q$ removed. Its cardinality is
$$
E_0(P;p,q)=(X-1)q+C-2,
\tag{11.14}
$$
and its total $xy$ weight is
$$
\begin{aligned}
E_1(P;p,q)={}&
\frac{X(X-1)}2\frac{q(2Y-q-1)}2\\
&+W+XV+YU+XYC\\
&-XY-(X+p)(Y-q).
\end{aligned}
\tag{11.15}
$$
**Proof.** First suppose that $q>0$. The point $(X,Y-1)$ belongs to the translated triangle and is neither endpoint, so it is an interior point. Both positive coordinates of every point in the rectangle are at most the corresponding coordinates of this point; hence the whole rectangle consists of interior points. That all points of the translated triangle except its endpoints are interior points is the assumed boundary property. The two sets have disjoint ranges of horizontal coordinates.
Conversely, take any interior point in the specified range of rows. If its horizontal coordinate is less than $X$, it belongs to the rectangle. If its horizontal coordinate is at least $X+p$, its vertical coordinate is at least $Y-q$, so the product of its coordinates is at least that of the exterior point $Q$, a contradiction. In the remaining case, its horizontal coordinate lies in $[X,X+p)$. The function $N/x$ is convex, and the segment joining the two exterior endpoints lies strictly above this curve on that interval. The interior point therefore lies below the segment and belongs to the translated triangle. This proves coverage in both directions.
The rectangle's weight separates into its horizontal and vertical factors; on the translated triangle the weight is
$$
(X+u)(Y+v)=XY+Xv+Yu+uv.
$$
It remains to subtract the two endpoints. If $q=0$, primitivity forces $p=1$; the rectangle is empty, and the degenerate triangle consists of its two endpoints. Removing them leaves zero contribution, so both formulas remain valid. $\square
The same boundary gives both D_0 and D_1, with each edge's contribution computed from a constant-dimensional moment record.
§4 Boundary Search, the Stack, and the Stopping Criterion
Construction 11.8. Start at
P=(\lfloor N/m\rfloor,m+1)
\tag{11.16}
This is an exterior point: writing N=km+r, where k=\lfloor N/m\rfloor\ge m and 0\le r<m, gives k(m+1)-N=k-r>0.
Initially the stack contains the directions (1,0),(1,1) from bottom to top, each with the moments in (11.7). The current accumulators are (Z_0,Z_1)=(0,0). Repeat the following procedure.
Pop the top direction L. As long as P+L remains an exterior point, add (11.14) and (11.15) to the accumulators and set P\leftarrow P+L. Repeat until the product of the next candidate's coordinates is at most N.
If the current value satisfies Y^3\le N, end the geometric procedure.
Let R be the current top of the stack. As long as the product of the coordinates of P+R is at most N, set L\leftarrow R, pop it, and take the new top as R.
Set M=L+R and compute its record using (11.10). If P+M is an exterior point, set R\leftarrow M, push it onto the stack, and repeat this step.
If the product of the coordinates of P+M is at most N, test
(X+p_M)^2q_R\ge Np_R.
\tag{11.17}
If the condition holds, end this rational-direction search and return to step 1; otherwise, set L\leftarrow M and return to step 4.
Here P+(p,q) always means (X+p,Y-q). All geometric tests use integer arithmetic. Search candidates may have Y-q\le0; such a candidate also enters the branch where the coordinate product is at most N, but it is not called an interior point under Definition 11.1. Actual advances accept only candidates whose coordinate product is greater than N. Since X+p>0, every endpoint of an edge actually emitted has a positive vertical coordinate.
Lemma 11.9. Equation (11.17) is a justified exclusion criterion. If the product of the coordinates of P+M is at most N and (11.17) holds, then starting from P+M and advancing along R, or along any direction downward and to the right that is steeper than R, cannot reach an exterior point with positive coordinates. The starting point may have a nonpositive vertical coordinate.
Proof. Put x_0=X+p_M and f(x)=N/x. Equation (11.17) is equivalent to
-q_R/p_R\le f'(x_0)=-N/x_0^2.
The function f is convex, so for x\ge x_0 it lies above its tangent at x_0. The starting point is no higher than f(x_0), and the slope of the ray under consideration is at most the tangent slope. The entire ray therefore lies no higher than the curve. \square
Proposition 11.10. Every edge emitted by Construction 11.8 satisfies the hypotheses of Proposition 11.7, and the processed row intervals are pairwise disjoint. At termination, the processed rows are exactly Y,Y+1,\ldots,m.
Proof. First establish the convexity fact repeatedly used in the search. If P=(X,Y) is an exterior point and Q=(X+a,Y-b) satisfies a>0 with coordinate product at most N, then
The first inequality uses Y>N/X and Y-b\le N/(X+a); the second uses convexity. Consequently, starting from Q and advancing along (a,-b) or any steeper direction downward and to the right always stays no higher than the hyperbola. This conclusion also permits a nonpositive vertical coordinate for Q.
The search invariant is as follows: L,R are adjacent, the coordinate product of P+L is at most N, and P+R is an exterior point; viewed from P, all lattice points with positive coordinates in directions no shallower than L are interior points. If the mediant candidate P+M has coordinate product at most N, any integer direction between L and M can be written as uL+vM, where u,v\ge1. Starting from P+M, the remaining direction uL+(v-1)M is no shallower than M, so the convexity fact above shows that this point also lies below the curve. The same holds for subsequent points on the ray in direction M. Thus, when setting L\leftarrow M, the entire newly enlarged region of steep directions has been excluded. The same argument applies when step 3 pops a right-hand candidate whose coordinate product is at most N. If P+M is an exterior point, only R is replaced by M, while the old, shallower direction is retained in the stack. The invariant is therefore preserved.
When (11.17) holds, any integer direction lying strictly below the ray in direction R can, by the integer-basis property, be written as \alpha L+\beta R with \alpha\ge1. If \beta\le0, it belongs to the already excluded region of steep directions. If \beta\ge1, it equals
M+(\alpha-1)L+(\beta-1)R.
By Lemma 11.9, starting from P+M and following the remaining direction, which is no shallower than R, cannot encounter an exterior point. Thus there are no exterior lattice points strictly below the entire rightward ray in direction R. Since R is primitive, one unit segment in this direction has no other lattice points on its edge; all points of the translated triangle except its two endpoints are therefore interior points.
Initialization and repeated advances must also be checked. Initially P=(k,m+1), where k=\lfloor N/m\rfloor\ge m. Integer points strictly below the initial ray of slope -1 have the form (k+u,y), where u\ge0 and y\le m-u. Whenever both coordinates are positive,
(k+u)y\le(k+u)(m-u)=km+u(m-k)-u^2\le N.
The initial edge therefore has the required property. During repeated advances along a direction already established, lattice points farther to the right and strictly below the line still belong to the previously excluded set. Once the next point on the ray has coordinate product at most N, the convexity fact above also excludes all subsequent points on the ray, restoring the full invariant for the next search.
For every edge actually emitted, Proposition 11.7 proves that the triangle and the rectangle to its left count exactly all the relevant interior points; the exterior right endpoint rules out omissions to the right. Each edge changes the row index from Y to Y-q and counts only [Y-q,Y-1]. Induction from the initial row index m+1 gives the disjointness and coverage of the row intervals. \square
Stack boundary conditions. The horizontal sentinel (1,0) at the bottom of the stack is never popped by step 3: the current point satisfies XY>N, so (X+1)Y>N. When R is the sentinel, (11.17) becomes 0\ge N, which is impossible. A search can therefore end only after at least one nonhorizontal direction has been pushed. On returning to step 1, the top to be popped is always above the sentinel. Thus neither access to the top of the stack can encounter an empty stack.
Termination. If R is the horizontal sentinel, adjacency forces q_L=1. Before the cutoff condition is met, Y\ge2. Repeatedly setting L\leftarrow L+R keeps the vertical difference equal to 1 while increasing the horizontal difference, and eventually produces a candidate whose coordinate product is greater than N, pushing a nonhorizontal direction. Thereafter, each exterior candidate sets R\leftarrow L+R and strictly increases its vertical difference; the exterior-point condition requires this difference to be less than Y, so only finitely many such updates can occur. With a fixed nonhorizontal R, consecutive candidates on the non-exterior branch strictly increase the horizontal difference and eventually satisfy (11.17). Each direction search is therefore finite. At the end of a search, the direction on top of the stack leads to an exterior point, so the next iteration successfully advances at least once, decreasing the positive integer Y by at least one. The entire geometric procedure is therefore finite as well.
Remark. The stack retains adjacent directions obtained in earlier searches for reuse in the next search; (11.17) determines where each search stops.
Theorem 11.11. After the geometric procedure ends, add the remaining rows:
Proof. Together, the geometric procedure and the remaining rows count exactly all interior points with y\le m. Exchanging the horizontal and vertical coordinates gives the part with x\le m. These two parts cover xy\le N and intersect in [1,m]^2. Summing the respective weights over this square gives the subtracted terms. \square
§5 An Executable Integer Construction
The following Python program implements the procedure above using arbitrary-precision integers. The input is N\ge1, and the output is the pair of exact integers (D_0(N),D_1(N)). The next section analyzes its complexity by counting elementary arithmetic operations.
from math import isqrt
def merge(L, R):
p, q, C, U, V, W = L
r, s, D, E, F, G = R
assert q * r - p * s == 1
A = p * (p - 1) // 2
B = -s * (2 * q + s + 1) // 2
return (p + r, q + s,
C + D + p * s - 1,
U + E + p * D + s * A - p,
V + F - q * D + p * B + q,
W + G + p * F - q * E - p * q * D + A * B + p * q)
def edge_weight(X, Y, R):
p, q, C, U, V, W = R
rectangle = X * (X - 1) // 2 * (q * (2 * Y - q - 1) // 2)
return ((X - 1) * q + C - 2,
rectangle + W + X * V + Y * U + X * Y * C
- X * Y - (X + p) * (Y - q))
def hyperbola_moments(N):
m = isqrt(N)
X, Y = N // m, m + 1
stack = [(1, 0, 2, 1, 0, 0), (1, 1, 3, 1, -2, -1)]
Z0 = Z1 = 0
def outside(R):
return (X + R[0]) * (Y - R[1]) > N
while True:
L = stack.pop()
while outside(L):
E0, E1 = edge_weight(X, Y, L)
Z0 += E0
Z1 += E1
X += L[0]
Y -= L[1]
if Y ** 3 <= N:
break
R = stack[-1]
while not outside(R):
L = R
stack.pop()
R = stack[-1]
while True:
M = merge(L, R)
if outside(M):
R = M
stack.append(R)
elif (X + M[0]) ** 2 * R[1] >= N * R[0]:
break
else:
L = M
for y in range(1, Y):
q = N // y
Z0 += q
Z1 += y * q * (q + 1) // 2
return 2 * Z0 - m * m, 2 * Z1 - (m * (m + 1) // 2) ** 2
Example 11.12. For N=10, the program returns (27,170). Direct classification by the product also gives
Computing both moments simultaneously increases each direction record to a constant size and does not change the geometric branches.
§6 Operation Counts and Region Counts
Let B=\lfloor N^{1/3}\rfloor. The construction switches to direct enumeration when Y\le B, so processing the final rows requires O(B) operations. The geometric part consists of edge advances, direction searches, and stack operations.
Let E(N) be the number of advances in step 1 and J(N) the number of mediant directions formed in step 4. The program's total operation count is
Each advance and merge uses only a constant number of operations. Every push after initialization corresponds to a mediant-direction merge, and each record is popped at most once, so all stack operations are also controlled by J(N)+2. Each advance along the same direction is counted separately in E(N). Since every step decreases Y by at least one, E(N)\le m.
We next estimate the number of regions produced by subdivision in rational directions in tangent-region algorithms.
In a subdivision into regions by rational directions, nontrivial processing can be assigned to adjacent fractions a/b>c/d>0, where ad-bc=1. The two corresponding tangency points have horizontal coordinates \sqrt{Nb/a} and \sqrt{Nd/c}. A region with nonzero width in both integer basis directions must satisfy
Hence 4abc^2(b+d)^2\le N. After substituting c=z/b and d=(z+1)/a, the left-hand side is at least 8z^3, so z=O(N^{1/3}). For a given z, choosing b\mid z and a\mid z+1 uniquely determines c,d. The required number is therefore at most
\sum_{z\le C N^{1/3}}\tau(z)\tau(z+1)
\le\frac12\sum_{z\le C N^{1/3}}
\bigl(\tau(z)^2+\tau(z+1)^2\bigr).
\tag{11.23}
Let d_4(n) be the number of ways to express n as an ordered product of four positive integers. Comparing prime-power values using
$$
\sum_{n\le X}d_4(n)
\le X\sum_{a,b,c\le X}\frac1{abc}
\le X(1+\log X)^3.
$$
Substitute this into (11.23). $\square
Lemma 11.13 bounds the number of regions associated with adjacent fractions. The program's time and space are described by (11.20) and O(J(N)+1), respectively. Maintaining four moments increases the cost of the same geometric procedure by only a constant factor.
Source. Printed pages 108–109 of Zhu Zhenting's original paper give the region count involving \log^3 N; page 110 discusses a geometric comparison with the polygonal-chain method.
When the answer is required modulo an integer, additions and multiplications involving C,U,V,W,Z_0,Z_1 may be reduced modulo it. Coordinates, order comparisons, divisibility tests, and (11.17) must always be evaluated over the integers. Every factor of one-half in the formulas comes from an integer summation formula and should either be canceled over the integers first or interpreted using the inverse of 2 in a residue ring where it is invertible.
This chapter makes D_0,D_1 explicit executable subroutines. An implementation should cache results for repeated arguments \lfloor N/k^2\rfloor. For small arguments, prefix sums of n^t\tau(n) can be precomputed directly, avoiding geometric searches.
Calling the program separately for each term gives total cost
where T is given by (11.20), and the initial O(\sqrt N) includes the Möbius sieve. Using the ordinary hyperbola subroutine from the preceding chapter gives total bound O(\sqrt N\log(N+1)).
Corollary 11.14. Suppose that an exact hyperbola subroutine uses O(x^{1/3}\log^3(x+1)) arithmetic operations per call. Then term-by-term evaluation of (11.24) has total cost O(\sqrt N), including the time for a linear sieve of the Möbius function.
Proof. Group the indices k by \sqrt N/2^{j+1}<k\le\sqrt N/2^j. Such a group has at most O(\sqrt N/2^j) elements, and every argument is at most 2^{2j+2}. The assumed subroutine bound within this group is O(2^{2j/3}(j+1)^3), so the total cost over all groups is at most
The linear sieve for the Möbius function satisfies the same time bound. \square
Editorial Notes
This text reconstructs Su Ziran (minstdfx), Cirno's Perfect Number Theory Classroom: Summer-Term Course on Algorithmic Competitions, file version 20260619-2 ver., comprising 128 pages. Its chapter organization and proof style follow the Bourbaki-style reconstruction of the introductory data-structures supplement, 数据结构入门补充材料_布尔巴基式重构.md. Informal explanations, diagrams, and code from the original notes have been recast as explicit input conditions, states, transformations, and correctness propositions, reordered by mathematical dependence. To develop algorithms only sketched in the original, the text adds local recurrences, the inverse process of the prime sieve, interval accumulation for sparse convolution, and a geometric construction for lattice-point summation.
Correspondence with the Original
All page numbers below refer to physical pages of the PDF.
Pages in the original notes
Content
Location in this text
3–16, 20–27
Divisibility, greatest common divisors, unique factorization, congruences, Bézout, CRT, nonnegative representations, and GCD Table
BSGS, exBSGS, exponential equations, Miller–Rabin, and Pollard–Rho
Chapter III
63–71, 75–77
Arithmetic functions, convolution, inversion, Bell series, and Dirichlet generating functions
Chapter IV
51–62, 72–74
Quotient blocks, the hyperbola identity, and five groups of summation examples
Chapter V
79–88
The Eratosthenes sieve, segmented sieves, the linear sieve, and a digit-sum application
Chapter VI
90–105
Convolution of quotient-value representations, the Du Jiao sieve, and weighted GCD summation
Chapter VII
106–110, 118
Prime-weight tables, Min_25 reconstruction, and the inverse process for completely multiplicative functions
Chapter VIII
111–118
The PN sieve, local differences, and sparse convolution at all quotient values
Chapter IX
119–123
Divisibility matrices, weighted elimination, and the GCD/LCM identity for multiplicative functions
Chapter X
124
Fast counting and weighted summation of lattice points beneath a hyperbola
Chapter XI
1–2, section-divider pages, 125–128
Title, contents, problem lists, acknowledgments, and references
Title, chapter organization, and these notes
Corrections and Additions
The greatest common divisor is defined as the nonnegative generator of an integer ideal, including the all-zero family. The least common multiple, in the range used here, is the least positive common multiple. Primes, composite numbers, and units are distinguished; 0,\pm1 are not classified as composite. Divisor pairing is restricted to positive integers.
Cancelling a common factor in a congruence also changes the modulus. ExCRT merging maintains the complete solution class. GCD Table checks candidates against the GCD equalities, treating a bounded starting position and an entire segment contained in the table separately.
Euler exponent reduction without coprimality is proved componentwise for the full prime-power factors, including the condition that the exponent has reached the threshold. Zero exponents, modulus one, and noninvertible denominators are treated separately. The ex-Lucas construction distinguishes a factorial with all factors of p removed from a product formed by omitting the multiples of p.
The exBSGS construction retains the coefficient accumulated by multiplying by a/g in each round and first tests the current smallest exponent. A single invariant proves the stripping step, the change of modulus, minimality of the solution, and termination.
The modulus of the exponent ring for a discrete logarithm is the group order; in CF1106F it is p-1, and the linear congruence is solved for this general modulus. Primality testing is presented with one-sided correctness, the random error theorem, and finite-range base sets. Pollard–Rho returns a factor when 1<d<n; failed batches are replayed or the parameters are changed.
The constant-one function on pages 65 and 67 is consistently denoted by \mathbf1, and the identity function by \operatorname{id}. The local factors in the divisor-sum formula are corrected to geometric sums; \prod_p(\nu_p(n)+1) counts divisors. The domain counted by \varphi is specified as a finite complete residue system, and \mu(1)=1 is stated explicitly.
Inversion applies to general arithmetic functions; the corresponding weighted identities use complete multiplicativity. Sums over multiples are finitely truncated. Generating functions are constructed as formal series, and convergence of real series is proved where they are used.
With the original definition of the double prefix sum on page 74, the correct identity is F_k(x)=T_k(2x)-2T_k(x). The text proves it by counting the coefficient corresponding to each possible sum of an ordered pair, restoring the missing factor 2. Preprocessing modulo 2^{32} uses no division.
Prime detection on an interval and complete factorization on an interval use different starting points. In the Haitang example, the candidate conditions are S(m)=s, m>s, and m\mid n-s. The entire short interval must be factored, and the checking cost depends on the total number of divisors of all its elements.
The linear-sieve branch on page 85 is corrected to ask whether the newly multiplied prime p divides the old index i, with the result stored at ip. Computations over general coefficient rings use the coprime cofactor and local data; their complexity includes the cost of obtaining prime-power data.
Given two quotient-value tables, direct hyperbola evaluation of a general convolution uses O(N^{3/4}) operations; when the smaller prefix values admit linear preprocessing, truncation gives O(N^{2/3}). The Du Jiao sieve uses a convolution factor with invertible first value and quickly evaluable prefixes.
The prime-weight sieve updates in increasing prime order and decreasing quotient-value order. Recovering completely multiplicative prefixes reverses both orders through the inverse triangular transformation. The cost of Min_25 recursion is counted by its nodes.
The auxiliary function actually recovered in the PN example is h; the end of page 114 incorrectly labels it g. For the completely multiplicative choice, the local difference formula is proved by a telescoping identity. Accumulating equal contributions over intervals of ranks recovers all quotient values in O(\sqrt N\log N) time.
The weighted GCD matrix is factored through a unit lower triangular integer matrix, including for composite moduli. The row multipliers used in elimination, the diagonal, and the determinant all follow from the same factorization.
The last problem's double sum is first reduced to the square of one prefix sum, then subjected to squarefree inversion. Chapter XI develops the inner lattice-point algorithm and calculates the total cost of the outer Möbius sum.
Problem Lists from the Original Notes
Page 125 of the original PDF provides the following lists for further practice:
gza's Recreational Number Theory 1
gza's Recreational Number Theory 2
Leasier's Number Theory Problem List
CF2081G2.
The original notes acknowledge Nacly_Fish, luogu_gza, dXqwq, Larunatrecy, and a contributor from Bashu Secondary School. Their references include OI Wiki, Zhou Kangyang's Selected Topics in Number Theory, and several solutions to the original problems. Additional algorithmic sources used in this text are cited near the relevant discussion, distinguishing material from the lecture notes, supplementary proofs, and externally invoked results.
注。 一轮用 O(\log n) 次模乘。Rabin 的强伪素数计数定理断言:对任意奇合数 n,在 1,\ldots,n-1 中通过式 (3.17) 的底数至多占四分之一,见 M. O. Rabin,Probabilistic Algorithm for Testing Primality,1980,定理 1。因此,独立均匀选取 t 个底数时,固定合数全部通过的概率至多为 4^{-t}。该概率针对固定合数与随机底数计算。
另有经典的确定性范围结果:对 2\le n<2^{64},依次检验底数
2,3,5,7,11,13,17,19,23,29,31,37
\tag{3.18}
足以确定素性。其依据是前十二个素数底数共同的最小强伪素数为 318665857834031151167461>2^{64},见 J. Sorenson 与 J. Webster,Strong Pseudoprimes to Twelve Prime Bases,定理 1.1。实现中先处理小于等于 37 的输入,之后这些底数均在 [1,n-1] 内;或者对底数取模并跳过零余数。无符号 64 位输入的模乘采用更宽的乘积表示或专门的模乘实现。
§6 从碰撞提取因子
构造 3.17(Pollard–Rho 的单次尝试)。 对奇合数 n,选取整数 c 与初值 x_0,在 \mathbf Z/n\mathbf Z 中置
证明。 一个整数乘积与 n 互素,当且仅当每个因子与 n 互素:正向因为每个因子整除乘积,反向由素因子判别得到。因此 d=1 时跳过整块不遗漏因子。1<d<n 时,无论 d 来自一个还是多个差值,它本身都是合法因子。d=n 则不能断定每个差值都与 n 有最大公约数 n;例如 n=15、差值为 3,5 时,积为零而各自可分解。逐项回放可恢复这些被乘积合并的因子。\square
注。 每块的 Q 从 1 重新开始;保存块首的轨道状态与块长即可回放。批处理通常每 b 个差值调用一次最大公约数,失败回放时增加调用。积在每一步模 n 约简,保持式 (3.21) 的最大公约数。某个差值为零时,批量积为零,进入失败回放。
构造 3.21(Brent 分段轨道)。 固定 F(x)=x^2+c\pmod n 与块长上限 b\ge1。令 y=x_0、r=1。一次外层过程如下。
保存 x=y,再让 y 连续前进 r 步。
在随后的 r 步中,每前进一步就产生差值 x-y;每至多 b 步组成一块,用构造 3.20 检验。块的起点、实际步数都须保存,以便回放。
这里“前进一步”指赋值 y\leftarrow F(y)。所有减法及乘积均可立即规范到模 n 的余数。
命题 3.22。 构造 3.21 的每次返回均为有效分解。对任意 p\mid n,若模 p 的轨道有长度为 \mu 的前导部分及长度为 \lambda 的循环部分,则当某一段的固定点 x 已落在循环中且 r\ge\lambda 时,该段产生的差值至少有一个被 p 整除。
证明。 返回正确性由构造 3.20 得到。固定点 x 已处于循环时,后续任何连续 \lambda 个轨道点都会经过 x 的模 p 剩余类。该段检测连续 r\ge\lambda 个点,故至少出现一次模 p 碰撞。随着 r 倍增,固定点的轨道下标不断增加,最终越过 \mu;只要尚未重启,也最终满足 r\ge\lambda。\square
注。 多个素因子的碰撞同时发生,或模 n 的轨道过早闭合时,可能得到 d=n,此时重启。Brent 分段使固定点在一整段内保持不变,便于批量乘积与回放;它调整运算常数与最大公约数调用频率,迭代量级仍按前述随机模型作启发式估计。返回因子可能只含某个素因子的部分重数,递归分解剩余商即可恢复其余重数。
第四章 算术函数与卷积
§1 以正整数乘法为下标的代数
本章固定含幺交换环 R。整数系数通过唯一的含幺环同态 \mathbf Z\to R 解释;除非另行指出,所有约数均为正约数。环中的除法仅表示乘以已知存在的逆元。
证明。 每次除法均为整数精确除法。一个素因子 p 被处理时,其在 x 中的全部次数被除去;此前除去其他素因子不改变该次数。最终若 a_x>1 仍为合数,它必有不超过 \sqrt{a_x}\le\sqrt U 的素因子,与所有这类素数已被除尽矛盾。残余素因子的平方也不可能整除 x,否则该素因子不超过 \sqrt U,仍会与已被除尽矛盾。\square
从区间中的第一个倍数开始,使 x=p 时的因子 p 也得到记录。对 x=1 不执行除法,其因子表为空。
证明。 任一生成对满足 p\le\operatorname{lpf}(i),因此 ip 的最小素因子正是 p;所写值正确。反之,给定合数 x,取其规范生成对 (i,p)。由于 i<x,扫描到 x 之前已处理 i;且 p\le\operatorname{lpf}(i)\le i,所以 p 已进入素数表,且满足内层循环条件,故 x 必被生成。任何生成 x 的对都必须具有 p=\operatorname{lpf}(x),从而 i=x/p,所以生成唯一。
尚未被生成的 i 因而恰为素数。内层循环的有效迭代次数等于合数个数,另有每个外层下标至多一次终止条件检查;初始化与素数追加亦为线性,故总时间为 O(N)。\square
常见实现写成先生成 ip,然后在 p\mid i 时立即退出。因素数升序且首次整除 i 的素数恰为 \operatorname{lpf}(i),该写法与式 (6.9) 等价。
正是讲义 P6384 所用的消元结果。若仅用基本行变换实现,则按 i 递增,对 k=2,\ldots,\lfloor n/i\rfloor,从第 ki 行减去第 i 行的 k 倍;倍数 k 与原矩阵的行权重 i 对应。讲义先除去行列权重再消元的办法在有理数域中同样成立;式 (10.4) 本身是整数恒等式,可直接映入模环。
搜索的不变量如下:L,R 相邻,P+L 的坐标乘积不大于 N,P+R 为外点;从 P 看去,不比 L 平缓的全部正整点均为内点。若中间候选 P+M 的乘积不大于 N,则 L 与 M 之间的任一整数方向均可写为 uL+vM,其中 u,v\ge1。从 P+M 出发,剩余方向 uL+(v-1)M 不比 M 平缓,由前述凸性事实可知该点仍在曲线下。M 射线上的后续点也一样。因此令 L\leftarrow M 时,新扩大的整个陡方向区域都已排除。步骤 3 弹出一个乘积不大于 N 的右候选时,应用同一论证;若 P+M 为外点,则仅将 R 换为 M,旧的较平缓方向保存在栈中。不变量由此保持。
from math import isqrt
def merge(L, R):
p, q, C, U, V, W = L
r, s, D, E, F, G = R
assert q * r - p * s == 1
A = p * (p - 1) // 2
B = -s * (2 * q + s + 1) // 2
return (p + r, q + s,
C + D + p * s - 1,
U + E + p * D + s * A - p,
V + F - q * D + p * B + q,
W + G + p * F - q * E - p * q * D + A * B + p * q)
def edge_weight(X, Y, R):
p, q, C, U, V, W = R
rectangle = X * (X - 1) // 2 * (q * (2 * Y - q - 1) // 2)
return ((X - 1) * q + C - 2,
rectangle + W + X * V + Y * U + X * Y * C
- X * Y - (X + p) * (Y - q))
def hyperbola_moments(N):
m = isqrt(N)
X, Y = N // m, m + 1
stack = [(1, 0, 2, 1, 0, 0), (1, 1, 3, 1, -2, -1)]
Z0 = Z1 = 0
def outside(R):
return (X + R[0]) * (Y - R[1]) > N
while True:
L = stack.pop()
while outside(L):
E0, E1 = edge_weight(X, Y, L)
Z0 += E0
Z1 += E1
X += L[0]
Y -= L[1]
if Y ** 3 <= N:
break
R = stack[-1]
while not outside(R):
L = R
stack.pop()
R = stack[-1]
while True:
M = merge(L, R)
if outside(M):
R = M
stack.append(R)
elif (X + M[0]) ** 2 * R[1] >= N * R[0]:
break
else:
L = M
for y in range(1, Y):
q = N // y
Z0 += q
Z1 += y * q * (q + 1) // 2
return 2 * Z0 - m * m, 2 * Z1 - (m * (m + 1) // 2) ** 2