Problem 1021: Dirichlet Drama
View on Project EulerProject Euler Problem 1021 Solution
The function f(n) = sum over d | n of mu(n/d) phi(d) is multiplicative with f(1) = 1, f(p) = p - 2 and f(p^k) = p^(k-2) (p-1)^2 for k >= 2, so n/f(n) is a product of one local factor per prime, and that factor depends on the exponent only through whether it is 1, giving p/(p-2), or larger, giving p^2/(p-1)^2. At the prime 2 only the factors 1 and 4 exist, because f(2) = 0. Taking the primes in increasing order makes integrality testable one factor at a time, and two different choices never give the same value, so a depth-first search that extends an integer V by p/(p-2) when p - 2 divides V and by p^2/(p-1)^2 when (p-1)^2 divides V meets every value exactly once: 53589 values for r = 40320, found in under a hundredth of a second. Implementations are available in C++, Python and Java.
Detailed mathematical approach
Problem Summary
Let \(\mu\) be the Möbius function and \(\varphi\) Euler's totient function. The problem defines
$$f(n)=\sum_{d\mid n}\mu(n/d)\varphi(d),$$
and, for a number \(r\), lets \(S(r)\) be the sum of all distinct integer values that the expression \(r\,n/f(n)\) can take over the positive integers \(n\). It gives \(S(1/4)=16\) and \(S(1)=208\) and asks for \(S(40\,320)\); \(r\) is a positive rational number in both examples and in the value asked for, and is taken to be positive throughout. [1]
The expression \(r\,n/f(n)\) is an integer only rarely, and surprisingly few integers occur: for \(r=1\) there are exactly sixteen of them, and they add up to the \(208\) of the statement. Three observations turn the search for them into a short walk through the primes. First, \(f\) is multiplicative with \(f(1)=1\), \(f(p)=p-2\) and \(f(p^k)=p^{k-2}(p-1)^2\) for \(k\ge2\), so \(n/f(n)\) is a product of one factor for each prime dividing \(n\), and that factor depends on the exponent only through whether the exponent is \(1\) or larger: it is \(p/(p-2)\) in the first case and \(p^2/(p-1)^2\) in the second. The prime \(2\) is the exception, because \(f(2)=0\): a number divisible by \(2\) exactly once has no ratio at all, so the prime \(2\) contributes either nothing or the factor \(4\). Second, the denominator of the local factor of \(p\) is built from primes smaller than \(p\) while its numerator is a power of \(p\); if the factors are multiplied in increasing order of their primes, starting from an integer, the running product is an integer at every step precisely when the final product is an integer. Third, two different combinations of these factors never produce the same value, so repetitions need not be recognised at all: the walk may simply add up everything it meets.
What remains is a depth-first search. It keeps an integer \(V\) and the largest prime used so far, counts \(V\) itself as one of the values, and extends \(V\) by \(p/(p-2)\) for every larger prime \(p\) with \(p-2\mid V\) and by \(p^2/(p-1)^2\) for every larger prime \(p\) with \((p-1)^2\mid V\). For \(r=40\,320\) this search visits \(53\,589\) integers; the largest of them is \(2\,288\,978\), the largest prime it uses is \(1\,133\,641\), and the longest chain consists of fifteen local factors.
Mathematical Approach
Section 1 determines \(f\) on prime powers. Section 2 shows that \(n/f(n)\) is a product of local factors with three possibilities per prime. Section 3 proves that increasing prime order makes integrality testable one factor at a time, Section 4 that different choices give different values, and Section 5 that the search is finite. Section 6 works through the two published examples completely, and Section 7 describes the search for \(r=40\,320\). Throughout, \(v_p(x)\) denotes the exponent of the prime \(p\) in the rational number \(x\), so that \(v_p(x)\) is negative when \(p\) divides the denominator of \(x\) in lowest terms, and \(x\) is an integer exactly when \(v_p(x)\ge0\) for every prime \(p\). The number \(r\) is positive throughout, as it is in both published examples and in the value the problem asks for, and \(v_p\) is applied only to numbers different from \(0\).
1. The function \(f\)
The Möbius function is \(\mu(1)=1\), \(\mu(n)=(-1)^k\) when \(n\) is a product of \(k\) distinct primes, and \(\mu(n)=0\) when \(n\) is divisible by the square of a prime. [2] Euler's totient function \(\varphi(n)\) counts the integers from \(1\) to \(n\) that are coprime to \(n\), and \(\varphi(p^k)=p^{k-1}(p-1)\) for a prime power. [3] The sum in the definition of \(f\) is the Dirichlet convolution of \(\mu\) and \(\varphi\), [4] and by Möbius inversion the definition is equivalent to
$$\varphi(n)=\sum_{d\mid n}f(d),$$
which is the form the program uses when it computes \(f\) from scratch in its self-test. [5]
A Dirichlet convolution of two multiplicative functions is multiplicative, and both \(\mu\) and \(\varphi\) are multiplicative, so \(f\) is multiplicative as well: \(f(1)=1\), and \(f(ab)=f(a)f(b)\) whenever \(a\) and \(b\) are coprime. [4][6] It is therefore enough to know \(f\) on prime powers. For \(n=p^k\) only the divisors \(d=p^k\) and \(d=p^{k-1}\) contribute to the sum, because \(\mu(p^j)=0\) for \(j\ge2\), and their coefficients are \(\mu(1)=1\) and \(\mu(p)=-1\):
$$f(p^k)=\varphi(p^k)-\varphi(p^{k-1})\qquad(k\ge1).$$
With \(\varphi(1)=1\) this gives \(f(p)=(p-1)-1=p-2\), and for \(k\ge2\)
$$f(p^k)=p^{k-1}(p-1)-p^{k-2}(p-1)=p^{k-2}(p-1)^2.$$
Among the prime powers, \(f\) vanishes only at \(p^k=2\): the first formula gives \(0\) only for \(p=2\), and \((p-1)^2\) is never \(0\) for a prime. Since \(f\) is multiplicative, \(f(n)=0\) holds exactly for those \(n\) that are divisible by \(2\) but not by \(4\), and for every other \(n\) the ratio \(n/f(n)\) is a well-defined positive rational number. The values \(f(1),f(2),f(3),\dots\) are the terms of A007431 of the OEIS from the index \(1\) on. [7]
The table lists the first values. Only five integers occur among the first twenty-four ratios, namely \(1\), \(3\), \(4\), \(5\) and \(12\), and two of them occur more than once: the ratio \(4\) at \(n=4\), \(n=8\) and \(n=16\), and the ratio \(12\) at \(n=12\) and \(n=24\).
| \(n\) | \(f(n)\) | \(n/f(n)\) | \(n\) | \(f(n)\) | \(n/f(n)\) |
|---|---|---|---|---|---|
| \(1\) | \(1\) | \(1\) | \(13\) | \(11\) | \(13/11\) |
| \(2\) | \(0\) | — | \(14\) | \(0\) | — |
| \(3\) | \(1\) | \(3\) | \(15\) | \(3\) | \(5\) |
| \(4\) | \(1\) | \(4\) | \(16\) | \(4\) | \(4\) |
| \(5\) | \(3\) | \(5/3\) | \(17\) | \(15\) | \(17/15\) |
| \(6\) | \(0\) | — | \(18\) | \(0\) | — |
| \(7\) | \(5\) | \(7/5\) | \(19\) | \(17\) | \(19/17\) |
| \(8\) | \(2\) | \(4\) | \(20\) | \(3\) | \(20/3\) |
| \(9\) | \(4\) | \(9/4\) | \(21\) | \(5\) | \(21/5\) |
| \(10\) | \(0\) | — | \(22\) | \(0\) | — |
| \(11\) | \(9\) | \(11/9\) | \(23\) | \(21\) | \(23/21\) |
| \(12\) | \(1\) | \(12\) | \(24\) | \(2\) | \(12\) |
2. The local factors
Let \(n\) be a positive integer that is not twice an odd number, and write it as a product of prime powers \(p^k\) with \(k=v_p(n)\ge1\). Since \(f\) is multiplicative,
$$\frac{n}{f(n)}=\prod_{p^k\|n}\frac{p^k}{f(p^k)},$$
where \(p^k\|n\) means that \(p^k\) is the exact power of \(p\) in \(n\). By Section 1 the single factor is \(p/(p-2)\) when \(k=1\), and when \(k\ge2\) it is
$$\frac{p^k}{p^{k-2}(p-1)^2}=\frac{p^2}{(p-1)^2}.$$
The exponent has disappeared from the second case: all exponents above \(1\) give the same factor. Each prime therefore offers at most three possibilities, which will be called its local factors:
$$1,\qquad \frac{p}{p-2},\qquad \frac{p^2}{(p-1)^2},$$
according to whether \(p\) does not divide \(n\), divides \(n\) exactly once, or divides \(n\) at least twice. At \(p=2\) the middle possibility does not exist, since it would be \(2/0\); the prime \(2\) contributes \(1\) or \(4\). A number \(n\) is thus described, as far as the ratio is concerned, by one admissible choice for every prime, all but finitely many of them equal to \(1\); and conversely every such choice is realised by some \(n\), for instance by the product of \(p\) over the primes that are to divide \(n\) exactly once and of \(p^2\) over the primes that are to divide \(n\) at least twice. The set of values of \(n/f(n)\) is exactly the set of these products.
| \(p\) | \(p/(p-2)\) | \(p^2/(p-1)^2\) |
|---|---|---|
| \(2\) | — | \(4\) |
| \(3\) | \(3\) | \(9/4\) |
| \(5\) | \(5/3\) | \(25/16\) |
| \(7\) | \(7/5\) | \(49/36\) |
| \(11\) | \(11/9\) | \(121/100\) |
| \(13\) | \(13/11\) | \(169/144\) |
For every odd prime both non-trivial factors exceed \(1\), and the first exceeds the second, because
$$\frac{p}{p-2}-\frac{p^2}{(p-1)^2}=\frac{p}{(p-2)(p-1)^2}\gt0.$$
The identity follows from \(p(p-1)^2-p^2(p-2)\)\({}=p^3-2p^2+p-(p^3-2p^2)\)\({}=p\). Every local factor is therefore at least \(1\), and a product of local factors is \(1\) only when every factor is \(1\). In particular \(r\,n/f(n)\ge r\) for every positive \(r\) and every admissible \(n\), with equality only for \(n=1\).
3. Integrality one prime at a time
A local factor need not be an integer, and the partial products of a product of local factors need not be integers either, even when the whole product is. The factor \(9/4\) of the prime \(3\) is not an integer, but \(4\cdot\frac94=9\) is: the factor of the prime \(2\) clears the denominator of the factor of the prime \(3\). The order in which the primes are taken therefore matters, and increasing order is the order that works.
Let \(V_0\) be the integer the walk starts at, and let \(p_1\lt p_2\lt\dots\lt p_m\) be the primes whose local factor differs from \(1\) and is applied after that start. Write the factor of \(p_i\) as \(a_i/b_i\), where \(a_i\) is \(p_i\) or \(p_i^2\) and \(b_i\) is \(p_i-2\) or \((p_i-1)^2\). Two facts about these fractions are all that is needed: the numerator \(a_i\) is a power of \(p_i\), and every prime factor of the denominator \(b_i\) is smaller than \(p_i\), since both \(p_i-2\) and \(p_i-1\) are. Consider the partial products
$$V_j=V_0\cdot\frac{a_1}{b_1}\cdots\frac{a_j}{b_j}\qquad(0\le j\le m).$$
Fix a prime \(q\) and follow \(v_q(V_j)\). The numerators raise it at one index at most — at the index \(t\) with \(p_t=q\), if \(q\) occurs among the \(p_i\) at all, where it grows by \(1\) or by \(2\) — and the denominators lower it only at indices \(i\) with \(p_i\gt q\), which are indices above \(t\). So \(v_q(V_j)=v_q(V_0)\) for every \(j\lt t\), while from the index \(t\) onwards the exponent never rises again, which gives \(v_q(V_j)\ge v_q(V_m)\) for every \(j\ge t\). If \(q\) does not occur among the \(p_i\), the exponent never rises at all, and \(v_q(V_j)\ge v_q(V_m)\) holds for every \(j\).
Lemma 1. Let the starting value \(V_0\) be a positive integer. Then \(V_m\) is an integer if and only if all of \(V_0,V_1,\dots,V_m\) are integers.
One direction is trivial. For the other, let \(V_m\) be an integer, and let \(q\) be a prime and \(j\) an index. If \(q\) occurs among the \(p_i\) and \(j\lt t\), then \(v_q(V_j)=v_q(V_0)\ge0\), because \(V_0\) is an integer. In every other case \(v_q(V_j)\ge v_q(V_m)\ge0\). As \(q\) was arbitrary, \(V_j\) is an integer.
The lemma says that integrality can be tested while the factors are being applied, which is what makes a depth-first search possible: once the starting value is an integer, a continuation whose value is not an integer may be abandoned at once, together with everything below it, because nothing later will repair it. What remains is to produce an integral starting value. The program accepts an \(r\) with a positive numerator and a denominator of \(1\), \(2\) or \(4\), which covers both published examples and the required \(S(40\,320)\). For such an \(r\) the prime \(2\) is the only prime that can divide the denominator, and the only numerator that can cancel a power of \(2\) is the \(4\) of the prime \(2\) itself; so if \(r\) is not an integer the walk must begin with that factor, at the integer \(4r\), and if \(r\) is an integer it may begin either at \(4r\) or at \(r\). In both cases the walk starts at an integer, the choice at the prime \(2\) is already contained in that start, and the primes \(p_1,\dots,p_m\) of the lemma are all odd.
An arbitrary positive rational \(r=a/b\) needs no further argument. Run the walk for the integer \(a\), that is from both of its starting values \(a\) and \(4a\), and report the value \(W/b\) at a node \(W\) exactly when \(b\) divides \(W\), without letting that test end the walk. Nothing is lost: if \(r\) times a product of local factors is an integer, then \(a\) times the same product is \(b\) times that integer and hence an integer too; its own starting value is \(4a\) when the product takes the factor \(4\) of the prime \(2\) and \(a\) when it does not, and both are integers, so by Lemma 1 every partial product is an integer and the node is visited. For \(r=1/4\) the walk from \(4a=4\) supplies all four values, through its nodes \(4\), \(12\), \(20\) and \(28\).
From here on the search is completely explicit. Its state is an integer \(V\) together with the largest prime \(p\) used so far. The value \(V\) is one of the integers to be summed. A chain is a sequence of local factors applied in increasing order of their primes, and the integer a chain reaches is called a node of the search. The continuations of a node are
$$V\longmapsto V\cdot\frac{q}{q-2}\qquad(q-2\mid V),$$
$$V\longmapsto V\cdot\frac{q^2}{(q-1)^2}\qquad\bigl((q-1)^2\mid V\bigr),$$
where in both cases \(q\) is a prime greater than \(p\). These divisibility tests are exactly the integrality tests of Lemma 1: since \(0\lt q-2\lt q\) and \(0\lt q-1\lt q\), the prime \(q\) divides neither \(q-2\) nor \((q-1)^2\), so the first new value is an integer precisely when \(q-2\) divides \(V\), and the second precisely when \((q-1)^2\) does.
Finding the first kind means running through the divisors \(d\) of \(V\) and testing whether \(d+2\) is a prime larger than \(p\); finding the second kind means running through the numbers \(c\) with \(c^2\mid V\) and testing whether \(c+1\) is a prime larger than \(p\). One continuation is easy to spot: since \(V\) divides itself, the prime \(q=V+2\) is admissible whenever \(V+2\) is a prime, and it then leads to the value \(V+2\). That prime is automatically larger than \(p\), because \(p\) divides \(V\) after a step at \(p\), and at the start of the walk \(p\) is \(2\).
4. No value occurs twice
Lemma 2. Two different choices of local factors give two different values.
Let the two choices differ, and let \(q\) be the largest prime at which they differ. Above \(q\) the two choices agree, so the denominators of their factors above \(q\) lower \(v_q\) by the same amount in both products. Below \(q\) nothing touches \(v_q\): those numerators are powers of primes different from \(q\), and those denominators have only prime factors below their own prime, hence below \(q\). The two values of \(v_q\) therefore differ exactly by the contribution of the factor at \(q\) itself, which is \(0\), \(1\) or \(2\) according to the three possibilities of Section 2 — three different numbers. The two products have different exponents at \(q\) and are therefore different.
At the prime \(2\) only the contributions \(0\) and \(2\) are available, which are also different, so the lemma covers that prime as well. The consequence for the program is that nothing has to be stored: the search reaches each choice at most once, every value it meets differs from all the others, and the values may be added up as they appear. This is why a problem that asks for a sum over a set needs no set.
The same reasoning explains why many different \(n\) give the same ratio while different choices never do: the exponents \(2,3,4,\dots\) all collapse to the one factor \(p^2/(p-1)^2\), so \(n=4\), \(8\), \(16\), \(32\) and so on all give the ratio \(4\). A choice records only which of the three cases occurs at each prime, and the smallest \(n\) realising a choice uses the exponents \(1\) and \(2\) only.
5. Why the search is finite
Throughout this section the walk starts at an integer, as in Section 3. It is not obvious that there are finitely many values. Every step multiplies the current value by more than \(1\), so the values along a chain increase, and a larger value may have more divisors and therefore offer more continuations. The following bound settles the question.
By Section 2 every local factor of an odd prime \(p\) is at most \(p/(p-2)\), and
$$\frac{p}{p-2}\le\Bigl(\frac{p}{p-1}\Bigr)^{3}=\Bigl(1-\frac1p\Bigr)^{-3}$$
for every \(p\ge3\). Clearing the denominators turns this into \((p-1)^3\le p^2(p-2)\), that is into \(p^3-3p^2+3p-1\le p^3-2p^2\), that is into \(p^2-3p+1\ge0\), which holds for every \(p\ge3\) because \(9-9+1\gt0\) and the left-hand side increases from there on. If a chain uses the odd primes \(q_1\lt\dots\lt q_j\), its value is therefore at most
$$V\le 4r\prod_{3\le p\le q_j}\Bigl(1-\frac1p\Bigr)^{-3},$$
the product being taken over all odd primes up to \(q_j\). By Mertens' third theorem the product of \((1-1/p)^{-1}\) over all primes \(p\le x\) is asymptotic to \(e^{\gamma}\log x\), [8] so the right-hand side is at most \(C\,r\,(\log q_j)^3\) for an absolute constant \(C\).
On the other hand the local factor of a prime \(q\) can be used only when \(q-2\) or \((q-1)^2\) divides the value \(U\) that the chain had reached before that step. A positive divisor of \(U\) is at most \(U\), so either \(q-2\le U\) or \((q-1)^2\le U\), and in both cases \(q\le U+2\). Since \(U\) obeys the bound just proved, combining the two gives
$$q_j\le C\,r\,(\log q_j)^3+2,$$
and \((\log x)^3/x\) tends to \(0\) as \(x\) grows, so the inequality fails for every sufficiently large \(q_j\). There is consequently a bound \(Q(r)\) that no prime used in any chain can exceed; every chain has at most one factor more than there are odd primes up to \(Q(r)\), every value is at most \(C\,r\,(\log Q(r))^3\), and the search tree is finite. For an arbitrary positive rational \(r=a/b\) the set of values is finite as well, since by the reduction at the end of Section 3 it is obtained by filtering the finite walk for the numerator \(a\). The bound above is then a bound in terms of \(a\) and not of \(r\), and the primes that occur need not be small merely because \(r\) is: for any odd prime \(p\) and \(r=(p-2)/p\), the factor of \(p\) alone already gives the integer \(1\). The bound is extremely generous: for \(r=40\,320\) the largest prime that actually occurs is \(1\,133\,641\) and the largest value is \(2\,288\,978\).
The computation of \(v_q\) in Section 3 has one more consequence, which bounds the exponents that can occur. Along a chain, \(v_t(V)\) can exceed \(v_t(r)\) by at most \(2\) for every prime \(t\): only the step at \(t\) itself raises \(v_t\), by \(1\) or by \(2\), and every other step either leaves \(v_t\) alone or lowers it. At \(t=2\) this can be made exact. A factor \(q/(q-2)\) of an odd prime has an odd numerator and an odd denominator and leaves \(v_2\) untouched, while a factor \(q^2/(q-1)^2\) of an odd prime lowers \(v_2\) by \(2v_2(q-1)\ge2\), and the factor of the prime \(2\) raises it by \(2\). Hence
$$v_2(V)=v_2(r)+2a-\sum_q 2v_2(q-1),$$
where \(a\) is \(1\) or \(0\) according to whether the factor \(4\) was taken, and \(q\) runs over the odd primes taken with the second kind of factor. Since \(v_2(V)\ge0\), a chain can carry at most \((v_2(r)+2)/2\) such primes. For \(r=40\,320=2^7\cdot3^2\cdot5\cdot7\) that is at most four, and four is attained by \(66\) of the values. No prime is ever used twice within a chain, since the primes along a chain increase strictly, and the values along a chain increase as well, so a chain never returns to a value it has left; two different chains end at different values by Lemma 2. The search therefore needs no record of the values it has already met.
6. The two published examples
For \(r=1/4\) only one start is possible. Without the factor of the prime \(2\) the value would be \(1/4\), which is not an integer, so the walk begins with that factor, at \(4\cdot\frac14=1\). From \(1\) the only divisor is \(1\), so the only candidate of the first kind is \(q=3\); a factor of the second kind would need \((q-1)^2\mid1\) and hence \(q=2\), which is not larger than the last prime used. The value becomes \(1\cdot3=3\). The divisors of \(3\) are \(1\) and \(3\), giving the candidates \(q=3\), which is not larger than \(3\), and \(q=5\); the value becomes \(3\cdot\frac53=5\). The divisors of \(5\) are \(1\) and \(5\), giving \(q=7\) and the value \(5\cdot\frac75=7\). The divisors of \(7\) are \(1\) and \(7\), giving \(q=3\) and \(q=9\), and \(9\) is not a prime; and no square above \(1\) divides \(7\), so there is no factor of the second kind either. The walk stops. The four values are \(1\), \(3\), \(5\) and \(7\), and they add up to the \(S(1/4)=16\) of the statement.
The smallest \(n\) that realise them are \(4\), \(12\), \(60\) and \(420\), with \(f(4)=1\), \(f(12)=1\), \(f(60)=3\) and \(f(420)=15\); a quarter of \(4/1\), \(12/1\), \(60/3\) and \(420/15\) is indeed \(1\), \(3\), \(5\), \(7\).
For \(r=1\) both starts are integers. The walk from \(1\) is the one just described, since the continuations depend only on the current value and on the largest prime used so far, not on \(r\), and both walks reach the value \(1\) with the prime \(2\) already passed; it contributes \(1\), \(3\), \(5\), \(7\). The walk from \(4\) is richer. The divisors of \(4\) are \(1\), \(2\) and \(4\), giving the candidates \(q=3\), \(q=4\) and \(q=6\), of which only \(3\) is a prime; and \((q-1)^2\mid4\) holds for \(q=2\) and \(q=3\), of which only \(3\) is larger than the last prime used. So \(4\) has the two children \(4\cdot3=12\) and \(4\cdot\frac94=9\), and the walk continues as the table shows. Every value in the table equals \(n/f(n)\) for the \(n\) beside it, and the sixteen values add up to \(S(1)=208\).
| \(n/f(n)\) | local factors | \(n\) | \(f(n)\) |
|---|---|---|---|
| \(1\) | none | \(1\) | \(1\) |
| \(3\) | \(3\) | \(3\) | \(1\) |
| \(5\) | \(3\cdot\frac53\) | \(15\) | \(3\) |
| \(7\) | \(3\cdot\frac53\cdot\frac75\) | \(105\) | \(15\) |
| \(4\) | \(4\) | \(4\) | \(1\) |
| \(12\) | \(4\cdot3\) | \(12\) | \(1\) |
| \(20\) | \(4\cdot3\cdot\frac53\) | \(60\) | \(3\) |
| \(28\) | \(4\cdot3\cdot\frac53\cdot\frac75\) | \(420\) | \(15\) |
| \(9\) | \(4\cdot\frac94\) | \(36\) | \(4\) |
| \(15\) | \(4\cdot\frac94\cdot\frac53\) | \(180\) | \(12\) |
| \(21\) | \(4\cdot\frac94\cdot\frac53\cdot\frac75\) | \(1260\) | \(60\) |
| \(23\) | \(\dots\cdot\frac{23}{21}\) | \(28\,980\) | \(1260\) |
| \(17\) | \(4\cdot\frac94\cdot\frac53\cdot\frac{17}{15}\) | \(3060\) | \(180\) |
| \(19\) | \(\dots\cdot\frac{19}{17}\) | \(58\,140\) | \(3060\) |
| \(11\) | \(4\cdot\frac94\cdot\frac{11}{9}\) | \(396\) | \(36\) |
| \(13\) | \(\dots\cdot\frac{13}{11}\) | \(5148\) | \(396\) |
Eight of the fourteen steps in the table are of the kind mentioned at the end of Section 3: the value \(V\) is followed by \(V+2\) because \(V+2\) is a prime, as with \(5\) and \(7\), \(9\) and \(11\), \(15\) and \(17\), \(21\) and \(23\). When the value reached in this way is itself a prime larger than \(3\), it has only the divisors \(1\) and itself, so the walk can continue only to the next number two further on, and only while that number is a prime. The chains \(\dots,11,13\) and \(\dots,17,19\) and \(\dots,5,7\) end precisely because \(15\), \(21\) and \(9\) are not primes. The chain \(4,12,20,28\) ends differently: the divisors of \(28\) are \(1,2,4,7,14,28\), so the candidates are \(3,4,6,9,16,30\), and none of these is a prime larger than \(7\); a factor of the second kind would need \((q-1)^2\) to divide \(28\) with \(q\gt7\), hence \((q-1)^2\ge64\gt28\).
7. The search for \(r=40\,320\)
The required value is \(r=40\,320=8!=2^7\cdot3^2\cdot5\cdot7\). Both starting values are integers, \(40\,320\) and \(4\cdot40\,320=161\,280\), and the first step of the walk, at the prime \(3\), splits each of them into three: the factor \(1\), the factor \(3\) and the factor \(9/4\), the last one only when \(4\) divides the value, which holds for both starting values here because \(4\) divides \(40\,320\). This produces six independent searches, from \(40\,320\), \(120\,960\), \(90\,720\), \(161\,280\), \(483\,840\) and \(362\,880\), and the program evaluates them on separate threads.
Altogether they visit \(53\,589\) values, all different by Lemma 2: \(16\,313\) in the three searches that omit the factor \(4\) and \(37\,276\) in the three that use it. The chains are short. The commonest length is eight local factors, reached by \(11\,290\) of the values, and the number of factors never exceeds fifteen; exactly one value needs fifteen, namely the one obtained from
$$2^2,\,3^2,\,5^2,\,7,\,11^2,\,13,\,23,\,41,\,43,\,79,\,131,\,239,\,241,\,31\,573,\,726\,181,$$
where an exponent \(2\) marks a factor of the second kind, \(p^2/(p-1)^2\), and a bare prime a factor of the first kind, \(p/(p-2)\).
The largest prime that occurs anywhere in the search is \(1\,133\,641\), and the way it arises shows what the divisibility condition really asks for. Its chain is
| factor | \(V\) | factor | \(V\) |
|---|---|---|---|
| \(V_0\) | \(161\,280\) | \(17/15\) | \(1\,732\,640\) |
| \(3\) | \(483\,840\) | \(19/17\) | \(1\,936\,480\) |
| \(25/16\) | \(756\,000\) | \(29^2/28^2\) | \(2\,077\,270\) |
| \(7/5\) | \(1\,058\,400\) | \(31/29\) | \(2\,220\,530\) |
| \(11/9\) | \(1\,293\,600\) | \(97/95\) | \(2\,267\,278\) |
| \(13/11\) | \(1\,528\,800\) | \(1\,133\,641/1\,133\,639\) | \(2\,267\,282\) |
The last denominator is \(1\,133\,639=13\cdot29\cdot31\cdot97\), the product of four primes that the chain has collected on the way, and the value just before the last step is exactly twice that product. The step is possible because the odd part of that value is exactly \(q-2\) for the prime \(q=1\,133\,641\), so the whole structure the chain has accumulated is consumed at once and the final value is \(2\cdot1\,133\,641\). The largest prime of the whole search must be the last factor of its chain, since any continuation would need a larger one. That is a property of the largest prime and not of large primes in general: the chain that reaches the prime \(887\,837\), for instance, continues from the value \(1\,775\,674\) to \(1\,775\,678\) with the prime \(887\,839\).
The largest value in the whole search is \(2\,288\,978=2\cdot31\cdot36\,919\). It is reached from the same value \(2\,220\,530\) by the factors \(67/65\) and \(36\,919/36\,917\) instead, which give \(2\,288\,854\) and then \(2\,288\,978\). Every value therefore stays below \(2^{22}\). Inside the search the program divides before it multiplies, so a child is formed as a value divided by the denominator of its local factor, times the numerator, which is at most three times a value; and every square it forms satisfies \(d^2\le V\), because the loop runs only while \(d\le V/d\). The largest quantities it handles are the running sums, and they stay below \(53\,589\cdot2\,288\,978\), which is less than \(2^{38}\). Signed \(64\)-bit arithmetic is ample.
How the Code Works
The C++ program [9] performs the search of Sections 3 to 5 and verifies it against the definition of \(f\). It works with signed \(64\)-bit integers, written i64, and uses NO_PRIME_LIMIT for the largest representable value when no bound on the primes is wanted.
is_prime(n) is deterministic trial division: it settles \(n\lt2\) and the multiples of \(2\) and of \(3\), then tests the divisors \(5,7,11,13,\dots\) in the two residue classes \(\pm1\) modulo \(6\), stopping as soon as the divisor exceeds \(n\) divided by that divisor, which is the loop's way of writing \(d\le\sqrt n\) without a square root.
sum_from(value, last_prime, prime_limit) is the recursion. When the prime limit does not exceed the last prime used, the function returns the value at once, since a continuation would need a prime greater than the last one and within the limit, and no prime is both. Otherwise it begins the sum with value itself, which is the node's own contribution, and then looks for continuations. The lambda add_single_power(divisor) handles a factor of the first kind: it forms \(p=\)divisor\(+2\) and recurses on value / divisor * p when \(p\) is a prime greater than last_prime and within prime_limit. Since every prime beyond the first step is odd, the divisor \(p-2\) is odd too, so only the odd divisors of the value can occur; the function therefore halves the value until it is odd, keeps the result in odd_part, and runs through the divisors of that. The loop takes \(d=1,3,5,\dots\) as far as the square root of that odd part and treats both \(d\) and odd_part / d, which is the standard way of listing divisors in pairs; the second condition of the loop, odd_part / d + 2 > last_prime, stops it as soon as even the larger divisor of the pair can no longer produce a prime above last_prime, and the smaller one never can. A second loop handles the factors of the second kind. It runs \(d\) through the even numbers from last_prime upwards: last_prime itself when that is even, as it is at the serial entry point with the prime \(2\), and last_prime\(+1\) when it is odd. It sets \(p=d+1\) and recurses on value / (d * d) * p * p when \(d^2\) divides the value and \(p\) is a prime. The bound \(d\le\sqrt V\) is again written as a division, and d < prime_limit is the condition \(p\le\) prime_limit.
distinct_sum(numerator, denominator, prime_limit) is the entry point for \(r=\)numerator\(/\)denominator. It requires a positive numerator and a denominator of \(1\), \(2\) or \(4\), the last enforced by the rejection test 4 % denominator != 0; the fraction is not reduced first, so a denominator of \(8\) is rejected even when the value it writes is a multiple of a quarter. The lambda split_at_three(value) performs the step at the prime \(3\) by hand, pushing value, \(3\,\)value and value / 4 * 9, the last only when \(4\) divides the value and the two further branches only when the prime limit admits the prime \(3\); it is called for \(4r\) when the prime limit admits the prime \(2\) and, when \(r\) is an integer, for \(r\) as well, so that, for a prime limit of at least \(3\), six branches arise when \(4\) divides \(r\), five for any other integer and two for an \(r\) that is not an integer. Each branch is a Branch with its own value, prime bound and partial sum. All branches but the last are given a thread with pthread_create, and a branch whose thread cannot be created is simply evaluated in place; the last branch is always evaluated on the calling thread, so no thread is created without need. After the joins the branch sums are added together. A join that fails is not patched over: the program calls std::terminate rather than counting a branch whose sum it cannot know was written. The split at the prime \(3\) is only a device for parallelism: sum_from(value, 2, limit) would find the same factors of \(3\) by itself, and the self-test checks precisely this, at the one input \(r=40\,320\).
small_convolution_values() computes \(f\) from its definition, in the inverted form \(\varphi(n)=\sum_{d\mid n}f(d)\) of Section 1, for every divisor \(n\) of \((2\cdot3\cdot5\cdot7)^2=44\,100\). It counts the integers \(k\le n\) with \(\gcd(k,n)=1\) to obtain \(\varphi(n)\) and then subtracts the values \(f(d)\) already found for the proper divisors \(d\) of \(n\). Because the loop runs over \(n=1,2,\dots\) in increasing order and every divisor of \(n\) is also a divisor of \(44\,100\), all the proper divisors are present by the time they are needed.
self_test(), started with the argument --self-test, requires \(S(1/4)=16\) and \(S(1)=208\), the two values of the statement. It then compares the search with the definition: for the denominators \(1\), \(2\) and \(4\) and the numerators \(1\), \(2\), \(3\), \(4\), \(5\), \(7\), \(12\) and \(40\,320\) it collects, into a std::set, every integer \(r\,n/f(n)\) with \(n\) a divisor of \(44\,100\) and \(f(n)\ne0\), and requires its total to equal distinct_sum with the primes limited to \(7\). The exponents in \(44\,100\) do not exceed \(2\), which by Section 2 is enough to realise every choice of local factors over the primes \(2,3,5,7\). Finally it requires the parallel total for \(r=40\,320\) to equal sum_from(r, 2, ...) plus sum_from(4r, 2, ...), the same search without the manual split and without threads. Without an argument the program prints \(S(40\,320)\); any other argument produces a usage message on the standard error stream and the exit status \(1\).
The Python and Java versions follow the C++ program function by function, with the same command line and the same self-test. Both form the starting value as the numerator times \(4\) divided by the denominator, but divide the denominator into the \(4\) first, which the guard has already shown to be exact. Python evaluates the branches on threads and leaves a branch's sum unset until the branch has really produced one, so that neither a branch that fails nor a thread that dies before it begins can be mistaken for a branch with the sum \(0\); a thread it cannot start is evaluated in place, as in the C++ program. Java submits the branches to an executor, where Future.get has the same effect, and uses checked arithmetic, Math.multiplyExact for a product and Math.addExact for a sum, which turns an overflow into an exception instead of a wrong answer; Python needs no such care, since its integers are unbounded.
Complexity and Verification
The search visits one node for every value, and by Lemma 2 these values are pairwise different, so for an integral \(r\) the number of nodes is the number of summands: \(53\,589\) for \(r=40\,320\). At a node holding the value \(V\) the two loops run at most as far as \(\sqrt V\); the largest index either of them reaches in the whole search is \(1512\). A primality test is performed only for a candidate that has passed the comparison with the last prime used. Counting the steps of the instrumented program gives \(4\,597\,974\) iterations of the divisor loop and \(5\,105\,591\) iterations of the loop over squares, of which only \(1152\) find a square that divides the value. These loops offer \(396\,389\) candidate primes; the comparison with the last prime used discards \(164\,131\) of them, and the remaining \(232\,258\) are tested for primality. Such a test divides by \(2\) and by \(3\) and then runs through the numbers that are \(\pm1\) modulo \(6\), two of them per turn, as far as \(\sqrt p\), so it turns its loop at most \(\lfloor(\sqrt p+1)/6\rfloor\) times; over the whole search these loops turn \(1\,509\,218\) times and perform \(2\,964\,880\) divisions, \(53\,556\) of the turns stopping after the first of their two divisors. That is about \(11\) million elementary steps in all, an average of roughly \(210\) per value. Exactly \(53\,583\) of the primality tests succeed, one for every value except the six the search starts from. The threads roughly halve the running time; a build in which every thread creation is made to fail prints the same value in about \(0.017\) seconds.
Measured as the median wall-clock time of five runs of the whole program on an Apple M4 Max, the C++ program built with clang++ -std=c++20 -O3 prints the answer in about \(0.009\) seconds on its six threads, and its self-test takes about \(0.027\) seconds. The Java version, compiled beforehand and run on OpenJDK 17, prints it in about \(0.096\) seconds and its self-test takes about \(0.098\) seconds, figures that include some \(0.026\) seconds for the start of the virtual machine; the Python version on CPython 3.11 takes about \(0.62\) seconds and \(1.25\) seconds.
All three programs print the same value and pass their self-tests. Builds of the C++ program with the address and undefined-behaviour sanitizers at two levels of optimisation, and with the thread sanitizer, print the same value, pass the self-test and emit no diagnostic at all, and the compiler raises no warning with -Wall -Wextra. Every number derived by hand in this article agrees with the programs: the values of \(f\) and of \(n/f(n)\) in the table of Section 1, the local factors of Section 2, the four values for \(r=1/4\) and the sixteen for \(r=1\) together with the \(n\) that realise them, and the chains, values and factorisations of Section 7.
Further checks, which are not part of the published solutions, use different code. A Python program written from the statement alone computes \(f\) from \(f(n)=\sum_{d\mid n}\mu(n/d)\varphi(d)\) with the Möbius and totient functions of a computer algebra library, extends a value by running through the divisors of the value itself rather than of its odd part, and collects the results in a set instead of relying on Lemma 2. It confirms \(f(1)=1\), \(f(p)=p-2\) and \(f(p^k)=p^{k-2}(p-1)^2\) for every prime power below \(100\,000\), confirms for every \(n\) below \(100\,000\) that \(f(n)=0\) holds exactly when \(n\) is twice an odd number, which Section 1 proves for all \(n\), and reproduces \(S(1/4)=16\) and \(S(1)=208\). An independent C++ program of the same kind agrees with the published one at \(r=40\,320\) and at \(r=\frac14,\frac12,1,2,\)\(3,4,5,6,7,12,720,5040\), and the published Python version agrees with it at those values and at \(r=\frac34,\frac72,1260\) as well. In every one of these runs the number of nodes equals the number of distinct values, which is Lemma 2 in experimental form. The same programs produced the statistics quoted in Section 7: the sizes \(16\,313\) and \(37\,276\) of the two halves of the search, the distribution of the chain lengths, the single chain of fifteen factors, the largest prime \(1\,133\,641\) with its chain, and the largest value \(2\,288\,978=2\cdot31\cdot36\,919\).
Footnotes and References
The references below supply background facts. The determination of \(f\) on prime powers, the three local factors, Lemma 1, Lemma 2 and the finiteness of the search are derived explicitly in this article.
- Project Euler 1021 — Dirichlet Drama. The official statement lets \(\mu(n)\) denote the Möbius function and \(\phi(n)\) Euler's totient function, defines \(f(n)=\sum_{d\mid n}\mu(n/d)\phi(d)\), lets \(S(r)\) be the sum of all distinct integer values the expression \(r\cdot n/f(n)\) can take over positive integers \(n\), gives \(S(\frac14)=16\) and \(S(1)=208\), and asks for \(S(40\,320)\). It does not say what kind of number \(r\) is; the two values it gives and the one it asks for are positive rationals.
- Wikipedia — Möbius function. \(\mu(n)\) is \(1\) for \(n=1\), \((-1)^k\) for a product of \(k\) distinct primes and \(0\) when a square of a prime divides \(n\); the function is multiplicative, and \(\sum_{d\mid n}\mu(d)\) is \(1\) for \(n=1\) and \(0\) otherwise.
- Wikipedia — Euler's totient function. \(\varphi(n)\) counts the integers from \(1\) to \(n\) that are coprime to \(n\); it is multiplicative, \(\varphi(p^k)=p^{k-1}(p-1)\) for a prime power, and \(\sum_{d\mid n}\varphi(d)=n\).
- Wikipedia — Dirichlet convolution. The convolution \((g*h)(n)\)\({}=\sum_{d\mid n}g(d)h(n/d)\) is commutative and associative, its identity element is the function that is \(1\) at \(1\) and \(0\) elsewhere, the convolution of two multiplicative functions is multiplicative, and \(\mu\) is the inverse of the constant function \(1\).
- Wikipedia — Möbius inversion formula. If \(g(n)=\sum_{d\mid n}h(d)\) for all \(n\), then \(h(n)=\sum_{d\mid n}\mu(n/d)g(d)\) for all \(n\), and conversely.
- Wikipedia — Multiplicative function. A multiplicative function satisfies \(f(1)=1\) and \(f(ab)=f(a)f(b)\) for coprime \(a\) and \(b\), so it is determined by its values on prime powers.
- OEIS A007431. The sequence \(\sum_{d\mid n}\varphi(d)\mu(n/d)\); its terms for \(n=1,\dots,20\) are \(1,0,1,1,3,0,5,2,4,0,\)\(9,1,11,0,3,4,15,0,17,3\), and the entry begins one place earlier, at the index \(0\). The entry also records that the sequence is multiplicative with the values \(p-2\) and \(p^{e-2}(p-1)^2\) for \(e\gt1\) on prime powers, and gives the Dirichlet generating function \(\zeta(s-1)/\zeta(s)^2\).
- Wikipedia — Mertens' theorems. The third theorem states that the product of \((1-1/p)^{-1}\) over the primes \(p\le x\) is asymptotic to \(e^{\gamma}\log x\), where \(\gamma\) is the Euler–Mascheroni constant.
- C++ — Euler1021.cpp. The linked immutable C++ revision contains
is_prime,sum_from,evaluate_branch,distinct_sum,small_convolution_valuesand the checks run by --self-test. It is the implementation record for this article.
Problem 1021 source code
C++
#include <cstdint>
#include <exception>
#include <iostream>
#include <limits>
#include <numeric>
#include <pthread.h>
#include <set>
#include <stdexcept>
#include <string_view>
#include <utility>
#include <vector>
namespace {
using i64 = std::int64_t;
constexpr i64 NO_PRIME_LIMIT = std::numeric_limits<i64>::max();
bool is_prime(i64 n) {
if (n < 2 || n % 2 == 0) return n == 2;
if (n % 3 == 0) return n == 3;
for (i64 d = 5; d <= n / d; d += 6) {
if (n % d == 0 || n % (d + 2) == 0) return false;
}
return true;
}
i64 sum_from(i64 value, i64 last_prime, i64 prime_limit) {
// The largest prime where two choices differ has different valuations in their products.
// No prime beyond the limit is admitted, so there the value is already the whole sum.
if (prime_limit <= last_prime) return value;
i64 sum = value;
const auto add_single_power = [&](i64 divisor) {
const i64 p = divisor + 2;
if (p > last_prime && p <= prime_limit && is_prime(p)) {
sum += sum_from(value / divisor * p, p, prime_limit);
}
};
// The next local denominator must divide value, since later numerator primes are larger.
i64 odd_part = value;
while (odd_part % 2 == 0) odd_part /= 2;
for (i64 d = 1; d <= odd_part / d && odd_part / d + 2 > last_prime; d += 2) {
if (odd_part % d != 0) continue;
add_single_power(d);
if (d != odd_part / d) add_single_power(odd_part / d);
}
for (i64 d = last_prime + last_prime % 2; d < prime_limit && d <= value / d; d += 2) {
const i64 p = d + 1;
if (value % (d * d) == 0 && is_prime(p)) {
sum += sum_from(value / (d * d) * p * p, p, prime_limit);
}
}
return sum;
}
struct Branch {
i64 value, prime_limit;
i64 sum = 0;
pthread_t thread{};
bool started = false;
};
// pthread_create takes a pointer to a function with C language linkage. The braced form keeps the
// definition static, so the anonymous namespace still hides it; extern "C" static is ill-formed.
extern "C" {
static void* evaluate_branch(void* argument) {
auto& branch = *static_cast<Branch*>(argument);
branch.sum = sum_from(branch.value, 3, branch.prime_limit);
return nullptr;
}
}
i64 distinct_sum(i64 numerator, i64 denominator = 1, i64 prime_limit = NO_PRIME_LIMIT) {
if (numerator <= 0 || denominator <= 0 || 4 % denominator != 0) {
throw std::invalid_argument("Expected a positive multiple of one quarter");
}
std::vector<Branch> branches;
const auto split_at_three = [&](i64 value) {
branches.push_back({value, prime_limit});
if (prime_limit >= 3) {
branches.push_back({3 * value, prime_limit});
if (value % 4 == 0) branches.push_back({value / 4 * 9, prime_limit});
}
};
// At 2 the only defined local factors are 1 and 4. Odd primes cannot clear a factor of 2.
// The denominator divides 4, so dividing it into the 4 first is exact and cannot overflow early.
if (prime_limit >= 2) split_at_three(numerator * (4 / denominator));
if (numerator % denominator == 0) split_at_three(numerator / denominator);
for (auto& branch : branches) {
if (&branch != &branches.back() && pthread_create(&branch.thread, nullptr, evaluate_branch, &branch) == 0) {
branch.started = true;
} else {
evaluate_branch(&branch);
}
}
i64 sum = 0;
for (const auto& branch : branches) {
if (branch.started && pthread_join(branch.thread, nullptr) != 0) std::terminate();
sum += branch.sum;
}
return sum;
}
std::vector<std::pair<int, int>> small_convolution_values() {
constexpr int RADICAL = 2 * 3 * 5 * 7;
constexpr int LIMIT = RADICAL * RADICAL;
std::vector<std::pair<int, int>> entries;
for (int n = 1; n <= LIMIT; ++n) {
if (LIMIT % n != 0) continue;
int f = 0;
for (int k = 1; k <= n; ++k) {
if (std::gcd(k, n) == 1) ++f;
}
// Inverting phi(n) = sum_{d|n} f(d) gives the original Mobius convolution.
for (const auto& [d, fd] : entries) {
if (n % d == 0) f -= fd;
}
entries.emplace_back(n, f);
}
return entries;
}
void self_test() {
if (distinct_sum(1, 4) != 16 || distinct_sum(1) != 208) {
throw std::runtime_error("Published example failed");
}
const auto entries = small_convolution_values();
for (const int denominator : {1, 2, 4}) {
for (const int numerator : {1, 2, 3, 4, 5, 7, 12, 40'320}) {
std::set<i64> values;
for (const auto& [n, f] : entries) {
const i64 top = static_cast<i64>(numerator) * n;
const i64 bottom = static_cast<i64>(denominator) * f;
if (bottom != 0 && top % bottom == 0) values.insert(top / bottom);
}
if (distinct_sum(numerator, denominator, 7) != std::accumulate(values.begin(), values.end(), i64{0})) {
throw std::runtime_error("Direct convolution check failed");
}
}
}
constexpr i64 r = 40'320;
if (distinct_sum(r) != sum_from(r, 2, NO_PRIME_LIMIT) + sum_from(4 * r, 2, NO_PRIME_LIMIT)) {
throw std::runtime_error("Serial and parallel totals differ");
}
std::cout << "All checks passed.\n";
}
}
int main(int argc, char* argv[]) {
if (argc == 2 && std::string_view(argv[1]) == "--self-test") {
self_test();
} else if (argc == 1) {
std::cout << distinct_sum(40'320) << '\n';
} else {
std::cerr << "Usage: Euler1021 [--self-test]\n";
return 1;
}
return 0;
}
Python
#!/usr/bin/env python3
"""Project Euler Problem 1021 - Dirichlet Drama."""
import sys
import threading
from math import gcd
NO_PRIME_LIMIT = sys.maxsize
def is_prime(n):
if n < 2 or n % 2 == 0:
return n == 2
if n % 3 == 0:
return n == 3
d = 5
while d <= n // d:
if n % d == 0 or n % (d + 2) == 0:
return False
d += 6
return True
def sum_from(value, last_prime, prime_limit):
# The largest prime where two choices differ has different valuations in their products.
# No prime beyond the limit is admitted, so there the value is already the whole sum.
if prime_limit <= last_prime:
return value
total = value
def add_single_power(divisor):
nonlocal total
p = divisor + 2
if p > last_prime and p <= prime_limit and is_prime(p):
total += sum_from(value // divisor * p, p, prime_limit)
# The next local denominator must divide value, since later numerator primes are larger.
odd_part = value
while odd_part % 2 == 0:
odd_part //= 2
d = 1
while d <= odd_part // d and odd_part // d + 2 > last_prime:
if odd_part % d == 0:
add_single_power(d)
if d != odd_part // d:
add_single_power(odd_part // d)
d += 2
d = last_prime + last_prime % 2
while d < prime_limit and d <= value // d:
p = d + 1
if value % (d * d) == 0 and is_prime(p):
total += sum_from(value // (d * d) * p * p, p, prime_limit)
d += 2
return total
class Branch:
def __init__(self, value, prime_limit):
self.value = value
self.prime_limit = prime_limit
self.total = None # stays None until the branch really produced a sum
self.error = None
self.thread = None
def evaluate_branch(branch):
try:
branch.total = sum_from(branch.value, 3, branch.prime_limit)
except BaseException as error: # a branch must never report 0 instead of failing
branch.error = error
def distinct_sum(numerator, denominator=1, prime_limit=NO_PRIME_LIMIT):
if numerator <= 0 or denominator <= 0 or 4 % denominator != 0:
raise ValueError("Expected a positive multiple of one quarter")
branches = []
def split_at_three(value):
branches.append(Branch(value, prime_limit))
if prime_limit >= 3:
branches.append(Branch(3 * value, prime_limit))
if value % 4 == 0:
branches.append(Branch(value // 4 * 9, prime_limit))
# At 2 the only defined local factors are 1 and 4. Odd primes cannot clear a factor of 2.
# The denominator divides 4, so dividing it into the 4 first keeps the product exact.
if prime_limit >= 2:
split_at_three(numerator * (4 // denominator))
if numerator % denominator == 0:
split_at_three(numerator // denominator)
for branch in branches:
if branch is not branches[-1]:
branch.thread = threading.Thread(target=evaluate_branch, args=(branch,))
try:
branch.thread.start()
except RuntimeError: # no thread available: evaluate it here instead
branch.thread = None
evaluate_branch(branch)
else:
evaluate_branch(branch)
total = 0
for branch in branches:
if branch.thread is not None:
branch.thread.join()
if branch.error is not None:
raise branch.error
if branch.total is None: # the thread died before it could record anything
raise RuntimeError("A branch produced no sum")
total += branch.total
return total
def small_convolution_values():
radical = 2 * 3 * 5 * 7
limit = radical * radical
entries = []
for n in range(1, limit + 1):
if limit % n != 0:
continue
f = sum(1 for k in range(1, n + 1) if gcd(k, n) == 1)
# Inverting phi(n) = sum_{d|n} f(d) gives the original Mobius convolution.
for d, fd in entries:
if n % d == 0:
f -= fd
entries.append((n, f))
return entries
def self_test():
if distinct_sum(1, 4) != 16 or distinct_sum(1) != 208:
raise RuntimeError("Published example failed")
entries = small_convolution_values()
for denominator in (1, 2, 4):
for numerator in (1, 2, 3, 4, 5, 7, 12, 40_320):
values = set()
for n, f in entries:
top = numerator * n
bottom = denominator * f
if bottom != 0 and top % bottom == 0:
values.add(top // bottom)
if distinct_sum(numerator, denominator, 7) != sum(values):
raise RuntimeError("Direct convolution check failed")
r = 40_320
if distinct_sum(r) != sum_from(r, 2, NO_PRIME_LIMIT) + sum_from(4 * r, 2, NO_PRIME_LIMIT):
raise RuntimeError("Serial and threaded totals differ")
print("All checks passed.")
def main(argv):
try:
if len(argv) == 2 and argv[1] == "--self-test":
self_test()
elif len(argv) == 1:
print(distinct_sum(40_320))
else:
print("Usage: Euler1021.py [--self-test]", file=sys.stderr)
return 1
except (ValueError, RuntimeError) as error:
print(error, file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
sys.setrecursionlimit(10_000)
sys.exit(main(sys.argv))
Java
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class Euler1021 {
private static final long NO_PRIME_LIMIT = Long.MAX_VALUE;
private static boolean isPrime(long n) {
if (n < 2 || n % 2 == 0) return n == 2;
if (n % 3 == 0) return n == 3;
for (long d = 5; d <= n / d; d += 6) {
if (n % d == 0 || n % (d + 2) == 0) return false;
}
return true;
}
// The largest prime where two choices differ has different valuations in their products.
private static long sumFrom(long value, long lastPrime, long primeLimit) {
// No prime beyond the limit is admitted, so there the value is already the whole sum.
if (primeLimit <= lastPrime) return value;
long sum = value;
// The next local denominator must divide value, since later numerator primes are larger.
long oddPart = value;
while (oddPart % 2 == 0) oddPart /= 2;
for (long d = 1; d <= oddPart / d && oddPart / d + 2 > lastPrime; d += 2) {
if (oddPart % d != 0) continue;
sum = Math.addExact(sum, singlePower(value, d, lastPrime, primeLimit));
if (d != oddPart / d) {
sum = Math.addExact(sum, singlePower(value, oddPart / d, lastPrime, primeLimit));
}
}
for (long d = lastPrime + lastPrime % 2; d < primeLimit && d <= value / d; d += 2) {
final long p = d + 1;
if (value % Math.multiplyExact(d, d) == 0 && isPrime(p)) {
final long next = Math.multiplyExact(Math.multiplyExact(value / (d * d), p), p);
sum = Math.addExact(sum, sumFrom(next, p, primeLimit));
}
}
return sum;
}
private static long singlePower(long value, long divisor, long lastPrime, long primeLimit) {
final long p = divisor + 2;
if (p > lastPrime && p <= primeLimit && isPrime(p)) {
return sumFrom(Math.multiplyExact(value / divisor, p), p, primeLimit);
}
return 0;
}
private static final class Branch {
final long value;
final long primeLimit;
Branch(long value, long primeLimit) {
this.value = value;
this.primeLimit = primeLimit;
}
long evaluate() {
return sumFrom(value, 3, primeLimit);
}
}
static long distinctSum(long numerator) {
return distinctSum(numerator, 1, NO_PRIME_LIMIT);
}
static long distinctSum(long numerator, long denominator, long primeLimit) {
if (numerator <= 0 || denominator <= 0 || 4 % denominator != 0) {
throw new IllegalArgumentException("Expected a positive multiple of one quarter");
}
final List<Branch> branches = new ArrayList<>();
// At 2 the only defined local factors are 1 and 4. Odd primes cannot clear a factor of 2.
// The denominator divides 4, so dividing it into the 4 first keeps the product exact.
if (primeLimit >= 2) {
splitAtThree(branches, Math.multiplyExact(numerator, 4 / denominator), primeLimit);
}
if (numerator % denominator == 0) {
splitAtThree(branches, numerator / denominator, primeLimit);
}
// With no admissible root the C++ and Python loops simply find nothing to add.
if (branches.isEmpty()) return 0;
final ExecutorService pool = Executors.newFixedThreadPool(Math.max(1, branches.size() - 1));
try {
final List<Future<Long>> started = new ArrayList<>();
for (int i = 0; i < branches.size() - 1; i++) {
final Branch branch = branches.get(i);
started.add(pool.submit(branch::evaluate));
}
// The last branch is always evaluated on the calling thread.
long sum = branches.get(branches.size() - 1).evaluate();
for (final Future<Long> future : started) {
try {
sum = Math.addExact(sum, future.get());
} catch (final InterruptedException error) {
Thread.currentThread().interrupt();
throw new IllegalStateException("Interrupted while waiting for a branch", error);
} catch (final java.util.concurrent.ExecutionException error) {
// A failing branch must never be mistaken for a branch with the sum 0.
throw new IllegalStateException("A branch failed", error.getCause());
}
}
return sum;
} finally {
pool.shutdown();
}
}
private static void splitAtThree(List<Branch> branches, long value, long primeLimit) {
branches.add(new Branch(value, primeLimit));
if (primeLimit >= 3) {
branches.add(new Branch(Math.multiplyExact(3, value), primeLimit));
if (value % 4 == 0) branches.add(new Branch(Math.multiplyExact(value / 4, 9), primeLimit));
}
}
private static long[][] smallConvolutionValues() {
final int radical = 2 * 3 * 5 * 7;
final int limit = radical * radical;
final List<long[]> entries = new ArrayList<>();
for (int n = 1; n <= limit; n++) {
if (limit % n != 0) continue;
long f = 0;
for (int k = 1; k <= n; k++) {
if (gcd(k, n) == 1) f++;
}
// Inverting phi(n) = sum_{d|n} f(d) gives the original Mobius convolution.
for (final long[] entry : entries) {
if (n % entry[0] == 0) f -= entry[1];
}
entries.add(new long[] {n, f});
}
return entries.toArray(new long[0][]);
}
private static long gcd(long a, long b) {
while (b != 0) {
final long t = a % b;
a = b;
b = t;
}
return a;
}
private static void require(boolean condition, String description) {
if (!condition) throw new IllegalStateException("Check failed: " + description);
}
private static void selfTest() {
require(distinctSum(1, 4, NO_PRIME_LIMIT) == 16 && distinctSum(1) == 208, "Published example failed");
final long[][] entries = smallConvolutionValues();
for (final long denominator : new long[] {1, 2, 4}) {
for (final long numerator : new long[] {1, 2, 3, 4, 5, 7, 12, 40_320}) {
final Set<Long> values = new HashSet<>();
for (final long[] entry : entries) {
final long top = Math.multiplyExact(numerator, entry[0]);
final long bottom = Math.multiplyExact(denominator, entry[1]);
if (bottom != 0 && top % bottom == 0) values.add(top / bottom);
}
long direct = 0;
for (final long value : values) direct = Math.addExact(direct, value);
require(distinctSum(numerator, denominator, 7) == direct, "Direct convolution check failed");
}
}
final long r = 40_320;
require(distinctSum(r) == Math.addExact(sumFrom(r, 2, NO_PRIME_LIMIT), sumFrom(4 * r, 2, NO_PRIME_LIMIT)),
"Serial and threaded totals differ");
System.out.println("All checks passed.");
}
public static void main(String[] args) {
try {
if (args.length == 1 && args[0].equals("--self-test")) {
selfTest();
} else if (args.length == 0) {
System.out.println(distinctSum(40_320));
} else {
System.err.println("Usage: java Euler1021 [--self-test]");
System.exit(1);
}
} catch (final IllegalArgumentException | IllegalStateException | ArithmeticException error) {
System.err.println(error.getMessage());
System.exit(1);
}
}
}