# Problem 14 — the price of stopping, the price of information, and a one-cent playing rule
**Research report and reproducible source edition · Third revision · 4 December 2026**
Shuffle equal numbers of red and black cards.
Start at zero.
A red draw adds a dollar and a black draw subtracts one.
At any time before the next draw the player may take the current balance and leave.
Finishing the deck pays zero.
What should a player do, what should someone pay to play, and how much would it help to know the future?
On 52 cards the fair price is exactly **41,984,711,742,427 / 15,997,372,030,584 dollars**, about **2.624475549**.
The exact standard-deck strategy fits in one line.
The large-deck price has a simple certified approximation.
A two-branch strategy guarantees that a player who follows it on **any** balanced deck gives up less than **one cent in expectation**.
The distinction between quoting a price and realizing a payoff is central to this report.
The results concern a finite game with risk-neutral expectation, equiprobable color orders, perfect recall of past draws, and exact knowledge of the starting composition.
The asymptotic analyses concern growing balanced decks.
The timing results concern the machines and workloads specified.
The proven finite price and stopping rules have the highest confidence.
The machine-checked conclusions, integer certificates, written arguments and experiments are identified individually, so that accepting one requires only the relevant assumptions.
Shepp studied the Brownian and urn formulations, Boyce developed the discrete theory, and a computational treatment on Gwern.net supplied the large-deck benchmark. [Shepp 1969](https://faculty.wharton.upenn.edu/wp-content/uploads/2012/04/Explicit-solutions-to-some-problems-of-optimal-stopping.pdf "Explicit Solutions to Some Problems of Optimal Stopping") · [Boyce 1973](https://sites.math.rutgers.edu/~zeilberg/EM13/boyce1973.pdf "On a simple optimal stopping problem") · [Branwen et al 2022](https://gwern.net/problem-14 "Problem 14 Dynamic Programming Solutions")
The published square-root fit concealed a slowly vanishing absolute error. Subtract the exact discrete binomial comparison before estimating the exponent. A two-sided proof gives the critical power $0.2311666867\ldots$. Numerical evidence puts the possible limiting multiplier near $0.1026$ for the number of pairs, or $0.1204$ for the number of cards. Its convergence remains open. On the playing side, a half-dollar change in the exercise test makes a measurable difference. Keeping the small-deck integer rule and changing only the large-deck boundary reduces the worst expected loss through 8,388,608 cards by a factor of 5,301, from about $0.02634$ cents to $0.000004969$ cents. Section 2 distinguishes finite maxima from all-deck guarantees, and Section 7 identifies precisely which players Lean certifies.
The most informative number in a regret certificate can be the part that even an optimal player must lose against the proof's upper bound. On a deck of 482,620 cards the original certificate spends 59.63% of its allowance on that discrepancy. Measuring the action errors along the paths the player actually follows exposes much smaller and sometimes extremely rare differences. A 215-red opening distinguishes two players that a numerical comparison had counted as tied.
That distinction also has an asymptotic consequence. The loss against the *optimal player itself* is of order $N^{-0.2311666867\ldots}$ for each of the three players that stay within a bounded distance of the Brownian boundary. A mistake confined to a fixed small endgame leaves a trace on arbitrarily large decks. The exponent measures how often play reaches a region where that mistake still matters. Improving its coefficient can be worth several orders of magnitude over feasible deck sizes.
## How to read and check this report
Sections 1–7 give a continuous account of the results, strategies, evidence and open questions.
The mathematical appendices give the longer derivations, including the explicit fixed-length formula, the discrete harmonic comparisons, and the information-pricing arguments.
The final appendices contain the source files themselves.
A standard-library Python extractor recreates the project, checks byte counts and SHA-256 digests, and restores executable permissions on scripts and historical images.
External tools such as the compiler, Lean 4.19.0, mathlib v4.19.0 and GMP are ordinary build dependencies.
No private link or separate source archive is needed.
- [Rules, notation and exact prices](#game)
- [A playing rule with an all-deck one-cent guarantee](#cent)
- [Which closed forms exist](#forms)
- [From exact arithmetic to constant-work quotes](#computation)
- [Assembly, executable startup and a one-syscall quote](#systems)
- [Advice, preview, vouchers and the prophet](#information)
- [Lessons, trust boundaries and open problems](#review)
- [The half-card correction and the three policies compared](#half)
- [The exact logarithmic decay exponent and its numerical amplitude](#spectral)
- [Corrections to the original numerical analysis](#original)
- [Suggested diffs to the original Gwern.net article](#suggested-article-diffs)
- [Expected coding length and the peak entropy](#codes)
- [Full-history Lean theorems and their assumptions](#full-history)
- [Measured regret and the parts of the proof allowance](#audit-regret)
- [Boundary correction, zero payouts and actual regret rates](#new-boundary)
- [Independent checks of sources and numerical results](#independent-findings)
- [Detailed derivations](#derivations)
- [Extraction and verification](#extract)
- [Readable source listings](#sources) and [machine-generated evidence](#evidence)
## 1. The ordinary game
Let $n$ be the number of **pairs**, $N=2n$ the total number of **cards**, and $r,b$ the numbers of reds and blacks remaining.
The balance and remaining horizon are $x=b-r$ and $t=r+b$.
A positive score means that the unseen deck contains more blacks than reds.
Let $V(t,x)$ denote the optimal expected **final balance**, $V_n=V(2n,0)$ the starting price, $S_j$ the balance after $j$ draws, and $H=\max_{0\le j\le N}S_j$ the peak including zero.
Regret of a rule $\pi$ means $V_n-E[S_{\tau_\pi}]$ from the initial shuffle.
Seeing a bad decision on one prefix, or knowing that another strategy can win a dollar more on one deal, does not specify this quantity.
At interior states the alternatives are
$$
V(t,x)=\max\left(x,\frac{(t-x)V(t-1,x+1)+(t+x)V(t-1,x-1)}{2t}\right).
$$
At a physical edge omit the absent child.
At exhaustion the value is zero.
Foregoing a stop and drawing to exhaustion is always feasible.
With $r$ reds and $b$ blacks, multiplying by $\binom{r+b}r$ changes the two weighted child contributions to addition.
The unshifted aggregate satisfies
$$
A(r,b)=\max\left((b-r)\binom{r+b}r, A(r-1,b)+A(r,b-1)\right),\quad A(r,0)=0,\quad A(0,b)=b.
$$
Then $V_n=A(n,n)/\binom{2n}n$.
This version is an exact reference implementation.
Lean uses an equivalent nonnegative shifted reward, establishes attainment against all legal stopping decisions, checks agreement with the paths of the game, and evaluates the standard-deck fraction.
The first diagonal aggregate values are $0,1,4,17,70,282,1136,4583$.
Reflection after the first visit to $h$ gives $P(H\ge h)=\binom{2n}{n-h}/\binom{2n}n$ for positive integer $h\le n$.
A player who names a level $h$ and cashes on reaching it earns $hP(H\ge h)$.
Full knowledge of the shuffle gives $EH=(4^n/\binom{2n}n-1)/2$.
In the remainder write $P_n=EH$.
These two comparisons give square-root order for the ordinary game, rationality gives a structural obstruction to algebraic formulas, and the tail probabilities price several of the advice contracts exactly.
### An exact rule a player can remember
On 52 cards, **stop when $x>0$ and $(x+2)^2\ge t+8$**.
At three dollars, cash out with 17 cards left and draw with 19.
This mnemonic makes an optimal decision at every state through 31 pairs.
With 26 reds and 32 blacks left in a 32-pair game it first makes a strict mistake.
The sole reachable nonterminal tie on a standard deck occurs with one red and two blacks remaining. Optimal play reaches it with probability 7.78668%. Drawing returns zero, one or two dollars with equal conditional probability, and takes one, two or three additional draws. Taking cash returns one dollar immediately.
Taking every tie versus continuing through every tie gives the same expectation on 52 cards but changes the probability of zero winnings from 22.0521% to 24.6476%, and expected draws from 36.4516 to 36.6073.
In the grammar $x>0$ and $dt\le ax^2+bx+c$, the small integer rule $79t\le112x^2+109x+14$ is exact through 8,242 pairs.
Four strictly decided, reachable states of the 8,243-pair game rule out **every real-coefficient quadratic in that grammar**.
Its own first mistake requires 107 consecutive opening reds and costs about $1.2430\times10^{-38}$ dollars in expectation.
The integer verifier bounds its loss below $1.232\times10^{-7}$ dollars for every starting deck through 65,535 pairs.
Optimization over *states decided correctly* and optimization over *dollars lost* already part company on the first failing deck.
Each row below assumes $x>0$. The first three formulae are optimal everywhere on a standard deck. “Pairs” is the largest initial balanced deck for which the indicated run of exact results holds.
| Stop condition | Consecutive optimal range | First failure or limitation |
|---|---:|---|
| $(x+2)^2\ge t+8$ | Through 31 pairs | With 26 reds and 32 blacks left, the rule makes a strict error. |
| $3t\le x(4x+5)$ | Through 42 pairs | With 36 reds and 43 blacks left, it draws at seven dollars. |
| $79t\le112x^2+109x+14$ | Through 8,242 pairs | Its first loss from a balanced start is about $1.24\times10^{-38}$ dollars. |
| $(2x+1)^2\ge4\alpha^2t$ | Through 54 pairs from a balanced start | The 55-pair loss is about $2.067\times10^{-6}$ dollars. This rule follows the correct large-deck slope. |
A GMP integer computation and a column induction establish that this is the only neutral urn whenever **either remaining color count is at most 8,192**, with the other count unrestricted. Boyce conjectured uniqueness over all finite nonempty urns. The verification concerns the two actions available at a reached state. A strategy can still condition its choice at this tie on the history. [Proof and exact fractions](#new-ties)
## 2. A table-free player within one cent on every balanced deck
**Original hybrid.** For every integer $n\ge0$, the following rule has expected payoff strictly greater than $V_n-0.01$ dollars. On a 52-card deck it chooses an optimal action at every reachable state. The numerical all-deck upper bound is **0.9804191707 cents**. Individual shuffles can have larger differences in either direction. This is a bound on expected loss from the initial balanced state.
### What the certificate measures
**What the 0.98¢ buys.** At $N=482{,}620$, the first even deck priced by the large-deck branch of the *proof*, an independent directed calculation gives the following amounts. Here $G_\pi$ is the actual expected payoff and $H$ the attainable lower comparison; the rule’s switch during play remains at 65,536 cards.
| Component of $Q-H$ | Dollars, rounded | Interpretation |
|---|---:|---|
| $Q-V$ | 0.005846655 | The optimal player also falls this far short of the upper comparison. |
| $V-G_\pi$ | 0.000258477 | Expected loss a better player could actually recover. |
| $G_\pi-H$ | 0.003699061 | Slack in the policy's lower comparison. |
| $Q-H$ | 0.009804192 | Certified allowance. |
Only about **2.64%** of the allowance is actual regret at this deck. The upper comparison accounts for **59.63%**. Each addend has its own interval in the proof worksheet. At 1,048,578 cards the upper comparison also accounts for about 64% of the product bound for either of the re-centered players.
Over **every even starting size through 8,388,608 cards**, the original hybrid's maximal loss is **$0.00026340776136 at 326,148 cards**. The single half-card rule peaks at **$0.00002321858013 at 220 cards** and 79 then half-card peaks at **$0.00000004968697 at 78,622 cards**. The respective maxima of the two hybrids differ by a factor of **5,301**. A 92-fractional-bit dynamic program isolates the winners through 1,048,576 cards. A heat-kernel enclosure rules out every larger even deck up to 8,388,608. The global maxima across all decks remain open.
Beyond the switch the original hybrid and the unchanged 79-rule first differ on a reachable deal at **66,048 cards**. The first 215 draws must all be red; with 65,833 cards remaining the hybrid cashes $215 and 79 continues. The 79-rule earns more from that state. The opening gives an advantage between $5.335\times10^{-70}$ and $5.336\times10^{-70}$ dollars at that deck. A statewise directed comparison certifies strict superiority of the unchanged 79-rule at every even starting size from 66,048 through 8,388,608. At 131,070 cards the original hybrid's loss is about 4,875 times its loss at 65,536 cards; it builds over an interval of sizes.
**Decision rule for the original hybrid.**
1. At exhaustion take zero. At a nonpositive balance draw.
2. With $1\le t\le65{,}536$ cards remaining and a positive balance $x$, cash out iff $79t\le112x^2+109x+14$.
3. For $t>65{,}536$ set $s=\sqrt{t+1}$. Choose a squared slope $c_t$ with $0\le(\alpha-\sqrt{c_t})s\le1/256$. Cash out iff $(x+1)^2>c_t(t+1)$. This is the parity-compatible exercise score nearest $\sqrt{c_t(t+1)}$, with midpoint ties upward. The coefficient recipe below is part of the executable rule.
Here $\alpha=0.83992367569237\ldots$ is characterized by $(1-\alpha^2)A(\alpha)=\alpha$, where $A(y)=\int_0^\infty e^{yu-u^2/2}\,du$.
In the entire unsigned 64-bit remaining-card range one squared coefficient suffices:
$$
c_t=\frac{13{,}013{,}657{,}395{,}120{,}439{,}157}{2^{64}}.
$$
It is the downward 64-bit rounding of $(83992367569237/10^{14})^2$.
The proven bracket of width $10^{-14}$ for $\alpha$ gives the required boundary displacement even at $t=2^{64}-1$.
The implementation takes the high word of a multiply-add, squares an integer, and compares.
It has a short circuit for large profits.
There is no square root, division, precomputed policy table or per-deck setup on this domain.
The game driver handles exhaustion and sets the input profit to zero whenever the balance is nonpositive.
The following is the actual native decision function.
```c
/* C11 with unsigned __int128. t is the remaining card count.
profit is the positive part of the signed balance; 0 represents any loss or tie.
The game driver stops separately at exhaustion. Valid states satisfy profit <= t. */
#include
#include
bool p14_cent_stop(uint64_t t, uint64_t profit) {
if (profit == 0) return false;
if (t <= 65536)
return 79 * t <= 112 * profit * profit + 109 * profit + 14;
/* floor(2^64 * (83992367569237 / 10^14)^2).
The multiply-add is exact even when t = UINT64_MAX. */
const uint64_t beta = UINT64_C(13013657395120439157);
const uint64_t cutoff = (uint64_t)(((__uint128_t)beta * t + beta) >> 64);
if (profit >= UINT32_MAX) return true;
uint64_t k = profit + 1;
return k * k > cutoff;
}
```
For larger integers use the enclosed arbitrary-precision player `cent/native/play.py`.
It encloses the root by interval arithmetic, calculates a downward dyadic approximation to its square at a precision growing as half the bit length of $t$ plus guard bits, and compares integers.
It uses an enclosure even if the residual interval at a trial point contains zero.
This avoids an unproved assumption about algebraic independence or the impossibility of exact ties.
A single fixed decimal slope cannot support this guarantee for unbounded integers.
The theorem covers the specified coefficient recipe at the finite horizons, where its exact decisions were checked.
### Why the lower bound applies to the player who uses this code
A price enclosure does not by itself prove that a given player earns its lower endpoint.
The proof needs an attainable lower value for the **same rule** at the junction of its two branches.
The following inequalities do this without computing the optimal policy on all large decks.
With $Z_t$ an unrestricted fair sign walk, write $p_t(x)=P(Z_t=x)$, $F_t(x)=P(Z_t0.83$ for $s\ge256$. The cubic term is negative and $R_t(B_t)>0$ throughout the needed region. Thus cashing at $B_t$ earns at least $L_t(B_t)$. Two successive real targets differ by less than one even when the allowed dyadic slope changes. Rounding introduces at most two more dollars into the difference. Opposite parity excludes zero and two, so the exercise boundary moves exactly one unit per step. A path coming from below first reaches it at equality.
**At 65,536 cards.** The early boundary is 216 at the switch, and the 79-rule takes 216. Every surviving even score is at most 214. An integer Bellman calculation for the **fixed** 79-rule rounds its weighted means downward. A zero lower bound on the remote negative edge is valid since the rule pays only nonnegative balances. A separate outward interval recurrence evaluates $F/p$ and $R$. It checks the required comparison for all **32,876** possible surviving scores, including the negative physical edge $x=-65{,}536$. The unweighted fixed-point checker certifies $\lambda=197356261/10^9<1/5$. This single check covers all larger initial decks. The integer check is in `cent/analytic/cutoff79.c`.
**At the initial state.** The normalized correction $R_0(0)=1$ obeys
$$
\frac{R_{2j+2}(0)}{R_{2j}(0)}=1-\frac{2}{5(2j+1)}=\frac{10j+3}{10j+5}.
$$
It is positive and strictly decreasing.
The estimate $R_N(0)/5<0.137/(N+1)^{1/5}$ suffices from 482,618 total cards, the first even $N$ above the fifth-power cutoff.
For multiplier $1/5$ the exact product first crosses below one cent at **233,631 pairs (467,262 cards)**. Using the smaller verified multiplier $0.197356261$ and the actual product, the bound first falls below one cent at **437,186 cards (218,593 pairs)**.
Its value there lies between **0.00999999107122 and 0.00999999107123 dollars**.
This is the first crossing for the specified upper bound.
At the largest measured loss, actual regret is about 0.02634 cents. The table in Section 2 gives the finite maximum and its starting deck.
The scalar check is in `cent/analytic/cent_product.py`.
Lean independently proves this threshold and the resulting all-size scalar cap in `cent/formal/CentPolicyCap.lean`.
**Smaller decks.** One backwards DP solves all initial sizes at once because every even $t$ has a balanced state $x=0$. Two separate rows evaluate the clipped optimum and the fixed rule. The artificial walls are at $x=\pm3072$. Reflection bounds the change to each root, and rounded integer arithmetic bounds the remaining calculation error. In $2^{-32}$-dollar units the largest certified upper bound through **482,618** cards is **2,075,264**, or **0.0004831850528717041015625 dollars (0.04831851 cents)**. This number bounds an average over equiprobable shuffles. All 241,309 nonempty even roots passed. A pinned CPU is unnecessary for correctness. One scan took about six seconds on an AMD EPYC 9V74. Checking coefficient rounding at every layer bridges the mathematical and native rules. The zero-card case pays zero. The finite and infinite ranges overlap by more than 45,000 cards. Evaluating the decreasing product at 482,620, the first even size beyond the sweep, sharpens the uniform all-size guarantee to **0.009804191707 dollars (0.9804191707 cents)**.
On one AMD EPYC 9V74 core the supplied native player took **1.94 ns per call** for short horizons, **1.67 ns** for long horizons and **2.29 ns** for a mixed workload.
These are median throughputs from nine rotated blocks of 1,048,576 calls, using GCC 14.2, a separate function call, and 8,192 warm, pre-generated inputs per workload.
Scores were deliberately near the decision boundary.
The timed loop includes input loads and an output checksum.
It excludes dealing, initial input generation and I/O.
See `cent/native/bench_play64.c` and its CSV for replay.
A player needs neither certificate during play.
The integer verifiers, proof of the tail comparison, data at the crossover, finite-tree regret lemma, and arithmetic proof for the native comparison are included below.
The all-deck theorem for this specific policy combines previous game theorems, new mathematical arguments and independently runnable integer checks.
The entire chain for this policy has not been re-expressed as a single Lean theorem.
No lower bound on instruction count or on worst-case regret among all table-free programs is asserted.
### Moving the exercise boundary by half a dollar
A player can use the single test **stop when $x>0$ and $(2x+1)^2\ge4\alpha^2t$**. A second player keeps the 79-rule through 65,536 cards remaining and uses this half-card test earlier. Both have expected regret below **0.7647297 cents** for the first player and **0.7645408 cents** for the second, on every balanced deck. The proof uses the exact slope or the specified dyadic implementation, a new exercise-contact estimate, a pointwise terminal certificate and a directed finite sweep. The supremum is much smaller throughout the measured range.
| Player | Largest expected loss on every balanced deck through 482,618 cards, in cents |
|---|---:|
| 79-rule in the endgame, original boundary earlier | Between 0.02634075350 and 0.02634079877 |
| Half-card rule throughout | 0.002321858013…; exact maximum at 220 cards |
| 79-rule in the endgame, half-card boundary earlier | Between 0.00000496323 and 0.00000497417 |
These earlier interval bounds already give a factor above 5,295. The larger sweep isolates the two peaks and gives 5,301.34. The half-card rule alone exactly prices every starting deck through 108 cards. At 110 its first expected loss is $2.06703676\times10^{-6}$ dollars. The later heat-kernel certificate extends the 220-card maximizer through **8,388,608 cards**. The original hybrid’s two losses at 65,536 and 65,538 are both about $4.14\times10^{-8}$ dollars. Its peak develops hundreds of thousands of cards later. At 20,000 cards the 79-rule loses about $1.6\times10^{-9}$ dollars, while half-card alone loses $4.5\times10^{-6}$. Comparing against an always-on displaced Brownian boundary would miss what the original small-deck branch achieves.
The analytic change is small. The old comparator subtracts $x/t$ and its boundary falls on the favorable side of the Brownian tangency. Moving the exercise point can put it slightly on the other side. Subtract $(17/8)x/t$ instead. That term still vanishes at a balanced start, but now covers the exercise error on either side. With the cubic correction recalibrated, the cutoff and product estimates then apply to the payoff of the new player. The conjectural global bound **0.003 cents** remains much sharper than the proven global bound. [Finite certificate](#proof-frontier-regret) · [Global comparison](#proof-half-tail)
The following are independent long-double measurements from Fable’s sweep. The four regret columns are in dollars per deal. The last column refers to optimal play, which takes cash at the single verified tie.
| Starting cards | Original hybrid | Always 79 | Half-card alone | 79 then half-card | Chance of zero under optimal stop-on-ties play |
|---:|---:|---:|---:|---:|---:|
| 65,536 | 4.14e−8 | 4.14e−8 | 3.29e−6 | 4.14e−8 | 4.3161% |
| 131,070 | 2.02e−4 | 1.23e−7 | 2.76e−6 | 4.11e−8 | 3.6772% |
| 482,618 | 2.58e−4 | 5.06e−7 | 2.02e−6 | 2.44e−8 | 2.7207% |
| 8,388,608 | 1.53e−4 | 3.95e−6 | 1.04e−6 | 9.74e−9 | 1.4061% |
The ratio between the always-79 rule’s growing asymptotic loss and the old hybrid’s vanishing loss eventually diverges. The suggestion that they cross near a billion cards extrapolates two fitted or asymptotic curves. The actual all-deck maxima and first one-cent crossing of an unchanged 79-rule remain open. [Peak isolation, dominance and decomposition](#proof-regret-audit)
## 3. Which exact formulas exist?
**The game-specific obstruction is non-P-recursiveness.** The one-variable sequence of exact prices satisfies no eventual homogeneous linear recurrence with polynomial coefficients. This excludes fixed sums of hypergeometric expressions and many natural factorial formulae. A separate representation theorem explains how a fixed arithmetic term can nevertheless encode the whole finite search: Kalmár-elementary functions admit fixed arithmetic representations in an appropriate language. The report provides the concrete term and its operand sizes. [Marchenkov 2007](https://doi.org/10.1134/S1990478907030106 "Superpositions of elementary arithmetic functions")
A useful impossibility statement specifies both the function and the grammar.
For the balanced diagonal $n\mapsto V_n$ the classification is as follows.
| Language or representation | Result and justification |
|---|---|
| A fixed polynomial relation $P(n,V_n)=0$ with real coefficients | Impossible eventually. In fact the coincidence set for any nonzero $P$ has density zero. Rational payoffs reduce a putative relation to rational coefficients on its coincidence set. Hilbert irreducibility excludes nonlinear factors on a density-one set. Square-root growth excludes rational functions. |
| Finitely many algebraic candidate formulas and any selector | Impossible by multiplying their polynomial relations. The value for each *particular* integer $n$ is rational. |
| Eventual homogeneous fixed-order linear recurrence with polynomial coefficients (P-recursiveness) | Impossible by the frontier–Taylor-gap argument. Equivalently the ordinary generating function fails to be D-finite. This is a separate theorem from nonalgebraicity of a function of $n$. |
| Rational and geometric factors times ratios of integer-affine factorials, fixed sums of hypergeometric terms, stated rational-slope Gamma products, or multiple binomial sums of the standard holonomic class | Excluded by the recurrence result. An arbitrary quotient of sums need not be holonomic. |
| Arbitrarily nested factorials or positive-argument Gamma with *field* arithmetic alone | Open for the balanced diagonal. The presence of division does not grant integer quotient. |
| A sum indexed by paths and possible stopping sets | Exists and is kernel-checked for every finite deck. Large instance sizes make it impractical. |
| A fixed term using ordinary factorial, arithmetic and Euclidean integer quotient, followed by final rational division | Exists. One can build variable powers using factorials and integer quotient, then encode a bounded search by arithmetic. |
| A fixed real expression using arithmetic, exponentiation and trigonometric/inverse trigonometric functions | Exists with no lookup constant containing the answers. It encodes all candidate tables and extracts the unique correct one. |
For the **two-variable** urn, a separate Lean theorem excludes an integer-polynomial rational function with denominator nonzero on all nonnegative integer count pairs.
Its proof exploits entire constant regions of the stopping table.
A theorem for all pairs of counts need not have the same consequence on the balanced diagonal.
The mechanism of the strongest negative result is worth inspecting.
Count total winnings over all shuffles.
The optimal exercise frontier has a nondecreasing integer gap of order at most square root and growing without bound, hence arbitrarily long plateaus.
Extending the continuation equation past exercise turns these plateaus into arbitrarily long strings of specified Taylor coefficients followed by a nonzero coefficient.
A hypothetical D-finite equation imposes a *uniform* bound on such gaps across a family of transformed series.
The differential-operator uniformity is essential.
The full derivation specifies the transformation, differentiations, exceptional indices and coefficient bounds.
Parts of the discrete construction and the terminal gap implication are formalized.
The analytic contradiction is a written proof.
The mechanism of the positive result is almost the opposite.
Pack every possible integer Bellman table in disjoint digit fields, compute the local constraint violations in parallel, and select the uniquely valid table.
Division, bitwise conjunction implemented by arithmetic, and digit extraction recover its diagonal.
The fixed term has finite syntax independent of $n$.
For four cards one intermediate space estimate alone is roughly **1.45 yottabytes** to recover $2/3$.
Syntactic brevity has hidden the search in operand length.
The explicit expression and its all-size mathematical derivation are included in the mathematical appendices.
## 4. Computing the price at the precision the caller needs
For a real Brownian threshold $\alpha$ define $K=(1-\alpha^2)\sqrt\pi=0.52203767598712386653837103312280527\ldots$.
For every integer $n\ge0$ pairs the finite discrete game satisfies
$$
K\sqrt n-\frac{0.137}{(2n+1)^{1/5}}\le V_n\le K\sqrt{n+1/2}.
$$
Thus the leading price per square root of the **total** card count is $K/\sqrt2=0.3691363807\ldots$.
The distinction between the two normalizations explains apparently different constants.
The absolute dollar error tends to zero.
The displayed exponent bounds the value error and gives no sharp asymptotic expansion of the optimal discrete frontier.
| Pairs | Total cards | Certified quote in dollars | Rounded cent |
|---:|---:|---:|---:|
| 26 | 52 | 41,984,711,742,427 / 15,997,372,030,584 | 2.62 |
| 32,768 | 65,536 | [94.484004, 94.499635] | Several cents possible from this enclosure |
| 133,787,000 | 267,574,000 | [6038.215406, 6038.218246] | **6038.22** |
| 500,000,000 | 1,000,000,000 | [11673.115131, 11673.117310] | **11673.12** |
| $10^{12}$ | $2\times10^{12}$ | [522037.675512, 522037.675988] | **522037.68** |
| $10^{30}$ | $2\times10^{30}$ | [522037675987123.866537, 522037675987123.866539] | **522037675987123.87** |
The original nine-day run's body and summary differ in the historic answer by ten cents.
The certified interval resolves it as **6038.22**. The spectral-amplitude fit predicts **6038.21688**. Its extra digits are an extrapolation.
The arbitrary-precision Python quote handles the last row.
For fixed machine words, the large-deck program needs two square-root endpoints and an integer fifth-root allowance.
It can return a range of possible cents if rounding is ambiguous.
The guarantee for a *player* in §2 applies to all decks, even when this price enclosure straddles a half-cent.
| Deliverable | Method and measured scope |
|---|---|
| Exact reduced fraction | Integer aggregate DP. First negative excursions return to zero before a profitable stop and produce a Catalan convolution. Packed arithmetic and cyclic transforms modulo $2^M+1$ reduce the cost. At 8,192 pairs the exact transform took 1.13 s in one comparison, at 24,000 pairs 18.51 s. |
| All diagonal numerators through $n$ | Two adjacent coefficient sequences trace the stopping frontier in $\widetilde O(n^2)$ bit operations. At measured sizes the cyclic transform was faster. |
| Tight numeric interval | `catalan` compresses the return kernel into 208 sums and verifies the error on the needed coefficients. `heat` weights by the free-walk mass and uses fixed-point heat updates. At a million pairs their intervals were about $1.82\times10^{-7}$ and $1.77\times10^{-9}$ dollars wide, taking 0.401 s and 1.99 s on the benchmark host. |
| Direct independent large-deck certificate | A moving comparison boundary, two directed Bellman cutoffs, and reflection/survival bounds recover the historic cent in roughly 65 s and the billion-card cent in roughly 78 s in the original measurements. |
| Large-deck price using proved constants | Compute the two scalar endpoints. Deck-independent finite inequalities and a scalar root enclosure are verified once. A warm C batch originally took 319 ns per distinct quote near the historic example. |
The appendices include the Bellman implementation, both exact solvers, approximation algorithms, wall corrections, proof constants, more precision and timing details, and the independent integer checkers.
### Checking the published numerical benchmark
Let $n$ count red–black **pairs** and $N=2n$ count physical cards.
The historical computation used $n=133{,}787{,}000$, hence $N=267{,}574{,}000$.
The article’s body reports **$6,038.22**, which the subsequent certified implementation confirms to the cent.
Its abstract says $6,038.32, the rounded value of the *refitted prediction* $6,038.32303.
The article's leading-constant conjecture also needs correction.
The coefficient is $0.522037675987\ldots$ per $\sqrt n$, or $0.369136380725\ldots$ per $\sqrt N$.
The true coefficient exceeds 0.5 in pair units by 4.41% of 0.5. Equivalently, 0.5 underestimates the true coefficient by 4.22%.
The two reported timing units disagree. The reported 184,331 CPU-core-minutes are 128.01 CPU-core-days, while the same sentence reports 51.
Nine calendar days are compatible with either figure at different levels of parallelism. The surviving article alone does not decide which counter was recorded. [Gwern et al. 2022](https://gwern.net/problem-14#blocks-skipping "Problem 14 Dynamic Programming Solutions")
The regression output can be reconstructed from the posted data.
Keep $n=1,\ldots,22974$, append the article’s $(100000,165.076)$, and fit an intercept in each model.
The 22,975 observations come from a floating-point table and the separately reported 100,000-pair value.
Here “residual s.e.” means $\sqrt{\mathrm{SSE}/\mathrm{df}}$ on these points. [FeepingCreature 2022](https://gwern.net/doc/statistics/decision/2022-10-03-feepingcreature-problem14-bottomup-values0to22974.txt "Original numerical data") · [Gwern et al. 2022](https://gwern.net/problem-14#approximating "Approximating")
| Fit | Intercept | Coefficient of $\log n$ | Coefficient of $\sqrt n$ | Residual df | Residual s.e. |
|---|---:|---:|---:|---:|---:|
| Square root | −0.01870094 | | 0.52208844 | 22,973 | 0.00186698 |
| Log plus square root | −0.05411623 | 0.00555158 | 0.52194214 | 22,972 | 0.00030495 |
| Square root after appending the record point | −0.01462286 | | 0.52204804 | 22,974 | 0.00245711 |
The article’s first square-root output matches inclusion of $n=0$, despite the displayed code dropping that observation.
Its printed joint fit, with coefficients $(-26.6931,4.40946,0.391493)$ and 91,897 residual degrees of freedom, is reproduced by pooling the original responses with the predictions from the three fitted models.
The displayed plotting code creates precisely these four groups *after* that output.
The final square-root regression agrees with a clean fit to the positive observations and the historical record.
Its quoted 0.0017% relative error is in-sample. Ordinary regression $t$-statistics on this deterministic sequence do not establish a limiting coefficient, intercept or convergence rate. [Gwern et al. 2022](https://gwern.net/problem-14#approximating "Source and regression output")
Two defects affect specific listings.
The first bottom-up C driver recomputes the entire $(i+1)$-square for each $i=0,\ldots,L$, so producing its whole list costs $\Theta(L^3)$ arithmetic operations. A single square takes $\Theta(L^2)$, and the same square already contains all smaller diagonal answers.
The driver allocates two float rows per invocation and never frees them. At $L=100000$ the allocations total 40,001,200,008 bytes before allocator overhead on a four-byte-float implementation.
Separately, the intermediate “Blocks” listing assigns to an undeclared variable `count` and fails a C11 syntax check. The final “Blocks + Skipping” listing declares it.
The historical linker ceiling depended on the platform and layout. With GCC 14.2 on x86-64, the final source linked at both 133,787,000 and 133,788,000 pairs. At 140,000,000 and 200,000,000, the default build failed with a PC-relative relocation overflow, and `-mcmodel=medium` linked both. These were build tests. [Gwern et al. 2022](https://gwern.net/problem-14#c "C port") · [Gwern et al. 2022](https://gwern.net/problem-14#blocks "Blocks") · [Gwern et al. 2022](https://gwern.net/problem-14#blocks-skipping "Blocks + Skipping")
The fixed-width beam conjecture has a probabilistic obstruction.
At the halfway draw $S_n=2X-n$, where $X$ is hypergeometric with population $2n$, $n$ successes and sample size $n$.
Thus $\operatorname{Var}(S_n)=n^2/(2n-1)$, and the largest individual point mass is $\binom{n}{\lfloor n/2\rfloor}^2/\binom{2n}{n}=O(n^{-1/2})$.
A fixed-width central band therefore retains a vanishing fraction of the halfway probability.
If the game pays zero on exit and permits exercise only inside $|S|\le w$, its payoff is at most $w$, whereas the true price grows as $\sqrt n$.
This refutes that literal truncation at fixed absolute dollar accuracy. For a certified band implementation with a reflection tail bound, width of order $\sqrt{n\log(n/\varepsilon)}$ suffices for absolute price error $\varepsilon$. The corresponding state count is an upper bound for that method. An algorithm that values excursions analytically or compresses the exterior states has a different error analysis. [Gwern et al. 2022](https://gwern.net/problem-14#faster "Faster?")
#### Suggested diffs to the original Gwern.net article
The 52-card answer survives rechecking. All **729 cells** in Han Zheng’s spreadsheet agree with rational Bellman values to their displayed precision. The record computation’s **$6,038.22** also survives. The substantive corrections concern what was being counted, what the statistical fits measured, and what several programs actually compute. Line numbers below refer to the original Markdown. [Branwen et al. 2022](https://gwern.net/problem-14.md "Problem 14 Dynamic Programming Solutions, Markdown source") · [Coldwell 2006](https://puzzles.nigelcoldwell.co.uk/fourteen.htm "Answer to Puzzle #14")
| Location in the original | Suggested edit and evidence |
|---|---|
| Description and abstract, lines 3–25 | Use **red–black pairs** for the solver parameter. The record was 133,787,000 pairs, or 267,574,000 cards. The body’s $6,038.22 is the computed price rounded to cents. The abstract’s $6,038.32 is the refitted prediction. The limiting coefficient is 0.522037675987 per square root of pairs, or 0.369136380725 per square root of total cards. Also give the book author’s surname, Crack. Coldwell numbers this item 14 in his collection. [Coldwell n.d.](https://puzzles.nigelcoldwell.co.uk/ "A Collection of Quant Riddles With Answers") |
| Model and betting variant, lines 34–54, 142–143 | The finite score is a random-walk bridge. Its scaling limit is Brownian. The $2.86 bug mixes fair interior coin flips with finite-urn edge payoffs. It reproduces $805867616040669/281474976710656$. With genuine replacement each increment has zero conditional expectation, so the expected stopped score is zero at every bounded stopping time. In the separate wagering game $9.08 is the final bankroll on a $1 stake; the profit is $8.08. |
| R, Haskell and the first bottom-up C program, lines 173–242, 392–445 | $6.21519192$ is for **143 pairs**, or 286 cards. Repair the R plot’s detached `+`. Size the Haskell table from its arguments. Its boxed rectangle uses quadratic space. Make the C program emit every diagonal price during one two-row sweep. The original repeated a quadratic calculation for every input through $L$, taking cubic time overall, and retained every allocation. The new driver takes quadratic time and linear space for the whole list. |
| Parallel C, lines 680–835, 846–1213 | Use actual C11 atomic objects for the spin flags and shared skip markers. Declare `count` in the intermediate Blocks example. Enforce its stated block-divisibility requirement: 26 pairs with block size 5 previously produced $4.47141$ instead of $2.62448$. Make the 100,000-pair PGO commands select that workload explicitly. The balanced price survives swapping color labels in the C array and block examples; the state-by-state policy needs the labels swapped back. |
| Historical runs, lines 1233–1239 | **$818.10 at two million pairs is wrong.** A separate directed-integer Bellman calculation gives $738.2692221632 < V < 738.2692221666$, hence **$738.27**. Two million *total cards* would pay **$522.03**. The nine-day wall time is reported independently of the two conflicting CPU-time figures: 184,331 core-minutes is about **128.01 core-days**; 51 core-days is **73,440 core-minutes**. The surviving record does not identify the intended counter or how $818.10 arose. |
| Caching and truncation, lines 1243–1260 | A cached root price answers a repeat query. To extend a Bellman computation one needs a separating frontier, such as the outer row and column of the saved square. A fixed-width central beam with zero on exit caps the possible payoff at its width while the true price grows as the square root of deck size. An approximation that models the omitted region separately needs its own error analysis. |
| Input data and regression, lines 1262–1362 | The published input table ends with its only decrease, 79.111328 followed by 79.11. The corresponding actual prices round to **79.114807** and **79.116529**. The first square-root transcript includes the zero-pair row that the displayed R drops. Pooling observations and three sets of fitted values reproduces the joint model’s **91,897** residual degrees of freedom. Fitting only the positive observed sizes gives **22,972**. Keep the observed data and graphing data in separate frames. [FeepingCreature 2022](https://gwern.net/doc/statistics/decision/2022-10-03-feepingcreature-problem14-bottomup-values0to22974.txt "Published 0–22,974-pair values") |
| New closing section | Give an optimal standard-deck rule readers can use by hand: stop at positive $x$ when $(x+2)^2\ge t+8$. Explain the single tie. This addition answers the question directly; it is a later result, separate from corrections to the 2022 computation. |
**What the regression predicts.** On the original positive-size inputs the square-root model extrapolates to $6,038.786647, about **57¢ high**. After the rounded record enters the fit, the fitted value becomes $6,038.323464, about **10¢ high**. The extra logarithmic term reduces training residual error roughly sixfold yet misses the held-out price by **$1.06**. The historical formulas printed with rounded coefficients yield slightly different last digits. The fitted near-zero intercept and the in-sample percentage do not establish an asymptotic formula.
**What the data file preserves.** A replay of the article's float recurrence matched the **first 22,974 printed rows byte for byte** on GCC 14.2 with `-O2 -march=native -ffp-contract=fast`. The next result was **79.113052**. Thus 79.11 is a prefix of the reconstructed historical line. Replacing missing digits would still leave the mathematical value low. Directed integer bounds distinguish more widespread single-precision error: **12,323 of the 22,975 printed values** differ from the true prices by more than $0.001. On ordinary nearest-cent rounding (half up), **3,029 entries** produce the wrong cent, beginning at **973 pairs**. The patch preserves the downloaded table as the historical regression input. Substituting independently bounded prices at the same training sizes moves the record prediction from $6,038.78665 to $6,039.10546, about **32¢ farther** from the record. The historical numerical noise happened to help this particular extrapolation.
**Checking the patch.** The appendix includes the exact preimage, patch, source-data checkers and verification notes under `review/article-edits/`. The original article’s Git blob is `c60a141c600681b8dc02fc0c9db3c471cd8a7d3e`, and its SHA-256 is `538f1e66ee5ef335f9aea2117da57fa66a2271c66feb071b4a984b71a2a41210`. The patch targets `problem-14.md` at the root of the site **content** checkout. Both `git apply` and `git am` reconstructed the reviewed postimage from the clean preimage. Pandoc parsed the postimage, including the added section and existing code fences. R, C and Haskell were exercised on test inputs, including the published regression observations. The Neat shuffle observation follows from inspection of the modulo sampling. The historical nine-day runtime and CPU totals have no independent replay here.
Unified diff against the published article
````diff
diff --git a/problem-14.md b/problem-14.md
index c60a141c600681b8dc02fc0c9db3c471cd8a7d3e..19353e123fd6ae7cbf896fe7c7ecd61949509165 100644
--- a/problem-14.md
+++ b/problem-14.md
@@ -1,9 +1,9 @@
---
title: "Problem 14 Dynamic Programming Solutions"
-description: "Timothy Falcon's quantitative-finance interview problem #14 asks for the optimal stopping strategy when playing a card-drawing game of l cards where red = +$1 & black = −$1; the value approaches 0.5 × √l. I re-solve it with dynamic programming in R, and others in Neat, Haskell & C, with increasing efficiency."
+description: "When should you stop drawing from a shuffled deck of red (+$1) & black (−$1) cards? Dynamic programming in R, Neat, Haskell & C gives the optimal expected payoff: $2.62 on 52 cards, rising asymptotically as 0.522038 times the square root of the number of red–black pairs."
author: Gwern, FeepingCreature, nshepperd, Khoth
created: 2022-10-02
-modified: 2022-10-17
+modified: 2026-12-04
thumbnail: /doc/cs/r/gwern-problem14-49randomgamesinr.jpg
thumbnail-text: "Graph of simulation of winnings over a sample of 49 Problem-#14 games using optimal strategy."
thumbnail-css: "outline"
@@ -18,34 +18,34 @@ css-extension: dropcaps-yinit
>
> It can be treated as a multi-stage decision problem and solved by top-down & bottom-up [dynamic programming](!W), to estimate the value of optimal play (and thus provide the actual optimal strategy). The value of a game with a standard deck of 52 (26 good vs 26 bad) cards is ~\$2.62; the value increases as the square root of cards.
>
-> Naive implementations which take hours or error out can be optimized down to milliseconds. We build on the original spreadsheet answer by providing a top-down DP (naive [memoization](!W)) implementation [in R](#r) (verified [in simulation](#simulation-check)), Neat implementations ([naive](#neat) & optimized to [use arrays](#neat-array)), and an optimized [C version](#c-array); these have 𝒪(_l_^2^) time/space computational complexity, limiting their range. Then we provide the more efficient [bottom-up](#bottom-up-dp) solution in [Haskell](#haskell) & [C](#c), which need 𝒪(_l_^2^) time but only 𝒪(_l_) space.
+> Naive implementations which take hours or error out can be optimized down to milliseconds. We build on the spreadsheet with top-down [dynamic programming](!W) [in R](#r) (checked [in simulation](#simulation-check)), [Neat](#neat) & [Neat arrays](#neat-array). The [Haskell](#haskell) & [C array](#c-array) examples keep a full table. The [two-row C version](#c) computes the same values in 𝒪(_l_^2^) arithmetic operations and 𝒪(_l_) space, where _l_ counts red--black pairs.
>
-> While it's not easy to change the 𝒪(_l_^2^) complexity without problem-specific analysis or approximation, modern computers are *so* powerful that by improving the constant factors, we can still calculate shockingly high card counts. The efficient C bottom-up can [be made faster](#c-diagonal-bottom-up) by careful use of parallelism at the CPU-core level using vector instructions, and then by [breaking the problem up](#blocks) into individual DP problems which can be solved independently in different CPU threads or processes.
+> While it's not easy to change the 𝒪(_l_^2^) complexity without problem-specific analysis or approximation, modern computers are *so* powerful that by improving the constant factors, we can still calculate shockingly high card counts. The efficient C bottom-up can [be made faster](#c-diagonal-bottom-up) by careful use of parallelism at the CPU-core level using vector instructions, and then by [breaking the problem up](#blocks) into blocks. Blocks whose top and left edges are ready can run concurrently on different cores.
>
-> This final version lets us calculate values of Problem 14 from the original 52 cards up to 133.7 million cards (value of \$6,038.32), and [fit approximations](#approximating) which confirm the conjecture that it increases as a square-root. (An approximation yields <0.002% relative error at 133.7m card count.)
+> The largest deck I computed in 2022 contained **133,787,000 pairs**, or **267,574,000 cards**. Its optimal expected payoff rounds to **\$6,038.22**. A [square-root regression](#approximating) predicted the result to within 0.01%; the smaller 0.0017% error comes from refitting with this result included.
-[Nigel Coldwell's](https://puzzles.nigelcoldwell.co.uk/) [2006 interview problem #14](#coldwell-2006) page discusses a simple gambling game:
+[Nigel Coldwell](https://puzzles.nigelcoldwell.co.uk/) lists this as [problem #14](#coldwell-2006) in his collection of interview puzzles from Timothy Falcon Crack’s _Heard on the Street_:
> You have 52 playing cards (26 red, 26 black). You draw cards one by one. A red card pays you a dollar. A black one fines you a dollar. You can stop any time you want. Cards are not returned to the deck after being drawn. What is the [optimal stopping](https://en.wikipedia.org/wiki/Optimal_stopping) rule in terms of maximizing expected payoff?
>
> Also, what is the expected payoff following this optimal rule?
This is a fun problem because the sampling-*without*-replacement makes it counterintuitive---you are so used to [sampling-with-replacement](https://en.wikipedia.org/wiki/Simple_random_sample) that the changing probabilities and the 0-EV-by-construction throws you for a loop.
-First, you think that it has to be 0 EV because the payoffs neutralize each other and so you shouldn't play at all; then you think that you ought to quit as soon as you are negative to cut your losses; both are wrong, and optimal play can go quite negative before quitting, because it 'knows' that the good cards are still in the deck and must then be coming up and it still has a chance to exploit a [random walk](https://en.wikipedia.org/wiki/Random_walk) up to >$0 to eke out a profit.
+First, you think that it has to be 0 EV because the payoffs neutralize each other and so you shouldn't play at all; then you think that you ought to quit as soon as you are negative to cut your losses; both are wrong, and optimal play can go quite negative before quitting, because it can always draw to the end for zero. Cashing a negative balance is strictly worse, and it can still exploit a [random walk](https://en.wikipedia.org/wiki/Random_walk) up to >$0 to eke out a profit.
And this problem is not as artificial as it might sound, as [Stas Volkov](https://x.com/stasyuha/status/1571826308929425410) points out that it corresponds to some scenarios in quantitative finance.
-The fact that it starts & ends at 0 makes it a special case of a ["Brownian bridge"](!W "Brownian bridge") process, which is a [Brownian random walk](https://en.wikipedia.org/wiki/Wiener_process) which is required to start & end at specific values; such processes cover things like financial bonds (eg. a [zero-coupon bond](https://en.wikipedia.org/wiki/Zero-coupon_bond)), whose prices may walk up & down but must end at a specific redemption value, or stock share prices if they are affected by [stock pinning](!W "Pin risk") which drives their price to a specific value (set by [options](https://en.wikipedia.org/wiki/Option_(finance)) on them).
+The score is a simple random walk conditioned to return to 0 at the last draw. Rescale time to the unit interval and divide the score by the square root of the initial number of cards: its limit is a [Brownian bridge](!W "Brownian bridge"). A pinned endpoint also arises in models for financial bonds (eg. a [zero-coupon bond](https://en.wikipedia.org/wiki/Zero-coupon_bond)), whose prices may walk up & down but must end at a specific redemption value, or stock share prices if they are affected by [stock pinning](!W "Pin risk") which drives their price to a specific value (set by [options](https://en.wikipedia.org/wiki/Option_(finance)) on them).
The ability to quit the game at any time then corresponds to selling or to exercising an ["American" option](https://en.wikipedia.org/wiki/Option_style#American_and_European_options) (which can be exercised at any time).
Optimal stopping, then, is simply how to trade so as to make as much money as possible.
General solutions to this problem of optimal stopping on a Brownian bridge are given in [Ekström & Wanntorp 2009](/doc/statistics/probability/2009-ekstrom.pdf "Optimal Stopping of a Brownian Bridge").
# Non-Optimal Stopping Version
-Suppose you have instead the betting version of this: you start with \$1, draw from a 52-card deck, and can bet any amount at 1:1 odds each time; what final return on investment could you guarantee?
+Suppose you have instead the betting version of this: you start with \$1, draw from a 52-card deck, and can bet any amount at 1:1 odds each time; what final bankroll could you guarantee?
Because you are choosing how much to bet each time, rather than being passively exposed to the slings and arrows of outrageous fortune, similar to the [Kelly coin-flip problem](/coin-flip "‘The Kelly Coin-Flipping Game: Exact Solutions’, Gwern et al 2017"), you can potentially earn much more; at a minimum, you know the last card drawn, and can end with \$2.
-The answer is ~\$9.08, as explained by [Scott](https://x.com/WindingNumber/status/1927000727307563401) with a [probability matching](!W) [Kelly-like 'ensemble of strategies'](!W "Kelly criterion#Multiple outcomes"):
+The largest guaranteed final bankroll is ~\$9.08 (a net profit of ~\$8.08 on the original \$1), as explained by [Scott](https://x.com/WindingNumber/status/1927000727307563401) with a [probability matching](!W) [Kelly-like 'ensemble of strategies'](!W "Kelly criterion#Multiple outcomes"):
> If you pick a possible sequence, and bet all-in on it every go, you win 2^52^ if you hit, otherwise go broke and stop.
>
@@ -140,7 +140,7 @@ This will run in something like 𝒪(_l_^2^) time+space in cards, where 26 is sm
## R
The tricky part here---which tripped me up initially & yielded a value of \$2.86 by accidentally leaving the probability of good/bad cards fixed at _P_ = 0.50 the entire game---is that the _P_ of good/bad is *itself* dependent on the state: the more of the good cards that get used up, the higher the probability of a bad draw and vice-versa, so the probabilities are constantly changing to push back towards the middle.
-(The EV being higher than the correct EV is a hint as to the error: if the _P_ remains at 0.5 the entire game, perhaps because we were sampling with replacement instead, then the value will be higher because there will be no 'reversion' from using up the good cards---we can always ride good luck still higher.)
+(That \$2.86 result mixed two models: it kept 50:50 draws in the interior but still let the player collect all remaining red cards when the black cards ran out. With genuine fair sampling *with* replacement and at most 52 draws, the balance is a martingale, so every stopping rule has expected payoff zero.)
My slow but easy [R](!W "R (programming language)") implementation:
@@ -170,7 +170,7 @@ sapply(0:26, function(t) { mV(t, t, 0); }) ## grows as 𝒪(√cards):
# [27] 2.624475549
~~~
-This is an easy enough problem that with no further optimization, the code runs near-instantly (all the way up to 143 cards, worth \$6.21519192, where it hits a stack limit) & we confirm that Han Zheng's value \$2.62 is correct.
+This is an easy enough problem that with no further optimization, the code runs near-instantly (all the way up to 143 pairs (286 cards), worth \$6.21519192, where it hits a stack limit on my machine) & we confirm that Han Zheng's value \$2.62 is correct.
### Simulation Check
@@ -206,7 +206,7 @@ Simulating 49 sample games, we can see how while the optimal strategy looks fair
~~~{.R .collapse}
simulateGameLog <- function(cards, ith) {
- df <- data.frame(ID=ith, Rounds=seq(1:(cards*2)), Winnings=rep(NA, cards*2))
+ df <- data.frame(ID=rep(ith, 2*cards), Rounds=seq_len(2*cards), Winnings=rep(NA_real_, 2*cards))
rounds <- 0
good <- cards; bad <- cards; winning <- 0;
playing <- TRUE
@@ -223,12 +223,12 @@ simulateGameLog <- function(cards, ith) {
winning <- winning+1; good <- good-1; } else
if (bad>0) { winning <- winning-1; bad <- bad-1; }
- df$Rounds[rounds] <- rounds; rounds <- rounds+1
+ rounds <- rounds+1
df$Winnings[rounds] <- winning
}
}
}
- return(df);
+ return(df[seq_len(rounds), , drop=FALSE]);
}
df <- data.frame()
@@ -238,8 +238,8 @@ for (i in 0:48) {
library(ggplot2)
p <- qplot(x=Rounds, y=Winnings, data=df)
-p + facet_wrap(~ID) + geom_line(aes(x=Rounds, y=Winnings), size = 3)
- + xlab("Card Draw #") + ylab("Winnings ($)") + theme(legend.position = "none") +
+p + facet_wrap(~ID) + geom_line(aes(x=Rounds, y=Winnings), size = 3) +
+ xlab("Card Draw #") + ylab("Winnings ($)") + theme(legend.position = "none") +
coord_cartesian(ylim=c(-7,5)) + geom_point(size=I(6)) +
theme(strip.background = element_blank(), strip.text.x = element_blank())
~~~
@@ -288,7 +288,7 @@ This version also confirms Han Zheng's value.
### Neat Array
FeepingCreature notes that this is slower than it needs to be, and can be converted from the hashmap memoization to a faster flat [array](!W "Array (data structure)"), especially if, like Zheng's spreadsheet, one stops tracking winnings and only tracks `(good,bad)` so the value function is reporting the marginal value of the state.
-FeepingCreature's faster, winnings-free, array-based version with a Monte Carlo simulation to double-check results:
+FeepingCreature's faster, winnings-free, array-based version with a Monte Carlo simulation to double-check results (the simulation uses a modulo shuffle, which has a small bias when the range of `rand()` is not divisible by the number of choices; the DP value is unaffected):
~~~{.D}
module fourteen;
@@ -382,24 +382,21 @@ So even a close-to-the-metal implementation will struggle if you ask for the val
But like in the [Kelly Coin-Flip problem](/coin-flip#cc), we can note that most 𝑆 will *not* be requested ever again (at least, if the user isn't requesting a bunch of values eg. at a REPL), because the game has a continually-shrinking (as cards get used up) 'tree' structure, and that evaluation follows a sort of 'wave' or 'ripple' back from the root final states like `(0,0)` or `(10,0)` to the initial `(26,26)`.
Since the evaluation won't revisit them, they can be discarded immediately if we start at the root final states, then evaluate the set of states 'before' them (now that we know the 'next' state), throw out the roots, and move back 1 level to evaluate the state of states before *those*, and so on and so forth.
-This **bottom-up** evaluation will still be 𝒪(_l_^2^) time (the constant factor can be optimized by [further changing the evaluation pattern](#c-diagonal-bottom-up)), but only 𝒪(_l_) linear space.
+With just the current and previous rows, this **bottom-up** evaluation will still be 𝒪(_l_^2^) time (the constant factor can be optimized by [further changing the evaluation pattern](#c-diagonal-bottom-up)), but only 𝒪(_l_) linear space.
So, if one was patient, one could evaluate up to millions of cards, probably, in a reasonable time like a few days.
-I have evaluated up to _l_ = 22,974, available as [a text file](/doc/statistics/decision/2022-10-03-feepingcreature-problem14-bottomup-values0to22974.txt).
+I have evaluated up to _l_ = 22,974 pairs, available as [a text file](/doc/statistics/decision/2022-10-03-feepingcreature-problem14-bottomup-values0to22974.txt).
## Haskell
-[nshepperd](https://x.com/nshepperd1) implementation in [Haskell](!W "Haskell (programming language)") using [`Data.Vector`](https://hackage.haskell.org/package/vector):
+[nshepperd](https://x.com/nshepperd1) implementation in [Haskell](!W "Haskell (programming language)") uses [`Data.Vector`](https://hackage.haskell.org/package/vector). This lazy table stores the full rectangle of states, taking quadratic space on a balanced deck. The C port below keeps just two rows. Here the table dimensions follow the input counts:
~~~{.Haskell}
-import Data.Decimal
-import Data.Ratio
-import Data.Vector
import qualified Data.Vector as V
solve :: (Fractional a, Ord a) => Int -> Int -> a
-solve r b = go r b
+solve reds blacks = look reds blacks
where
- tab = V.generate 27 (\r -> V.generate 27 (\b -> go r b))
+ tab = V.generate (reds + 1) (\r -> V.generate (blacks + 1) (go r))
look r b = tab V.! r V.! b
@@ -417,7 +414,7 @@ solve r b = go r b
## C
-FeepingCreature port of [nshepperd's Haskell version](#haskell) (compiled with [GCC](!W "GNU Compiler Collection"): `gcc -Wall -Ofast -march=native -o problem14 -lm problem14.c`):
+FeepingCreature's C port of [nshepperd's Haskell version](#haskell), revised to print each balanced value from one sweep. Computing the whole series through _l_ pairs takes 𝒪(_l_^2^) time and 𝒪(_l_) space. Re-running the square DP separately for each output took 𝒪(_l_^3^) time. Compile with [GCC](!W "GNU Compiler Collection") using `gcc -Wall -Ofast -march=native -o problem14 problem14.c -lm`:
~~~{.C}
#include
@@ -426,21 +423,23 @@ FeepingCreature port of [nshepperd's Haskell version](#haskell) (compiled with [
#define AT(r, b) tab[((r)%2) * (blacks + 1) + (b)]
-float calc(int reds, int blacks, int r, int b, float *tab) {
+float calc(int blacks, int r, int b, const float *tab) {
return !r ? 0 : !b ? r : fmax(0,
r*1.0/(r+b) * (AT(r-1, b) + 1) +
b*1.0/(r+b) * (AT(r, b-1) - 1));
}
-int main() {
- for (int i = 0; i <= 100000; i++) {
- int reds = i, blacks = i;
- float *tab = malloc(sizeof(float)*2*(blacks+1));
- for (int r = 0; r <= reds; r++) for (int b = 0; b <= blacks; b++)
- AT(r, b) = calc(reds, blacks, r, b, tab);
- printf("%f\n", AT(reds, blacks));
+int main(void) {
+ const int blacks = 100000; // maximum number of pairs
+ float *tab = malloc(2 * (blacks + 1) * sizeof *tab);
+ if (tab == NULL) return EXIT_FAILURE;
+ for (int r = 0; r <= blacks; r++) {
+ for (int b = 0; b <= blacks; b++)
+ AT(r, b) = calc(blacks, r, b, tab);
+ printf("%f\n", AT(r, r));
}
- return 0;
+ free(tab);
+ return EXIT_SUCCESS;
}
/*
0.000000
@@ -476,7 +475,7 @@ int main() {
-And FeepingCreature's [code-golfed](!W "Code golf") version using [lambdas](!W "Anonymous function") to show off:
+And FeepingCreature's [Neat](#neat) [code-golfed](!W "Code golf") version using [lambdas](!W "Anonymous function") to show off:
~~~{.Cpp .collapse}
module fourteen2;
@@ -501,7 +500,7 @@ void main() {
## C Array
-[C](!W "C (programming language)") array version by Khoth (note: not 𝒪(_l_) space because the optimization was not implemented):
+[C](!W "C (programming language)") array version by Khoth (the full array uses quadratic space). This listing and the block listings count black as +1 and red as −1. Exchanging the color names preserves the balanced starting value; interpreting a stopping decision in the original game requires exchanging them back:
~~~{.C .collapse}
#include
@@ -667,7 +666,7 @@ The initial version ran substantially faster when compiled with [Clang](!W) (`cl
This second version should vectorize on both Clang & GCC (4.6s vs 5.8s), and can calculate into the millions without a problem.
Probably it would be even faster on a CPU with [AVX-512](!W), as it could vectorize more.
-The difference in performance between the simplest easiest R version, which took a bad programmer (myself) minutes to write the first version but takes seconds to evaluate & tops out at 143, and this optimized C implementation, which took multiple versions & hours to write by good programmers (FeepingCreature with advice from Khoth & nshepperd), but runs in milliseconds & tops out at somewhere between 'millions' and 'however long you care to wait', illustrates how much potential for optimization there can be---[your computer may be faster than you think](/note/faster "‘Computer Optimization: Your Computer Is Faster Than You Think’, Gwern 2021").
+The difference in performance between the simplest easiest R version, which took a bad programmer (myself) minutes to write the first version but takes seconds to evaluate & tops out at 143 pairs, and this optimized C implementation, which took multiple versions & hours to write by good programmers (FeepingCreature with advice from Khoth & nshepperd), but runs in milliseconds & tops out at somewhere between 'millions' and 'however long you care to wait', illustrates how much potential for optimization there can be---[your computer may be faster than you think](/note/faster "‘Computer Optimization: Your Computer Is Faster Than You Think’, Gwern 2021").
## Parallel
@@ -677,7 +676,7 @@ For card counts like 52, I don't think any parallelism above the CPU-core level
### Diagonalization
-A [spinlock](!W) is one way to [lock](!W "Lock (computer science)") for synchronization, and for large card counts like _l_ = 100,000, there may be enough work when split up to keep CPU cores busy: a spinlock for one thread, when it hits a value it needs but which hasn't been computed yet, will check constantly, and as soon as the other thread finishes computing the necessary value, will grab it and resume its own computation with as little delay as possible.
+A [spinlock](!W) is one way to [lock](!W "Lock (computer science)") for synchronization, and for large card counts like _l_ = 100,000 pairs, there may be enough work when split up to keep CPU cores busy: a spinlock for one thread, when it hits a value it needs but which hasn't been computed yet, will check constantly, and as soon as the other thread finishes computing the necessary value, will grab it and resume its own computation with as little delay as possible.
FeepingCreature provides a parallelized version of the diagonal code, which tries to split the pending diagonal of 100,000 into separate parts (like 4 parts for the 4 cores of his laptop), evaluate them separately on a thread for each core, and spin until all 4 finish, at which point it moves up to the next 100,001 and starts again. This reduces to the same approach as before when only 1 thread is used.
~~~{.C .collapse}
@@ -703,14 +702,14 @@ FeepingCreature provides a parallelized version of the diagonal code, which trie
FP calc(int cards, int r, int b, int dia, bool ascent, FP *prevDia);
void calc_thread(
int cards, int row_base, int col_base, int col_from, int col_to, bool ascent, FP *prevDia, FP *curDia);
-void bool_wait_spin(volatile bool *marker, bool value);
-void bool_set_spin(volatile bool *marker, bool value);
+void bool_wait_spin(atomic_bool *marker, bool value);
+void bool_set_spin(atomic_bool *marker, bool value);
struct ThreadConfig {
int cards;
int thread;
int num_threads;
- volatile bool active;
+ atomic_bool active;
FP *dia1, *dia2;
};
@@ -823,16 +822,16 @@ FP calc(int cards, int r, int b, int dia, bool ascent, FP *prevDia) {
}
}
-void bool_wait_spin(volatile bool *sem, bool value) {
+void bool_wait_spin(atomic_bool *sem, bool value) {
while (atomic_load(sem) != value) _mm_pause();
}
-void bool_set_spin(volatile bool *sem, bool value) {
+void bool_set_spin(atomic_bool *sem, bool value) {
atomic_store(sem, value);
}
~~~
-Efficiency-wise, on my 16-core [AMD](https://en.wikipedia.org/wiki/AMD) [Ryzen Threadripper 1950X](https://en.wikipedia.org/wiki/Ryzen#Ryzen_1000) CPU, the optimal thread count appears to be ~12, and I get a GCC^[It doesn't compile as-is with Clang, for some reason. Replacing the `volatile bool` declarations with ` _Atomic(bool)` compiles, but is ~0.1s slower for both GCC & Clang (2.9s → 3s).] speedup of 6.1s → 2.9s to calculate the 100k value of \$165.075847.
+Efficiency-wise, on my 16-core [AMD](https://en.wikipedia.org/wiki/AMD) [Ryzen Threadripper 1950X](https://en.wikipedia.org/wiki/Ryzen#Ryzen_1000) CPU, the optimal thread count appears to be ~12, and I get a GCC^[The timed version used `volatile bool` with `atomic_load` and `atomic_store`. C11 requires a pointer to an atomic object here. The listing uses `atomic_bool`; the original measurements put this variant at ~3.0s versus 2.9s.] speedup of 6.1s → 2.9s to calculate the 100k value of \$165.075847.
### Blocks
@@ -841,7 +840,7 @@ Efficiency-wise, on my 16-core [AMD](https://en.wikipedia.org/wiki/AMD) [Ryzen T
One could expose enough parallelism to make it profitable by breaking up the problem into large *blocks*, which can be evaluated independently, such as 10,000×10,000 blocks (also improves locality), and assigns each block to a different CPU core.
Nested within each block, the core evaluates diagonally as before.
The optimal size of the blocks will depend on how many blocks there are available at each phase: the bigger the card count, the more blocks will become available after the initial setup: too big and there will only be a few 'intermediate' blocks that size, moderately too small and it doesn't help, and too small (like size = 10) and the overhead becomes so severe it may take minutes to finish instead of <1s.
-On my Threadripper, for _l_ = 100,000 cards some manual tweaking suggested a block size = 400.
+On my Threadripper, for _l_ = 100,000 pairs some manual tweaking suggested a block size = 400.
Khoth's bottom-up+diagonalized+blocks version in C (`clang -Wall -Ofast -march=native -pthread -o Khoth -lm Khoth.c`):
@@ -857,6 +856,9 @@ Khoth's bottom-up+diagonalized+blocks version in C (`clang -Wall -Ofast -march=n
#define BLOCK_SIZE 400
#define NUM_THREADS 15
+_Static_assert(BLOCK_SIZE > 0 && NUM_CARDS % BLOCK_SIZE == 0,
+ "BLOCK_SIZE must be positive and divide NUM_CARDS");
+
#define DIV_ROUND_UP(x, y) (((x) + (y) - 1) / (y))
#define NUM_BLOCKS DIV_ROUND_UP(NUM_CARDS, BLOCK_SIZE)
@@ -935,7 +937,7 @@ int cash(int rem_black, int rem_red) {
}
void do_block(int thread, int block_r, int block_b) {
- count = BLOCK_SIZE;
+ int count = BLOCK_SIZE;
int base_b = 1 + BLOCK_SIZE*block_b;
int base_r = 1 + BLOCK_SIZE*block_r;
int cur = 0;
@@ -1032,12 +1034,18 @@ This skipping of most of the bottom triangle cuts off almost half the state spac
#include
#include
#include
+#include
// NUM_CARDS must be a multiple of BLOCK_SIZE because I'm lazy
+#ifndef NUM_CARDS
#define NUM_CARDS 133787000
+#endif
#define BLOCK_SIZE 1000
#define NUM_THREADS 15
+_Static_assert(BLOCK_SIZE > 0 && NUM_CARDS % BLOCK_SIZE == 0,
+ "BLOCK_SIZE must be positive and divide NUM_CARDS");
+
#define DIV_ROUND_UP(x, y) (((x) + (y) - 1) / (y))
#define NUM_BLOCKS DIV_ROUND_UP(NUM_CARDS, BLOCK_SIZE)
@@ -1073,7 +1081,7 @@ FP diag_arr[NUM_THREADS][2][BLOCK_SIZE+1];
int b_progress[NUM_BLOCKS];
int r_progress[NUM_BLOCKS];
-int skipped[NUM_BLOCKS];
+atomic_int skipped[NUM_BLOCKS];
work_item_t get_work(void)
{
@@ -1108,9 +1116,9 @@ void handle_work_done(work_item_t work)
if (work.b + 1 < NUM_BLOCKS && work.r + 1 < NUM_BLOCKS && cash((work.b+1)*BLOCK_SIZE, (work.r+1)*BLOCK_SIZE) == r0_edge[(work.b+1)*BLOCK_SIZE]) {
r_progress[work.b] = NUM_BLOCKS;
- skipped[work.b + 1] = work.r+1;
+ atomic_store(&skipped[work.b + 1], work.r+1);
}
- else if (work.r + 1 < NUM_BLOCKS && (b_progress[work.r + 1] >= work.b || skipped[work.b])) {
+ else if (work.r + 1 < NUM_BLOCKS && (b_progress[work.r + 1] >= work.b || atomic_load(&skipped[work.b]))) {
put_work((work_item_t){.b = work.b, .r = work.r + 1});
}
@@ -1127,7 +1135,8 @@ void do_block(int thread, int block_r, int block_b) {
int count = BLOCK_SIZE;
int base_b = 1 + BLOCK_SIZE*block_b;
int base_r = 1 + BLOCK_SIZE*block_r;
- if (skipped[block_b] && skipped[block_b] <= block_r) {
+ int first_skipped = atomic_load(&skipped[block_b]);
+ if (first_skipped && first_skipped <= block_r) {
for (int i = 0; i < BLOCK_SIZE; i++) {
b0_edge[base_r + i] = cash(base_b - 1, base_r + i);
}
@@ -1216,10 +1225,10 @@ For _l_ = 100k, this runs in ~0.5s, not quite halving the runtime.
[^PGO]: As a last optimization trick, can sometimes squeeze out another few % of performance (like it did with "Kelly Coin Flip"), but in this case, Clang PGO actually makes it slower by ~0.03s:
~~~{.Bash}
- clang -Ofast -march=native -pthread -o khoth -lm khoth.c -fprofile-generate
+ clang -Ofast -march=native -pthread -o khoth -lm khoth.c -DNUM_CARDS=100000 -fprofile-generate
./khoth > /dev/null
llvm-profdata merge default_*.profraw --output profiling.prof
- clang -Ofast -march=native -pthread -o khoth -lm khoth.c -fprofile-use=profiling.prof
+ clang -Ofast -march=native -pthread -o khoth -lm khoth.c -DNUM_CARDS=100000 -fprofile-use=profiling.prof
time ./khoth
# value=165.076
#
@@ -1231,12 +1240,12 @@ For _l_ = 100k, this runs in ~0.5s, not quite halving the runtime.
While one would think PGO would never hurt, we apparently are so close to the machine & optimal performance by parallelism that PGO isn't smart enough to help given the complexity.
For kicks, I thought I'd calculate the largest _l_ possible.
-This turns out to be _l_ = 133,787,000; higher values require static arrays so large that the [linker](!W "Linker (computing)") balks---presumably there's a way around that but 133m seems big enough.
-I messed with the block size some more on _l_ = 2m (\$818.1, ~2m10s), and found that a block size closer to 1,000 seems better than 400, so for a 133m run, I bumped it to 1,000 to be safe, since as the card count gets bigger, the optimal block size presumably also slowly gets bigger.
+The largest run I completed used _l_ = 133,787,000 pairs. I hit a [linker](!W "Linker (computing)") limit with the static arrays on this setup. On x86-64, a larger code model can address larger arrays.
+I tried block sizes at _l_ = 2 million pairs (~2m10s in my notes) and found that a block size closer to 1,000 worked better than 400. The optimal expected payoff at that size rounds to \$738.27. For the 133-million-pair run, I used 1,000.
-After 9 days on my Threadripper (8--17 October 2022) & 51 CPU-core-days (184,331 CPU-core-minutes), the exact value of _l_ = 133,787,000 turns out to be \$6,038.22.
-Comparing this to [my original square root approximation](#approximating) of `-0.0186936 + 0.522088* sqrt(133787000)` → \$6,038.78162, the approximation has an error of 0.009%.
-If we include that into the square-root approximation, the finetuned approximation then yields `-0.0146229 + 0.522048 * sqrt(133787000)` → \$6,038.32303, which has a better error of 0.0017%.
+After 9 days on my Threadripper (8--17 October 2022), the floating-point result for _l_ = 133,787,000 pairs was \$6,038.22 to the nearest cent. My notes give both 51 CPU-core-days and 184,331 CPU-core-minutes. Those disagree: the latter is about 128 CPU-core-days.
+Before including the record, the [square-root fit](#approximating) on the positive pair counts predicts \$6,038.78665, about 57¢ high (0.0094%).
+Adding the rounded record value to the fit gives \$6,038.32346, about 10¢ high (0.0017% in-sample).
# Faster?
@@ -1247,116 +1256,96 @@ A few possibilities:
- [caching]{.smallcaps}: begin storing pre-computed values in the algorithm, such as every power of 10.
- After all, now that values like _l_ = 133m have been calculated, why should they ever be calculated again? They provide a shortcut to all intermediate values, and a speedup for larger values.
+ A saved root price answers repeat queries for that exact deck size. To resume the Bellman calculation on larger decks, save the needed boundary rows or block edges; a single root price does not determine its neighboring values.
- [GPUs]{.smallcaps}: small local arithmetic calculations done in parallel with minimal control-flow or long-range dependencies scream for a GPU implementation (might require low-level CUDA programming to ensure that the calculations stay in the GPU thread they should)
- [cluster parallelization]{.smallcaps}: for larger problems, network overhead/latency becomes less of an issue and parallelizing across multiple computers becomes useful
- **approximation**:
- [ε probability]{.smallcaps} truncation: as the card count increases, more of the state-space is devoted to increasingly astronomically-unlikely scenarios, which contribute ever tinier values to the final value of the game, because there are no massive payoffs or penalties lurking, only the same old ±\$1.
- Thus, one could truncating value estimates at some small fixed value ε to avoid full rollouts. I suspect that such an approximation would turn it into 𝒪(1) space + 𝒪(_l_) time, because one is now just calculating a wide diagonal 'beam' of fixed-width down through the square of all possible states
+ A fixed-width beam around zero loses most of the deck's probability by the halfway draw: the score's variance there is _l_^2^/(2_l_ − 1). With zero payoff on exit from |score| ≤ _w_, even the largest possible payout is _w_, while the fair price grows like √_l_. A truncation with a guaranteed fixed dollar error therefore needs a growing width or an estimate of the value outside the beam.
- [ε value]{.smallcaps} truncation (perhaps sub-machine precision---the exact calculation is not exact here once something falls below [double-precision floating-point format's](!W "Double-precision floating-point format") ability to represent a number, so compute spent on that is wasted)
It is hard to know if the value < ε *before* you spend the compute, of course, so one needs to figure out a way to bound it or have a good heuristic to guess it.
# Approximating
+The input counts red–black *pairs*: 26 pairs means 52 cards.
+The published table gives floating-point DP values for 0–22,974 pairs; I add the separately reported value at 100,000 pairs, \$165.076 rounded to three decimals.
+I retain the original inputs so the fits are reproducible. The last two entries, 79.111328 and 79.11, give the table's only decrease; directed calculations give 79.114807 and 79.116529 to six decimals, so the final value rounds to \$79.12. Replaying the float recurrence on GCC 14.2 with `-O2 -march=native -ffp-contract=fast` reproduces all 22,974 preceding rows byte for byte and prints 79.113052 on the final row. The published 79.11 is a prefix of that result. Across the file, 3,029 prices round to the wrong cent (nearest cent, half up); the first is at 973 pairs.
+For a fair comparison, fit all three models to the same 22,975 positive sizes. The logarithm is undefined at zero.
+
~~~{.R .collapse}
-values <- read.table("https://gwern.net/doc/statistics/decision/2022-10-03-feepingcreature-problem14-bottomup-values0to22974.txt")
-df <- rbind(data.frame(Cards=seq(0,22974), Value=values$V1, Type="exact"),
- data.frame(Cards=c(100000),Value=165.076, Type="exact"))
-df <- df[-1,] # delete 0 card entry to make things easier with the logs
-
-llog <- lm(Value ~ log(Cards), data=df); summary(llog)
-# ...Residuals:
-# Min 1Q Median 3Q Max
-# −6.62279 −4.98638 −1.00526 3.96333 107.14550
-#
-# Coefficients:
-# Estimate Std. Error t value Pr(>|t|)
-# (Intercept) −106.6454973 0.3724555 −286.331 < 2.22e-16
-# log(Cards) 17.6267169 0.0409405 430.545 < 2.22e-16
-#
-# Residual standard error: 6.19828 on 22973 degrees of freedom
-# Multiple R-squared: 0.889734, Adjusted R-squared: 0.889729
-# F-statistic: 185369 on 1 and 22973 DF, p-value: < 2.22e-16
-
-lsqrt <- lm(Value ~ sqrt(Cards), data=df); summary(lsqrt)
-# ...Residuals:
-# Min 1Q Median 3Q Max
-# −0.05298383 −0.00071444 0.00047093 0.00121099 0.01869362
-#
-# Coefficients:
-# Estimate Std. Error t value Pr(>|t|)
-# (Intercept) −1.86936e-02 3.70052e-05 −505.163 < 2.22e-16
-# sqrt(Cards) 5.22088e-01 3.45212e-07 1512369.327 < 2.22e-16
-#
-# Residual standard error: 0.00187101 on 22974 degrees of freedom
-# Multiple R-squared: 1, Adjusted R-squared: 1
-# F-statistic: 2.28726e+12 on 1 and 22974 DF, p-value: < 2.22e-16
-#
-## The fit:
-##
-## v = −0.0186936 + 0.522088 * √(cards)
-##
-## so 100k = 165.080028 (not quite 165.076), 1m = 522.0, 10m = 1650.96,
-## 100m = 5220.86, 1b = 16509.85, 10b = 52208.78, 100b = 165098.70 etc
-
-llogsqrt <- lm(Value ~ log(Cards) + sqrt(Cards), data=df); summary(llogsqrt)
-# ...Residuals:
-# Min 1Q Median 3Q Max
-# −80.34388 −1.34909 −0.15215 1.34937 26.80501
-#
-# Coefficients:
-# Estimate Std. Error t value Pr(>|t|)
-# (Intercept) −2.66931e+01 1.72306e-01 −154.917 < 2.22e-16
-# log(Cards) 4.40946e+00 2.66876e-02 165.225 < 2.22e-16
-# sqrt(Cards) 3.91493e-01 7.45612e-04 525.063 < 2.22e-16
-#
-# Residual standard error: 2.68411 on 91897 degrees of freedom
-# Multiple R-squared: 0.978735, Adjusted R-squared: 0.978735
-# F-statistic: 2.11482e+06 on 2 and 91897 DF, p-value: < 2.22e-16
-
-df <- rbind(df,
- data.frame(Cards=df$Cards, Value=predict(llog), Type="log"),
- data.frame(Cards=df$Cards, Value=predict(lsqrt), Type="√"),
- data.frame(Cards=df$Cards, Value=predict(llogsqrt), Type="log+√")
-)
-
-p <- qplot(x=Cards, y=Value, color=Type, data=df) + theme_bw(base_size = 50)
-p + geom_line(aes(x=Cards, y=Value), linetype = "dashed", size = 5) +
- scale_color_manual(values=c("#999999", "#5b6b6b", "#313131", "#000000")) +
- xlab("Card Draw (#)") + ylab("Winnings ($)") + theme(legend.position = "none") +
- ggtitle(" √ vs Log approximation of Problem 14 value") +
- geom_point(size=8) + theme(strip.background = element_blank(), strip.text.x = element_blank())
+values <- scan("https://gwern.net/doc/statistics/decision/2022-10-03-feepingcreature-problem14-bottomup-values0to22974.txt", quiet=TRUE)
+stopifnot(length(values) == 22975L, values[1] == 0)
+observed <- data.frame(Pairs=c(1:22974, 100000), Value=c(values[-1], 165.076))
+llog <- lm(Value ~ log(Pairs), data=observed)
+lsqrt <- lm(Value ~ sqrt(Pairs), data=observed)
+llogsqrt <- lm(Value ~ log(Pairs) + sqrt(Pairs), data=observed)
+
+fits <- list(log=llog, sqrt=lsqrt, "log+sqrt"=llogsqrt)
+print(lapply(fits, function(f) c(coef(f), residual.df=df.residual(f), residual.se=sigma(f))), digits=12)
+
+# Build a separate data frame for the plot.
+plot_data <- rbind(transform(observed, Type="DP"),
+ transform(observed, Value=fitted(llog), Type="log"),
+ transform(observed, Value=fitted(lsqrt), Type="sqrt"),
+ transform(observed, Value=fitted(llogsqrt), Type="log+sqrt"))
+
+library(ggplot2)
+ggplot(plot_data, aes(x=Pairs, y=Value, colour=Type)) +
+ geom_line(linetype="dashed") + geom_point() + theme_bw() +
+ scale_color_manual(values=c("DP"="#000000", "log"="#999999",
+ "sqrt"="#5b6b6b", "log+sqrt"="#313131")) +
+ xlab("Red-black pairs") + ylab("Expected winnings ($)")
~~~
-The square-root fits well enough that adding additional terms seems unnecessary, while the residual values indicate that the log fit has some serious issues somewhere.
-Plotting reveals that the log is wildly inaccurate early on, hitting negative values; ignoring that, it grows too slowly compared to the true value, while the square root fits perfectly:
+| Predictors | Intercept | $\log n$ coefficient | $\sqrt n$ coefficient | Residual df | Residual standard error, dollars |
+|:-----------|----------:|--------------------:|---------------------:|------------:|--------------------------------:|
+| $\log n$ | −106.64549734 | 17.62671686 | | 22,973 | 6.19827646 |
+| $\sqrt n$ | −0.01870094 | | 0.52208844 | 22,973 | 0.00186698 |
+| $\log n$, $\sqrt n$ | −0.05411623 | 0.00555158 | 0.52194214 | 22,972 | 0.00030495 |
-{.width-full}
+The log fit predicts negative winnings for small decks and grows too slowly for large ones.
+On the scale of the graph the square-root fit almost covers the DP points. Adding a logarithm reduces the in-sample residual standard error about sixfold, but its extrapolation to the record deck misses by \$1.06, against \$0.57 for the square root alone.
-The square-root fit looks suspiciously like it is just the initial expected value of 1 card (0.5) along with a tiny near-zero misfit term that vanishes as the card value asymptotically increases; I wonder if the limit is just 0.5 × √_l_?
+{.width-full}
-The largest available exact value, _l_ = 133m, changes the approximation consistent with that:
+Using independently bounded prices for the same training sizes gives a square-root prediction of \$6,039.10546. The original input errors happened to bring the record prediction about 32¢ closer.
+
+What does the fit predict at 133,787,000 pairs, before seeing the record result? Keep the predictions separate from the observations when refitting:
~~~{.R}
-## compare with the final available exact value of 𝑙 = 133,787,000
-df <- rbind(df, data.frame(Cards=c(133787000),Value=6038.22, Type="exact"))
-lsqrt <- lm(Value ~ sqrt(Cards), data=df); summary(lsqrt)
-# Residuals:
-# Min 1Q Median 3Q Max
-# −0.10346355 0.00010533 0.00071383 0.00105519 0.00453808
-#
-# Coefficients:
-# Estimate Std. Error t value Pr(>|t|)
-# (Intercept) −1.46229e-02 2.54948e-05 −573.563 < 2.22e-16
-# sqrt(Cards) 5.22048e-01 1.93756e-07 2694354.736 < 2.22e-16
-#
-# Residual standard error: 0.00245711 on 22974 degrees of freedom
-# Multiple R-squared: 1, Adjusted R-squared: 1
-# F-statistic: 7.25955e+12 on 1 and 22974 DF, p-value: < 2.22e-16
+record <- data.frame(Pairs=133787000, Value=6038.22)
+refit <- lm(Value ~ sqrt(Pairs), data=rbind(observed, record))
+p <- c(sqrt=predict(lsqrt, record)[[1]],
+ log_sqrt=predict(llogsqrt, record)[[1]],
+ sqrt_refit=predict(refit, record)[[1]])
+print(round(cbind(dollars=p, percent_error=100 * (p - record$Value) / record$Value), 6), digits=12)
+# dollars percent_error
+# sqrt 6038.786647 0.009384
+# log_sqrt 6037.162951 -0.017506
+# sqrt_refit 6038.323464 0.001713
~~~
-It adjusts the coefficients a bit, and then the relative error drops; the 0.5 multiplier gets slightly smaller, but the offset/intercept gets slightly bigger.
-So it looks like it *does* converge to 0.5 × √_l_ with, for small numbers, an intercept as a constant to help soak up the zig-zag staircase discretization one often sees in probability problems.
+The refit changes the square-root slope from 0.52208844 to 0.52204804 and the intercept from −0.01870094 to −0.01462286.
+Its 0.0017% error is in-sample: the record value of \$6,038.22 helped determine the coefficients.
+The earlier figures of \$6,038.78162 and \$6,038.32303 used the printed, rounded coefficients; the first printed fit also included the zero-pair row.
+
+I originally guessed the coefficient might approach 0.5, the fair price of a single *pair*.
+The limiting coefficient is $(1-\alpha^2)\sqrt{\pi}=0.522037675987\ldots$ per square root of a pair count, or $0.369136380725\ldots$ per square root of the total card count. Here $\alpha=0.839923675692\ldots$ is the Brownian bridge stopping constant.
+The square-root fit found the right growth law; its fitted intercept depends on the range of deck sizes. [Shepp 1969, §6](https://faculty.wharton.upenn.edu/wp-content/uploads/2012/04/Explicit-solutions-to-some-problems-of-optimal-stopping.pdf#page=8 "Explicit Solutions to Some Problems of Optimal Stopping")
+
+# Later results: the price & a rule for 52 cards {#later-results}
+
+On the standard deck the fair price is exactly 41,984,711,742,427/15,997,372,030,584 dollars.
+The optimal _decision_ also has a short answer.
+Let $x$ be the current profit in dollars and $t$ the number of cards left.
+**Cash out when $x>0$ and $(x+2)^2\ge t+8$; otherwise draw if cards remain.**
+At a profit of \$3, for example, cash with 17 cards left and draw with 19.
+It draws with one red and two blacks left. Taking the dollar immediately is equally good there. This rule is optimal at every feasible state of the 52-card game. It first makes a strictly worse decision on a balanced deck of 64 cards.
+
+At large sizes write $n$ for red--black pairs and $N=2n$ for total cards.
+Then $V_n/\sqrt n\to(1-\alpha^2)\sqrt\pi=0.522037675987\ldots$, or $V_n/\sqrt N\to0.369136380725\ldots$.
+Here $\alpha=0.839923675692\ldots$ is the positive solution of $(1-\alpha^2)\int_0^\infty e^{\alpha u-u^2/2}\,du=\alpha$.
+Shepp obtained the corresponding Brownian value and described the discrete limiting step as formal; Boyce investigated the finite urn and its stopping boundary. [Shepp 1969](https://faculty.wharton.upenn.edu/wp-content/uploads/2012/04/Explicit-solutions-to-some-problems-of-optimal-stopping.pdf#page=8 "Explicit Solutions to Some Problems of Optimal Stopping") · [Boyce 1973](https://sites.math.rutgers.edu/~zeilberg/EM13/boyce1973.pdf "On a simple optimal stopping problem")
````
#### What the mathematical sources support
The finite urn and its Brownian bridge limit were already studied by Shepp, and Boyce gave an exact algorithm, bounds for perturbed urns and a stopping-boundary table through 200 balls.
For the discrete boundary, Lai, Yao and AïtSahlia distinguished the parity-constrained optimal cutoff from its real-valued interpolation. Their §4 gives numerical evidence for the $-1/2$ correction and explicitly identifies the singular derivative of the limiting boundary at zero as an obstacle to proof.
Elton proved a finer Catalan-triangle correction and a density-one exact decision rule in the related infinite-horizon game with independent tosses and reward equal to the running proportion of heads. The finite deck has a different payoff and conditional transition law. [Shepp 1969, §6](https://faculty.wharton.upenn.edu/wp-content/uploads/2012/04/Explicit-solutions-to-some-problems-of-optimal-stopping.pdf "Explicit Solutions to Some Problems of Optimal Stopping") · [Boyce 1973](https://doi.org/10.1016/0012-365X(73)90123-4 "On a simple optimal stopping problem") · [Lai, Yao & AïtSahlia 2007, §4](https://doi.org/10.1239/aap/1189518637 "Corrected random walk approximations to free boundary problems in optimal stopping") · [Elton 2025](https://doi.org/10.1017/apr.2025.6 "Exact solution to the Chow–Robbins game for almost all n, by using a Catalan triangle")
Four published variants change the information or available actions. An exact closed form exists when a player may decline an individual wager and keep observing later draws. A Bayesian urn instead hides the initial color count. A solvency-constrained urn adds initial capital and forces stopping at bankruptcy. In another version, the gambler can draw several items simultaneously, and the optimal policy chooses either zero or maximum capacity. Each assumption changes the Bellman equation. [Chen et al. 1998](https://doi.org/10.1137/S0895480195282148 "An Optimal Acceptance Policy for an Urn Scheme") · [Chen et al. 2005](https://doi.org/10.1137/S0895480102418099 "A Random Version of Shepp’s Urn Scheme") · [Chen, Grigorescu & Kang 2015](https://www.math.miami.edu/~igrigore/pp/mpv.pdf "Optimal Stopping for Shepp’s Urn with Risk Aversion") · [Dehghanian & Kharoufeh 2019](https://doi.org/10.1016/j.orl.2019.04.006 "Optimal stopping with a capacity constraint")
A prescribed square-root boundary also has a substantial first-passage literature. For centered i.i.d. random walks satisfying moment conditions, Denisov and coauthors prove that survival above $c\sqrt{t+b}-a$ decays as a constant times $n^{-p(c)/2}$, where $p(c)$ is a parabolic-cylinder root. This supplies a rigorous comparator for the proposed spectral exponent. The proof of the urn deficit in Section 8 supplies the extra comparison with the payoff of an optimally stopped bridge. The older Chow–Robbins computational papers give precedents for bounding a stopping region via finite computations and continuous-time comparison. [Breiman 1967](https://digicoll.lib.berkeley.edu/record/113068 "First exit times from a square root boundary") · [Novikov 1981](https://doi.org/10.1070/SM1981v038n04ABEH001455 "On estimates and the asymptotic behavior of nonexit probabilities of a Wiener process to a moving boundary") · [Denisov et al. 2025](https://arxiv.org/abs/2501.04554 "Random walks with square-root boundaries") · [Häggström & Wästlund 2013](https://doi.org/10.4169/amer.math.monthly.120.10.893 "Rigorous Computer Analysis of the Chow–Robbins Game") · [Christensen & Fischer 2022](https://doi.org/10.1017/jpr.2021.73 "On the S_n/n problem")
The graph obstruction uses unconditional Hilbert irreducibility for ordinary positive integer specializations. For an irreducible $F\in\mathbb Q(t)[Y]$ of $Y$-degree at least two, only $O_F(\sqrt B\log B)$ integers $1\le t\le B$ have a reducible specialization, with finitely many poles and degree drops handled separately.
Consequently its zero locus can contain a rational sequence value at only that many indices. Linear factors give rational functions, whose integral growth exponents are incompatible with $\Theta(\sqrt n)$ at all sufficiently large indices.
An argument for real or complex polynomial coefficients first descends to rational ones by linear algebra on the rational evaluation vectors of its finitely many monomials. Dörge supplies a classical irreducibility proof. Cohen and Zywina supply the direct quantitative statement. Bary-Soroker, Garzoni and Matei restate the unconditional ordinary-integer result in their introduction, before addressing exponential specializations under GRH.
This argument concerns a fixed algebraic relation on the points $(n,v_n)$. Algebraicity and differential finiteness of the generating function require separate arguments. [Dörge 1927](https://link.springer.com/article/10.1007/BF01209160 "Einfacher Beweis des Hilbertschen Irreduzibilitätssatzes") · [Cohen 1981](https://doi.org/10.1112/plms/s3-43.2.227 "The Distribution of Galois Groups and Hilbert’s Irreducibility Theorem") · [Zywina 2010, Theorem 1.2](https://pi.math.cornell.edu/~zywina/papers/Quantitative-HIT.pdf#page=2 "Hilbert’s irreducibility theorem and the larger sieve") · [Bary-Soroker, Garzoni & Matei 2025, eq. 1](https://doi.org/10.1007/s00209-025-03717-7 "On the irreducibility of f(2ⁿ, 3ᵐ, X) and other such polynomials")
**All-deck prophet inequality.** Reflection gives $E H=(4^n/\binom{2n}n-1)/2$. Lean now proves the central-binomial upper bound for every $n$, so
$$ V_n\le (1-\alpha^2)(2E H+1), \qquad \lim_{n\to\infty} V_n/(E H)=2(1-\alpha^2)=0.5890564380\ldots . $$
Thus the optimal online player asymptotically collects 58.91% of what someone who sees the complete shuffle can collect. The additive one matters on small decks. The square-root price enclosure in Section 4 also holds for every $n$. A new finite reflection in Lean and an independent GMP checker fill the old small-deck gap. [All-size enclosure](#proof-all-sizes)
### The exponent of the price correction
Let $K=(1-\alpha^2)\sqrt\pi$ and $\Delta_n=(1-\alpha^2)4^n/\binom{2n}n - V_n$. The following is a two-sided order theorem for the discrete game:
$$
\Delta_n=\Theta(n^{-\mu}),\qquad
\mu=0.2311666867344859191491701\ldots,\qquad D_{2\mu}(-\alpha)=0.
$$
Here $D_p$ is the parabolic cylinder function and $2\mu$ its first positive zero in the **order** at this fixed argument. There are constants $0
### The half-dollar correction and the cost of reaching the endgame
Let $t$ be the cards remaining, $x$ the player's current dollars and $N=2n$ the initial deck size. The integer exercise score has the parity of $t$. The first feasible $x$ with $x+1/2\ge\alpha\sqrt t$ predicts the exact optimal exercise cutoff on a set of layers of natural density **one**. Using $x\ge\alpha\sqrt t$ gets the exact cutoff on a set of density **three quarters**. Each layer gets equal weight here. These are different statistics from the probability that a shuffle encounters a wrong decision.
There is a sharper way to state the displacement. Lai, Yao and Aitsahlia allow one card in the urn to have a deterministic payoff between $-1$ and $1$. This defines a real-valued break-even score $\beta(t)$ between the ordinary lattice scores. For this specific game the written proof below gives **$\beta(t)=\alpha\sqrt t-1/2+O(t^{-1/6})$**. The integer rule can miss on at most $O(X^{5/6})$ of the first $X$ layers. Both implied constants and the onset remain unspecified. The $-1/2$ comes from the discrete local stopping equation. Its limiting continuation premium, in suitable units, is a quadratic cut off at the integer nearest its minimum. Taking one more draw is neutral at offset $-1/2$. A finer term of order $t^{-1/4}$ remains open. [Integer frontier](#proof-new-boundary) · [Fractional urn](#proof-fractional) · [Quantitative remainder](#proof-boundary-rate)
Write $\mu=0.2311666867344859\ldots$, half the first positive $p$ with $D_p(-\alpha)=0$. Under optimal play with cash taken on ties, the probability of leaving with zero is $\Theta(N^{-\mu})$. More generally the probability of surviving through a layer of $T$ remaining cards is bounded above and below by fixed positive multiples of $(T/N)^\mu$, uniformly for all sufficiently large $T\le N$. At 8,388,608 cards, numerical play pays zero on about 1.4061% of deals. At that size $N^\mu\Pr(\text{zero})\simeq0.56046$ and $N^\mu(Q-V)\simeq0.12042$. Converting the latter to pairs gives $n^\mu(Q-V)\simeq0.10259$. These are finite measurements. Existence of limits for the normalized quantities remains open. [Two-horizon survival proof](#proof-survival-window)
For each of the three specified square-root players the **actual loss against optimal play** also has order $\Theta(N^{-\mu})$, as does its zero-payout probability. These players are the original 79-then-unshifted hybrid, the pure half-card rule, and the 79-then-half-card hybrid. The proof uses a fixed small deck where the policy makes a strict error. A positive fraction on the appropriate spectral scale reaches an endgame carrying that error. Improving the policy there changes finite losses by orders of magnitude while preserving their eventual power law. [Proof for actual regret](#proof-real-regret)
## 5. What remains when arithmetic takes nanoseconds?
Integer microdollars are the interface to the large-deck price routine.
A floating-point square-root estimate can cheaply locate a candidate.
An integer residual or adjacent-square comparison repairs it.
In the batched code an estimate outside the proven range invokes the scalar routine.
These designs give the hint permission to be wrong and establish correctness at the last exact comparison.
The fixed-width price code covers 32,768 through $2^{64}-1$ **pairs**.
The per-draw native strategy in §2 instead takes an unsigned 64-bit **remaining card count**.
The Python versions have growing precision.
| Workload | Implementation / control | Result |
|---|---|---|
| Inputs and endpoints already in memory, sustained throughput on one AMD EPYC core | C reproducing the original integer algorithm, hand-written scalar, and eight-lane AVX-512 | Scalar assembly 22.8–25.9 ns/quote across three distributions. Eight lanes 6.5–9.4 ns/quote. Algorithm-matched C was much closer to scalar assembly than the original C. |
| Three formatted answers in a newly launched process, warm pages | Normal C, static launcher using C arithmetic, static launcher using hand-written arithmetic | 550.5, 64.4, 72.8 µs in the same test. Most of the speedup came from changing the launcher. |
| Compact executable versus a program that exits immediately | 1,771-byte general solver versus 127-byte control, single-threaded caller, vfork/exec/wait | 52.542 vs 51.662 µs in this run. The general program has an ELF header and one load segment and fits in one file-backed executable page. |
| General executable versus an oracle that prints exactly the same three answers | 416-byte hardwired writer, two randomized interleaved runs | Median paired saving from hardwiring 0.655 µs, 95% sign interval −0.290 to 1.597 µs. The experiment could resolve a few percent and did not establish equivalence within 1 µs. |
| Resident shell, same three formatted answers | Bash builtin vs literal-output builtin | 2.734 vs 2.231 µs per command, including shell dispatch. A successful tested write delivered all 232 bytes. |
| Device already open, one request, printed output excluded | Linux module vs the same integer C called inside a QEMU/TCG guest | One deck 2.237 vs 0.944 µs. Three decks 4.044 vs 2.832 µs. Guest numbers compare those two guest paths. Native module latency was not measured. |
The compact ELF is built with an assembler and a header writer, with zero relocations left to resolve and no linker in its build.
The loader still has to map the image.
Lean decodes the actual 120 header bytes.
Byte checks connect instruction ranges and constants to the model.
The arithmetic proofs cover the integer root, endpoint rounding, debit, edge inputs and optimized quote path.
The game theorem uses two fixed computations discharged with Lean's native evaluator.
Memory validity, calling convention, modeled instructions, and OS behavior define the proof boundary.
The kernel-module path additionally trusts compiler lowering and the Linux ABI.
In the recorded guest 50,969 actual device comparisons passed, and the freestanding integer core passed 242,201 differential inputs.
A pipe ioctl in an unrelated native control is not a measurement of this module.
The archive includes the original timing distributions, benchmark controls and the arithmetic sources.
Playing the ordinary 52-card game is a different machine task: return a single decision given the state.
Its table-indexed AMD64 routine is **eight bytes**, plus a 27-byte threshold table: `cmp dil,[rdx+rsi]`, `setge al`, `ret`.
The table-free alternative is 21 bytes.
Lean models the signed comparison including overflow and checks the decision on all 729 remaining-count pairs.
An adequately advised player need only test equality with the transmitted target: six bytes, `cmp edi,esi`, `sete al`, `ret`.
Updating counts and passing the target are work performed by the caller.
No timing or code-size minimality over all possible implementations follows.
## 6. What the player should pay for information
The contracts specify *when* the player learns what.
A pre-game announcement of a fixed card, a bit designed after looking at the entire shuffle, a voucher to inspect one upcoming card, and a preview renewed at every draw have different values.
The foresight premium is $P_n-V_n$.
A fraction of the premium uses that denominator whenever it is positive.
At one pair, an ordinary player already earns the full-information value.
An asymptotic dollar coefficient below is labeled by $\sqrt n$ (pairs) or $\sqrt N$ (cards).
### Messages before play
An adviser with $m$ possible messages can select one of $m$ ordinary online policies after seeing the deal.
Equivalently, an online player can nominate $m$ balances and take their maximum, with an unused nomination worth zero.
For one direction run the policies together and mark their stops.
For the converse, policy $j$ waits for the $j$th chronological nomination, including legal tie handling.
This changes an optimization over partitions of all shuffles into a DP over the remaining composition, remaining nominations and highest banked score.
It also clarifies the expense hidden on the dealer's side.
To answer the best question the dealer must know which online policy will do best on that shuffle.
| Pre-game information on 52 cards | Expected winnings (dollars) or increase, as marked |
|---|---:|
| None | 2.624475549 |
| First card's color | Increase 0 |
| Last card's color | Increase 0.11487039 |
| Colors of positions 51 and 52, best two fixed positions | Increase 0.19490077 |
| Whether the peak will reach six, best single peak cutoff | Increase 0.44511 |
| Best binary question, which can be made exactly fair | 3.236409379 (increase 0.611933830) |
| Best 3 distinct messages | 3.524785166 (63.57269% of premium) |
| Best 4 messages (2 bits) | 3.690630982 |
| Best 8 messages (3 bits) | 3.981263639 |
| Best 16 messages (4 bits) | 4.040655522 |
| Full foresight | 4.040664775 |
On 52 cards the colors of any one of the first four positions have zero value in advance.
Their identities become available during draws the ordinary player can already afford to take.
The last color changes what a future suffix is worth.
The optimal bit can be phrased as **“take the first nomination, or wait for the second?”** There are enough tied deals to split the two answers equally without sacrificing a dollar.
A different bit built by ranking peaks into two equiprobable halves also has a growing value: a simple strategy earns at least $0.55713\sqrt n$ to leading order against $0.52204\sqrt n$ unaided.
Entropy alone does not predict economic value.
With $n$ pairs, **exactly $n$ distinct labels** are necessary and sufficient to guarantee the peak on every shuffle.
A target for every positive level suffices, since zero-peak deals can use any target and finish at zero.
The $n$ decks $R^j B^n R^{n-j}$ require incompatible first stops.
With $n-1$ labels exactly one aggregate dollar over all shuffles must be sacrificed, and one simple target menu attains that bound.
More generally, announcing the peak capped at $m$ has exact value $\sum_{j=1}^{\min(m,n)}\binom{2n}{n-j}/\binom{2n}n$.
This is optimal among all $m$-message strategies exactly at and above $m=\lceil n/2\rceil$ for $n\ge7$, with small exceptions at $n=4,6$ described in the detailed proof.
For the standard deck 13 labels make the capped scheme optimal and 26 give the prophet's payout.
Given 16 messages the exact binomial calculation took about 1.7 µs versus 30 ms for unrestricted nominations on the measured host.
**Half the foresight premium.** One unrestricted bit captures less than 35% of the premium in the large-deck limit. In units per $\sqrt N$, an exponential-martingale bound for the bonus from the second nomination, followed by the Brownian bridge stopping inequality, gives the upper price 0.4592. Unaided play tends to 0.36913638 and the prophet to 0.62665707, making the halfway target 0.49789672. A concrete four-message contract reaches at least 0.49977534, or 50.7295% of the premium. Its four early targets are $(0.4,0.7,1.0,1.4)\sqrt n$; in the last quarter replace them by $(0.2,0.5,0.8,1.1)\sqrt n$. Reflection conditions on the score at the switch. The limiting implication for optimized discrete players uses time-grid approximation and transition convergence, including control of the information available at each grid stop. Convergence of the underlying random paths alone would leave that gap.
| Total cards | Optimum fraction with three distinct messages |
|---:|---:|
| 52 | 63.57269% |
| 8,192 | 50.23075% |
| 16,384 | 49.92094% |
| 32,768 | 49.70215% |
At 16,384 cards, three messages earn 63.449682883 dollars against a halfway target of 63.475357565.
Four earn at least 63.973670085 dollars on that deck.
Thus exactly four labels are needed there.
The two-bit asymptotic result is settled in fixed-width bits.
The eventual necessity of *all four labels* remains open.
**Perfect prefix advice.** Charge per transmitted bit and permit different lengths on different shuffles, with a prefix-free code, zero payoff error on every deal, and an arbitrary online decoder. The optimum satisfies $L_n^*=\tfrac12\log_2 n+O(1)$ expected bits, against $\lceil\log_2 n\rceil$ in the worst case. For the lower bound a policy stopping at a record $x$ has conditional chance $(x+1)/(b+1)$ of having selected the final maximum. Applying Kraft's inequality to the successful codewords, then a Catalan rotation bound to how late such a record can be, gives the logarithmic lower coefficient. A simple quotient/remainder description of the peak matches it.
On 52 cards the optimum lies in **[2.91309099, 3.05230128] expected bits**.
The best code that only assigns positive peak targets (with a free reassignment of zero-peak deals) costs 3.116571426 bits.
Change the short three-dollar instruction to also cash one or two dollars if the last red has appeared and the player is at the running record.
The short word can then serve another **31,872,759,742,852** shuffles.
Its decoder uses the cards revealed during play.
This improves even on the optimal Huffman code for the more restrictive target representation.
The exact optimum over decoders remains open.
### The constant cost of prefix advice
Let $L_n^*$ be the minimum expected binary prefix length of advice which realizes the peak on every deal. The sharpened ballot–Kraft converse and an explicit prefix construction give
$$
-1.026321953\ \le\ \liminf (L_n^*-\tfrac12\log_2 n)
\ \le\ \limsup (L_n^*-\tfrac12\log_2 n)\ \le\ 0.945139462.
$$
The entropy of the literal peak has constant $+0.85906813$. A single binary prefix message has integer length. For the literal peak, the resulting excess over entropy stays strictly positive and has an explicit limit along each convergent fractional phase of $\tfrac12\log_2 n$. On a standard deck literal-peak Huffman coding costs 3.270627252 bits; assigning zero-peak deals to an existing target reduces this to 3.116571426. A decoder that also uses the observed play reaches 3.052301273. Whether the online decoder saves a positive constant asymptotically remains open. [Proof and phase formula](#proof-prefix)
### Preview, recall and vouchers
A rolling preview of the next $k$ cards is equivalent path by path to permission to take the largest balance in a trailing window, with the decision shifted by up to $k$ draws.
Any ordinary player can recognize a preview player's stopping decision at most $k$ cards late, losing at most $k$ dollars.
For each fixed $k$, the limiting premium is **exactly $k$ dollars**.
Near an ordinary stopping state on a sufficiently large deck, the preview player can wait for $k$ consecutive blacks and retire just before them at vanishing expected waiting cost.
The appendix states the growing-window condition and proof.
A renewable one-card preview on 52 cards earns **3.076827375** dollars and two cards earn **3.381628365**.
For a growing window with $k\,2^k=o(\sqrt N)$ the premium is asymptotic to $k$; for $k\gg\log N$ the premium divided by $k$ tends to zero.
The crossover on the logarithmic scale remains open.
The compressed rolling recursion remembers the last visits to higher balances, replacing $2^k$ ordered histories with Fibonacci-many states.
For half the prophet premium, renewable preview requires two cards on a 52-card deck, 18 on 800 and 30 on 1,400.
The finite classifications through 700 pairs check each boundary independently.
In the large-deck limit the necessary fraction of cards tends to $d$ with **$1/1280
### What the extended information calculations establish
At 131,072 cards a one-bit message chosen with knowledge of the shuffle captures **33.33406–33.33410%** of the difference between perfect foresight and ordinary optimal play. Three messages capture **49.43815–49.43819%**. Four messages suffice asymptotically. The necessity of a fourth remains open. Extrapolating the last doubling with a leading $N^{-1/2}$ error predicts 33.1556% and 49.1742%, respectively. That extrapolation has no certified remainder.
Let $d_*$ be the limiting fraction of the deck a renewable preview must show to earn half the foresight premium. A block strategy plus directed integer integration gives **$1/1280
## 7. What generalizes, what has been proved, and what remains open
**Formalizing the contract produced algorithms.** Requiring a legal strategy instead of a numerical Bellman value exposed a missing step in the one-cent argument. Agreement between upper and lower *prices* certifies the price. To certify the player, the lower object must be the value of the code actually used after the cutoff. Replacing a maximization by the fixed action in one finite layer closed that gap. In the information game the definition of a stopping time led directly to a much smaller search space via chronological nominations. This is a practical reason to model what an agent can observe before optimizing.
**A precise error budget changes what is worth computing.** An exact fraction, correctly rounded cents, expected loss under one cent, and an action correct on every reachable state are four separate deliverables. Each has a different cheapest known method here. The first wrong quadratic decision is strict but almost worthless from the starting deal. Conversely an asymptotic relative loss of about **4.65767 parts per billion** for the 79-rule gives an unbounded absolute loss of about **$2.43148\times10^{-9}\sqrt n$ dollars**. Matching the true Brownian slope to bounded boundary displacement makes the absolute loss tend to zero. The explicit two-branch player adds a finite guarantee and turns it into usable code.
**A common comparison can save more than a faster instruction.** Centering both players' bounds on the same binomial martingale eliminates a dollar-error term before arithmetic starts. In the price evaluator, proving that a repaired integer endpoint contains the game value permits an approximate instruction or SIMD guess to supply it. In both cases the proof identifies what may be approximate and exactly where to check it.
**The benchmark needs a control that can win.** A hardwired executable gets the right answers for free on the chosen inputs. Identical output, swapped filenames, a pre-opened sink and paired timing isolate how much this is worth to a caller. The answer on the measured machine was consistent with a sub-microsecond saving, with uncertainty of the same order. The 6–9 ns SIMD result answers a throughput question for a resident caller. Neither measures how long it takes a person to play a deck. Recording workload, process state and output obligations matters as much as specifying the instruction set.
**The source of a short answer may be expensive.** A six-byte action can spend information supplied by a dealer who inspected the whole shuffle. A constant-length elementary formula can use more memory than the physical computer can supply. A microsecond quote can use a theorem whose finite calibration was computed previously. The useful accounting states who knows the input, where the work is performed, what is reused, and what output or guarantee is purchased.
**A proof can suggest a different optimization objective.** A half-card displacement originally appears in the local exercise decision. Its effect on regret depends on how often play reaches that decision and what the two actions pay there. A 107-red prefix makes the first error of the 79-rule essentially free. Keeping that rule in its accurate range gains far more than applying the same asymptotic fix everywhere. Likewise, shifting the time index of a discrete heat solution by two leaves its central power unchanged while moving its zero across the exercise obstacle. In one calculation the lattice shift improves the player. In the other it makes a two-sided proof possible.
### Proof and trust ledger
| Claim group | Evidence here | Boundary a reviewer should inspect |
|---|---|---|
| Tree semantics, aggregate DP, 52-card fraction and finite formula | Lean kernel, exact integer reference | Shifted versus unshifted rewards, tie rules and conditioning on completed words |
| Nonalgebraicity and non-P-recursiveness; straight-line formula | Written all-size proofs with Lean sublemmas; tests of packed digits and corrupted tableaux | Hilbert irreducibility and uniform degree/order arguments, all-size packing proof, and exact grammar for the positive formula |
| Large-deck price theorem | Lean/mathlib game-to-bound theorem; independent integer implementations | Native evaluation at the 3,600- and 65,536-card cutoffs trusts Lean's native evaluator; mathematical libraries and the model remain part of the base |
| Machine quote | Arithmetic, decoder, selected linked bytes, header and renderer proofs; independent byte and native comparison tests | Exact modeled paths, preconditions, particular compiled lowering and host ABI |
| New one-cent player | Constructive analytic comparison, two finite integer programs, certified rational coefficient construction, separate Lean lemmas and native cross-check | The fixed-rule cutoff, finite sweep, and irrational-to-rational error allowance are distinct obligations; the local hypotheses of the full-history Lean theorem still require the analytic and finite executable certificates |
| Advice, preview and vouchers | General pathwise/reduction Lean theorems and selected exact finite game values; independent combinatorial and interval checkers | Advice sorting and full-history Bellman semantics use two encodings; probability limits and certain analytic inequalities have written proofs |
| Large-deck one-bit obstruction, prefix-code costs | Optional stopping and grid-limit proofs; exact polynomial, integral, combinatorial and finite-game checks | Check order of maximization and conditioning, the prefix-free contract, the finite-grid approximation, and outward interval endpoints |
| Performance | Archived raw data, independent reruns of functional checks, controlled measurements | Historical wall times, empirical distributions and emulator results are measurements, not universal bounds |
### What the full-history Lean theorems establish
At zero vouchers the full-history tree allows the continuation after each observed prefix to be chosen independently. In `review/formal/FullHistoryPrice.lean`, `markov_suffices` proves that a count-only strategy attains the greatest expected payoff among all those strategies on every balanced deck. Any finite random mixture obeys the same ceiling. `scalar_machine` transfers the modeled scalar machine specification to this optimum; `printed_record` transfers the verifier’s dollar and rounding guarantees. Three concrete stdout records give 603,822, 1,167,312 and 52,203,768 cents.
There are two distinct one-cent Lean results.
| Theorem | Player covered | What the proof assumes |
|---|---|---|
| `IdealPlayer.all_ordinary_strategies` | Below 233,631 initial pairs, optimize exactly. Otherwise use the exact Brownian contact column until 65,536 cards remain, then optimize the endgame exactly. | For every $n$, the theorem has no analytic or certificate hypotheses. It imports checked finite-layer results that use Lean’s native-evaluation axiom. Its policy uses exact real comparisons and finite optimization. |
| `FullHistoryRegret.all_competitors` | Use the 79-rule in the final 65,536 cards and the supplied exercise frontier before then. | The theorem proves loss below $0.009804191707$ dollars against every legal full-history competitor, given the finite root sweep, the policy’s payoff on the cutoff row, a physical advancing frontier containing the start, and contact there. The executable and analytic certificates supply these premises outside Lean for the dyadic implementation. |
The source directory includes the six supplementary Lean modules, their build script and the axiom transcript. Neither theorem identifies the half-card player with either of these policies. Their playing guarantees use the distinct contact calculation and numerical certificates in Section 2.
For the two half-card policies, `HalfCardCap.central_bound` proves the all-later central product estimate from only the first 2,048 factors, without native evaluation. `HalfCardCap.all_sizes` uses the full-history upper theorem and gives the strict bounds **0.7647297 cents** (half-card alone) and **0.7645408 cents** (79 then half). Sharper directed evaluation of the same central product lowers the numerical all-size bounds to **0.76472151 cents** and **0.76453259 cents**. Its hypotheses identify the external work precisely: the bounded finite root sweep and the attained lower envelope for the specified policy.
| Additional result | Strongest established conclusion | Remaining proof boundary |
|---|---|---|
| Spectral correction | The discrete deficit is bounded above and below by positive constant multiples of the critical power. | Written proof. The sharp coefficient, its convergence, and the three-term price expansion remain open. |
| Half-card players | All-deck regret below 0.765 cents for both. All three unique finite maxima are isolated through 8,388,608 cards. | Directed finite sweeps and cutoff plus written contact argument. The central-factor estimate is independently kernel-checked. |
| One-shot perfect advice | Explicit lower and upper constants for the optimal decoder. A phase formula for the excess cost of coding the literal peak. | Written probability and coding proofs. The best online-decoder constant remains open. |
### What a reviewer can check independently
| Claim | Lean result | Native computation trusted by Lean | Additional evidence |
|---|---|---|---|
| 52-card price and optimal decisions | Bellman tree, exact finite price and specialized rule | See the individual proof statements | Separate integer path counts and original dynamic program |
| Square-root enclosure and central-binomial upper price, every balanced deck | `P14Entry.game_bounds_all`, `P14Entry.central_upper_all` | Yes, finite row comparisons | Independent directed GMP replay |
| Loss equals the sum of errors at decisions actually reached | `Problem14.RegretAccounting.deck_regret` | No | Integer recurrence also underlies the independent regret sweep |
| Subcent regret for the two half-card policies | `HalfCardCap.all_sizes` with stated premises | See its finite-policy premises | Written contact estimate, directed cutoff and starting-row certificates |
| Exact peak locations through 8,388,608 cards, and first strict dominance | — | — | Directed fixed-point and heat recurrences, integer threshold checks, exact opening probability |
| Non-P-recursiveness of the exact price sequence | Component algebraic results | — | Written boundary-gap and analytic-operator argument, plus finite modular-rank cross-checks |
| Half-card boundary, survival exponent, actual regret exponent | Supporting game and comparison lemmas | — | Written proofs of the asymptotic conclusions. The fitted amplitudes are numerical. |
| Advice and preview | Several finite or structural components | Depends on theorem | Directed integrals, finite Bellman bounds and written scaling arguments. The 1/30 witness is an integer calculation. |
| Latency of a quote and specialized executable | Semantic and byte-level proofs for the routines identified below | Depends on theorem | Native benchmarks and syscall measurements on the specified systems. Timing is empirical. |
A useful review question is whether a different policy can beat the certified one while every line of its proof remains true. Here that question led to three separate quantities one can measure on the same deck: the gap between the upper bound and the optimum, the loss from the player's decisions, and the gap between the player's payoff and its lower bound. Only the middle quantity measures the value of changing a decision.
| Additional claim | Evidence | Scope |
|---|---|---|
| Half-dollar boundary, optimal zero payouts and actual regret rates | Written discrete comparisons and boundary-layer uniqueness | Density of exact lattice agreement and continuous fractional-urn correction. The next term and limiting amplitudes remain open. |
| Price bounds on every balanced deck | Lean incl. one new native finite check, and independent directed GMP | Both the square-root interval and the central-binomial upper hold from zero pairs. |
| Ties, dominance and finite maxima | Exact aggregate integers and directed integer intervals | Ranges and first strict disagreements are given in Sections 1–2 and the verification worksheets. |
### Open questions worth a reviewer's time
1. For a *single* unchanged 79-rule, what is the first balanced deck on which expected regret exceeds a cent? Its leading coefficient alone cannot locate that crossing. For each of the two hybrids and the single half-card rule, determine the actual all-deck maximum regret or minimize code size over a stated instruction grammar and tolerance. The finite comparison in §2 also locates the exact 220-card maximizer of the single half-card rule on the tested range.
2. Does every sufficiently large balanced deck need four distinct advice messages to reach half of full foresight? Three fail at 16,384, 32,768, 65,536, and 131,072 cards. There is no proved monotonicity in deck size for that comparison. Find the exact one-bit and three-message limiting prices.
3. Determine the optimal prefix code for perfect play on 52 cards and the constant term, if it exists, in $L_n^*-\frac12\log_2 n$. The finite lower bound optimizes how many deals can be served at each depth without requiring the maximizing menus to be jointly nested.
4. Allow the dealer to inspect at most $q$ chosen positions adaptively, then send one bit before play. What is the minimum $q$ beating the 45.235¢ gain from a renewable one-card preview? With one look the best position is last (11.487¢). With 51 looks the balanced composition determines the whole shuffle, giving 61.193¢. The missing parameter is the work to *produce* the bit.
5. Determine the limiting rolling-preview fraction $d$, close the remaining pure-factorial/field-operations question in a well-specified language, or test how many of the verified reductions survive an asymmetric balanced-payoff urn (for example $n$ cards worth +2 and $2n$ worth −1).
6. On the formal side, link the discrete stopping/value limits and the Brownian inequalities, connect the two advice representations explicitly, and discharge the remaining finite and analytic input certificates inside Lean for the dyadic player. General pathwise advice/nominations equivalence and full-history nomination optimization already have Lean proofs.
At the spectral boundary, determine whether $n^\mu[Q_{2n}(0)-V_n]$ converges, characterize its putative amplitude and bound the remainder after subtraction. Even convergence to a positive constant would leave the proposed $o(n^{-1/2})$ remainder to prove. For the half-card rule, the finite maximum at 220 cards suggests a sharper all-deck conjecture of less than 0.003 cents. The retained-79 variant poses a different extremal question. For an unchanged 79-rule, the leading regret estimate $2.43148\times10^{-9}\sqrt n$ dollars equals a cent at roughly $1.69\times10^{13}$ **pairs**, or $3.38\times10^{13}$ cards. This extrapolation supplies a scale, with no bound on the first crossing.
Determine whether the established $O(t^{-1/6})$ remainder in the continuous half-card boundary admits a $c\,t^{-1/4}$ term for the specified fractional-payoff urn. The integer cutoffs observed at first strict continuation times are interval-censored by parity. A fit to those crossings alone cannot distinguish all possible interpolants. Determine the multiplicative constants for real regret and optimal zero payouts, and the finite deck giving the global worst regret of each rule.
### Suggested order for an adversarial reading
Start with the ordinary integer Bellman recurrence and independently recover the 52-card fraction.
For the new guarantee, inspect the sign of each rounded mean, the reflection factor at both artificial walls, the equality case in the squared exercise test, and the first surviving row on either side of the switch.
For an alleged counterexample, report the initial pair count, the remaining counts at the offending state, the payoffs of both legal actions, and whether the claim at issue concerns a state, a whole shuffle, or an expectation.
For the closed-form result, focus on uniformity of the differential equation across the long frontier plateaus.
For the advice limits, inspect what the observer knows when a nomination is made or rounded to the next time-grid point.
These checks target the points where a stronger-looking conclusion would actually change the problem.
### Selected literature and provenance
- The original finite-urn theory and benchmark problem. [Shepp 1969](https://faculty.wharton.upenn.edu/wp-content/uploads/2012/04/Explicit-solutions-to-some-problems-of-optimal-stopping.pdf "Explicit Solutions to Some Problems of Optimal Stopping") · [Boyce 1973](https://sites.math.rutgers.edu/~zeilberg/EM13/boyce1973.pdf "On a simple optimal stopping problem") · [Branwen et al 2022](https://gwern.net/problem-14 "Problem 14 Dynamic Programming Solutions")
- D-finite sequences and the scope of multiple binomial sums. [Stanley 1980](https://math.mit.edu/~rstan/pubs/pubfiles/45.pdf "Differentiably finite power series") · [Bostan et al 2017](https://mathexp.eu/bostan/publications/BoLaSa17.pdf "Multiple binomial sums")
- Brownian optimal stopping and conditioned random walks. [Ekström & Wanntorp 2009](https://www.cambridge.org/core/journals/journal-of-applied-probability/article/optimal-stopping-of-a-brownian-bridge/AC73024AFDDD7FE2127B4123F3978FF9 "Optimal stopping of a Brownian bridge") · [Dimitrov & Wu 2021](https://doi.org/10.1007/s00440-021-01030-y "KMT coupling for random walk bridges")
- Preview/recall in continuous time and prefix codes. [Ernst et al 2017](https://www.sciencedirect.com/science/article/pii/S0304414917300923 "The value of foresight") · [Huffman 1952](https://doi.org/10.1109/JRPROC.1952.273898 "A Method for the Construction of Minimum-Redundancy Codes")
The game-specific extensions, claims of impossibility, calibrations, advice prices and software measurements are developed in this report.
A citation to one of these classical papers does not attribute those extensions to its authors.
## 8. Proofs and independent checks
The five appendices give the derivations. Where experiments reuse a proof or benchmark, the text points to its full worksheet in the embedded project. All numbered worksheets are extractable as Markdown.
### Appendix 1. The ordinary game, growth, and formula obstructions
#### 1.1. Finite formula via stopping sets
##### An exact finite formula in Lean
The formula below has no unknown stopping threshold or Bellman values on the right.
It sums over $2^{(n+1)^2}$ stopping sets and uses enormous integers.
Lean proves this particular formula for every deck size.
Let $S$ range over subsets of the $(n+1)^2$ states $(r,b)$, the remaining counts of red and black cards.
For a balanced color word $w$, let $p_S(w)$ be the balance at the **first** visited state in $S$, or zero at exhaustion.
A purely arithmetic definition numbers the visited states $s_0,\ldots,s_{2n-1}$ before exhaustion.
With $I_j=\mathbf1\{s_j\in S\}$ and $x_j$ their balances,
$$
p_S(w)=\sum_{j=0}^{2n-1}x_j I_j\prod_{i
#### 1.2. Finite obstacles, rationality, algebraic impossibility and the Brownian limit
##### A finite-deck stopping bound
With $t>0$ cards remaining, write $x$ for the current balance.
For a balanced initial deck, $x$ is also the number of remaining black cards minus the number of remaining red cards.
**It is optimal to stop whenever $x\geq 2\sqrt t$.**
The threshold is sufficient; play can become unprofitable at smaller balances.
Fix $a>0$ and put $d_s=a+s/a$, for every remaining horizon $s\geq 0$.
Consider the upper bound
$$
F_s(x)=x+\frac{(d_s-x)_+^2}{2d_s},\qquad
q_s(x)=\frac{d_s+x^2/d_s}{2},
$$
where $u_+=\max(u,0)$.
We have $x\leq F_s(x)\leq q_s(x)$, with $F_s=q_s$ for $x\leq d_s$.
Let $X'$ be the next balance from $(s,x)$.
An up-step has probability $(s-x)/(2s)$, giving
$$
E[X']=(1-1/s)x,\qquad E[(X')^2]=(1-2/s)x^2+1.
$$
If $x0$ choose $k=\lfloor c\sqrt n\rfloor$.
The logarithm of the binomial ratio is
$$
\sum_{j=0}^{k-1}\left[\log(1-j/n)-\log(1+(j+1)/n)\right]
=-\frac{k^2}{n}+O(k^3/n^2),
$$
by Taylor expansion with a uniform quadratic remainder.
The lower bound divided by $\sqrt n$ tends to $c e^{-c^2}$, maximized at $c=1/\sqrt 2$.
Stirling's formula applied to the upper bound gives
$$
\frac{1}{\sqrt{2e}}\ \leq\ \liminf_{n\to\infty}\frac{V_n}{\sqrt n}
\ \leq\ \limsup_{n\to\infty}\frac{V_n}{\sqrt n}
\ \leq\ \frac{\sqrt\pi}{2}.
$$
In particular $V_n=\Theta(\sqrt n)$, with no assumption about convergence to a Brownian optimal stopping problem.
##### No algebraic formula for the fair price
**Theorem.** For every nonzero polynomial $P\in\mathbb R[X,Y]$, there are arbitrarily large positive integers $n$ with $P(n,V_n)\ne0$.
In particular a fixed expression formed from $n$ and real constants by field operations and radicals cannot give $V_n$ for every sufficiently large $n$.
The claim concerns algebraicity as a function of $n$; every individual deck has a rational price.
More strongly, the positive integers where any fixed nonzero polynomial relation holds have natural density zero.
To see this, let $S$ be all positive integers where the proposed relation holds. A finite $S$ already has density zero.
Fix its finite list of monomials $X^iY^j$.
Each $n$ in $S$ gives a row of rational numbers $(n^iV_n^j)_{i,j}$.
These rows span a finite-dimensional rational vector space.
Choose a finite basis from the rows.
The basis matrix has a nonzero real null vector by hypothesis.
Gaussian elimination over the rationals gives a nonzero rational null vector as well, producing a nonzero relation in $\mathbb Q[X,Y]$ on all of $S$.
Factor that polynomial over $\mathbb Q(X)$ in the variable $Y$, clearing denominators and omitting finitely many $n$ where a pole occurs or a leading coefficient vanishes.
Any factor of degree one could give only a rational-function value $R(n)$.
A nonzero rational function grows in absolute value as $C n^m$ for an integer $m$ and some $C>0$.
The two-sided square-root bounds thus exclude every such factor for all sufficiently large $n$, and exclude the zero function as well.
Every remaining positive-degree factor is irreducible over $\mathbb Q(X)$ and has degree at least two in $Y$.
The integer form of **Hilbert's irreducibility theorem** gives a density-one set of positive integers where a given irreducible factor remains irreducible over $\mathbb Q$.
The intersection of finitely many density-one sets still has density one. Degree drops at only finitely many points.
None can vanish at the rational number $V_n$.
Factors depending only on $X$ vanish at finitely many integers.
Thus $S$ is contained in a density-zero set together with finitely many exceptions. Only rationality and two-sided square-root growth enter this argument. It works just as well for the sequence $\lfloor\sqrt n\rfloor$. Cohen gives the quantitative exceptional-set theorem. [Cohen 1981](https://doi.org/10.1112/plms/s3-43.2.227 "The Distribution of Galois Groups and Hilbert’s Irreducibility Theorem")
The same proof excludes a finite menu of algebraic formulas with *any* rule for choosing among them: take the product of their polynomial relations.
A separate stopping-frontier argument excludes every P-recursive expression, including finite sums of hypergeometric terms. An explicit fixed-length expression using elementary trigonometric functions and exponentiation gives the price exactly. [Derivation](#proof-factorials-and-problem-14-md)
##### No constant-coefficient linear recurrence
There is also an elementary obstruction to a different sort of formula.
An eventual homogeneous linear recurrence of fixed order with constant coefficients would make $G(z)=\sum_{n\geq0}V_nz^n$ rational, by multiplying the series by the characteristic denominator.
As $z\uparrow1$, the two-sided bounds give $G(z)=\Theta((1-z)^{-3/2})$.
Indeed, with $h=-\log z$, $h^{3/2}\sum_{n\geq1}\sqrt n\,z^n=h\sum_{n\geq1}\sqrt{nh}\,e^{-nh}$ tends to $\int_0^\infty \sqrt t\,e^{-t}\,dt$ by Riemann summation, and $h\sim1-z$.
A rational function has integer pole order at $z=1$, yielding a contradiction.
The follow-up proves the stronger polynomial-coefficient obstruction using the stopping frontier.
##### The leading coefficient for the discrete deck
For a standard Brownian bridge $B$ on $[0,1]$, Shepp gives its optimal stopping value explicitly. The finite-deck prices have exactly this leading coefficient:
$$
\lim_{n\to\infty}\frac{V_n}{\sqrt{2n}}
=(1-\alpha^2)\sqrt{\frac{\pi}{2}}=0.369136\ldots,
\qquad
\alpha=(1-\alpha^2)\int_0^\infty e^{\alpha y-y^2/2}\,dy.
$$
Here $\alpha\simeq0.839923676$ is the unique positive root. Shepp states the discrete prediction in §6 and explicitly says his argument for the discrete value limit is formal. The following discretization justifies the balanced case. [Shepp 1969](https://faculty.wharton.upenn.edu/wp-content/uploads/2012/04/Explicit-solutions-to-some-problems-of-optimal-stopping.pdf#page=10 "Explicit Solutions to Some Problems of Optimal Stopping")
**Restrict the decision times.** Put $T=2n$, and allow decisions only at $j_i=\lfloor iT/m\rfloor$, $0\leq i\leq m$, for a fixed $m\geq2$.
Normalize all balances by $\sqrt T$ and call this value $v_{T,m}$.
Rounding any stopping time up to the next grid point is again a stopping time, and the two balances differ by at most twice the largest within-block displacement from the block's starting balance.
The bridge is an independent fair sign walk conditioned to end at zero.
For any block of $\ell$ increments, its density relative to $\ell$ independent signs, evaluated at any particular sequence with sum $u$, is
$$
\frac{\Pr(W_{T-\ell}=-u)}{\Pr(W_T=0)}\leq C
$$
for a universal $C$ when $\ell\leq \lceil T/2\rceil$, by the central binomial bounds; $W$ here is the independent walk.
The maximal exponential inequality $\Pr(\max_{r\leq\ell}|W_r|\geq h)\leq2e^{-h^2/(2\ell)}$ follows from the nonnegative exponential submartingales $e^{\pm\lambda W_r}$ and $\cosh\lambda\leq e^{\lambda^2/2}$.
A union bound over the $m$ blocks gives the normalized maximum a tail bounded by $\min(1,2Cm\exp(-z^2 T/(2\lceil T/m\rceil)))$ at $z$.
Integrating this bound shows
$$
0\leq V_n/\sqrt T-v_{T,m}\leq C'\sqrt{\log(2m)/m}\qquad(T\geq m).
$$
**Pass to Brownian motion on the grid.** At fixed grid times $u
#### 1.3. P-recursiveness, factorials, and an explicit straight-line formula
##### Where the zero coefficients come from
Put $B_n=\binom{2n}{n}$, $D_n=B_n V_n$, and $D(z)=\sum_{n\ge0}D_nz^n$.
Let $A(r,b)$ be the sum of the optimal *final* balances over color orders from a state with $r$ red and $b$ black cards left.
Its current balance is $b-r$.
All future color orders have equal probability, giving integer aggregate values and the recurrence
$$
A(r,b)=\max\left\{(b-r)\binom{r+b}{r},\; A(r-1,b)+A(r,b-1)\right\}.
$$
The edges are $A(0,b)=b$, $A(r,0)=0$, and $A(n,n)=D_n$. [Boyce 1973](https://sites.math.rutgers.edu/~zeilberg/EM13/boyce1973.pdf "On a simple optimal stopping problem")
Let $T(r)$ be the first black count for which stopping is optimal in row $r$, counting a tie as a stop, and put $j_r=T(r)-r$.
We need three facts about this frontier.
1. $j_r$ is nondecreasing. The marginal gain over stopping is nonincreasing as black cards are added. Adding one red and one black to a strictly favorable state preserves favorability, by Boyce’s Theorem 3.8. Apply this at $b=T(r)-1$ to obtain $T(r+1)\ge T(r)+1$ for $r\ge 1$. [Boyce 1973](https://sites.math.rutgers.edu/~zeilberg/akherim/BoyceUrn.pdf#page=8 "On a simple optimal stopping problem")
2. $j_r\to\infty$. At fixed gap $j\ge0$, stop on gaining one additional dollar or else draw to the end. By reflection, the probability of hitting that target is $\binom{2r+j}{r-1}/\binom{2r+j}{r}=r/(r+j+1)$. The policy's expected final balance exceeds the current $j$ whenever $r>j(j+1)$.
3. $j_r=O(\sqrt r)$. One sufficient stopping condition with $t$ cards left and current balance $x$ is $x\ge2\sqrt t$. Appendix 1.2 proves the bound. Substituting $t=2r+x$ gives the desired order.
It follows that for each integer $L$ there are arbitrarily high levels $j$ at which $j_r=j$ for at least $L$ consecutive rows.
Otherwise, after finitely many rows, at most $L$ rows could be spent at each level, implying $r=O(j_r)$.
Each such run ends, since $j_r$ is unbounded.
Write
$$
w=\sqrt{1-4z},\qquad U=(1+w)/2,\qquad u=(1-w)/2,\qquad C=1/U .
$$
Here $C$ is the Catalan generating function, $U+u=1$, $Uu=z$, $U(0)=1$, and $u=z+O(z^2)$.
For all $r,b\ge0$ define the formal extension
$$
H(r,b)=[z^b]C^{r-b}D(z).
$$
Since $C^{-1}+zC=1$, this extension satisfies Pascal’s addition rule at every interior state.
It agrees with $A$ on the diagonal.
For $r>b$, finishing guarantees zero, a strict improvement over stopping at $b-r<0$, so $A$ must also obey Pascal’s rule there.
On $b=0$ the two agree since $D_0=0$.
Induction gives $H=A$ throughout the negative half.
The agreement extends **through the first stopping state of every positive row**.
Induct on $b-r>0$ for states with $b\le T(r)$, taking $r\ge1$.
The parent $(r+1,b)$ strictly continues because $bV_{\rm urn}(m,p)$. Thus the largest strictly favorable black count increases by at least one when another red is added; the first stopping column $T(r)$ obeys $T(r+1)\ge T(r)+1$. [Boyce 1973, p. 304](https://sites.math.rutgers.edu/~zeilberg/EM13/boyce1973.pdf#page=8 "On a simple optimal stopping problem")
##### Why a polynomial recurrence cannot produce those gaps
A series is D-finite if it satisfies a nontrivial linear differential equation with polynomial coefficients.
A sequence is P-recursive exactly when its ordinary generating function is D-finite.
P-recursive sequences are closed under pointwise multiplication.
In particular, P-recursiveness of $V_n$ would imply that of $D_n=B_nV_n$. [Stanley 1980](https://math.mit.edu/~rstan/pubs/pubfiles/45.pdf "Differentiably finite power series")
Assume $D$ is D-finite.
It is analytic near 0 since $0\le D_n\le n4^n$.
Choose one monic ordinary differential operator $L$ with rational-function coefficients in $z$ that annihilates both $D$ and $1/w$.
Such an operator exists by taking a linear dependence among the derivative pairs of these two D-finite functions over $\mathbb C(z)$.
Let its order be $d$ and its solution space on a small disk of ordinary points be $\mathcal V$, of dimension $d$.
We prove two uniform statements about the functions in
$$
\mathcal W_j=U^j\mathcal V+u^j\mathcal V.
$$
**First, a common differential equation has order and coefficient degrees bounded independently of $j$.**
Use a symbolic parameter $J$.
For $f\in\mathcal V$, every derivative of $U^Jf$ of order $k\le 2d$ can be expressed as $U^J$ times a linear combination of $f,f',\ldots,f^{(d-1)}$.
Choose the companion matrix $A(z)$ of the fixed monic differential operator for the jet $(f,f',\ldots,f^{(d-1)})$. With $r_0=(1,0,\ldots,0)$ the derivative rows satisfy $r_{k+1}=r_k'+r_kA+J(U'/U)r_k$, where $U'/U=-(1-w)/(2zw)$. Induction puts every row in $\mathbb C(z,w)[J]^d$. Differentiation introduces no poles in the parameter $J$.
The conjugation $w\mapsto-w$ gives the corresponding row for $u^Jf$.
Write each row as $a_k+w b_k$, $a_k,b_k\in\mathbb C(J,z)^d$.
The $2d+1$ rows $(a_k,b_k)$ in dimension $2d$ are dependent over $\mathbb C(J,z)$.
Clearing denominators and removing any polynomial factor in $J$ common to every scalar coefficient of every power of $z$ gives a single nontrivial equation
$$
\mathcal L_J=\sum_{k=0}^{2d}P_k(J,z)\,\partial_z^k,\qquad P_k\in\mathbb C[J,z].
$$
For every sufficiently large integer $j$, specialization gives a nonzero operator annihilating $\mathcal W_j$.
A nonzero coefficient of a power of $z$ is a nonzero polynomial in $J$, so only finitely many specializations can make the entire operator zero. In particular $M=\max_k\deg_z P_k$ is independent of $j$. Moreover $P_{2d}$ cannot vanish identically. Otherwise every sufficiently large nonexceptional specialization would have order less than $2d$, yet annihilate the $2d$ independent members of $\mathcal W_j$ established below. On a disk away from singularities an equation of order $k$ has solution space of dimension at most $k$.
**Second, every nonzero solution of this equation analytic at zero has order of vanishing at most $j+B$ for a constant $B$ independent of large $j$.**
Here are the details, including possible singularities of $L$ at zero.
Choose the ordinary disk above so that $u,U$ are nonzero and the branch of $w$ extending from $w(0)=1$ is single-valued.
The ratio $h=U/u$ is nonconstant.
Choose two closed subdisks $K_1,K_2$ with $\max_{K_1}|h|=a2B$ these two exponent intervals are disjoint, so the lowest terms of two nonzero summands cannot cancel.
This proves the bound $\operatorname{ord}_0 y\le j+B$.
**Apply both bounds to a long plateau.**
Let its first coefficient index be $N=r+j$, and its length be $s>M+2d$.
Let $P$ be the truncation of $E_j$ through degree $N-1$.
The analytic tail $Y=E_j-P$ is nonzero by strict continuation immediately after the plateau and starts at degree $N+s$.
Since $E_j\in\mathcal W_j$, we have $\mathcal L_j P=-\mathcal L_j Y$.
The left side is a polynomial of degree at most $N-1+M$.
The right side vanishes to order at least $N+s-2d$.
Thus both sides are identically zero.
Now $Y$ is a nonzero analytic solution of $\mathcal L_j$ of order at least $r+j+s$, exceeding $j+B$ for large $r$.
That contradiction proves the theorem.
This argument also rules out agreement with a P-recursive formula after an arbitrary finite prefix.
Finite changes preserve D-finiteness.
An integer-affine factorial ratio has a rational consecutive-term quotient, making it hypergeometric and hence P-recursive.
For rational slopes, split $n$ into residue classes modulo a common denominator.
On each class the gamma recurrence gives a rational consecutive-term quotient.
Interlacing finitely many P-recursive sequences preserves P-recursiveness, by the ordinary generating function identity $\sum_{a=0}^{q-1} z^aF_a(z^q)$.
Finite sums and pointwise products preserve the class as well. [Stanley 1980](https://math.mit.edu/~rstan/pubs/pubfiles/45.pdf "Differentiably finite power series")
The result also excludes many formulas with a summation limit that grows with the deck. Neither $V_n$ nor its unnormalized integer total $D_n$ can be a multiple binomial sum in the sense of Bostan, Lairez and Salvy. Their Corollary 3.6 gives a polynomial-coefficient recurrence for every such sum. For example, there can be no formula for $D_n$ resembling the Apéry numbers $\sum_{k=0}^n\binom nk^2\binom{n+k}k^2$, assembled using the binomial factors, affine index substitutions, and summations in their definition. [Bostan et al 2017](https://mathexp.eu/bostan/publications/BoLaSa17.pdf#page=17 "Multiple binomial sums")
The sufficient stopping bound is proved once in [Appendix 1.2](#proof-mathematics-md).
##### How the fixed-length formula escapes the theorem
For $n\ge1$, store the proposed values of all interior states of a Bellman table as the digits of a single integer $ja^b$ and
$$
a^b=2^{hb}\bmod M
$$
because $2^h\equiv a\pmod M$.
This reduces all the powers in the straight-line expression to the factorial identity.
Lean proves both the factorial quotient and the resulting expression for $a^b$ for every pair of nonnegative integers, including $0^0=1$. The proofs use integer inequalities on the falling factorials. See `two_eq` and `power_eq` in `FactorialPowers.lean`.
The ordinary field-division-only version for arbitrary nested factorials remains a separate question.
##### Verification and scope
The non-P-recursiveness theorem above is a mathematical proof.
The source kit also includes an independent first-order obstruction via the Pólya–Carlson theorem. [First-order proof](#proof-first-order-obstruction-md)
Lean 4.19.0 checks the uniqueness and game interpretation of the local table constraints for every deck size, the extension through the first stopping state given the frontier hypotheses, the combinatorial plateau lemmas, and the factorial substitution for every exponent.
`TaylorGap.lean` checks the final truncation argument for polynomial differential operators given the analytic order bound. Constructing the uniform differential equation and proving that order bound are the analytic steps in the paper.
It implements the packed formula and checks the complete small-deck examples with native bitwise conjunction in the Lean kernel.
The all-size identities for the packed digits and the differential-equation proof above are proved on paper.
The Python checks include the complete candidate space for one pair and 527 valid or corrupted candidate boards for one through seventeen pairs.
The frontier regression also verifies the Catalan extension against an independent exact-integer calculation at 1,199 positive-gap and 160 negative-gap states. For example, at gap six the exercise surplus is exactly zero for $r=19,\ldots,26$ and its aggregate jumps to $391661796060927$ at $r=27$.
For four cards, the packed enumeration alone takes about $77\cdot2^{77}$ bits, or 1.45 yottabytes, to recover $V_2=2/3$. This is before expanding the arithmetic implementation of bitwise conjunction.
The practical exact and certified solvers in the kit remain the way to compute large decks.
##### Appendix. The explicit straight-line expression
There is one expression, independent of deck size, which gives the exact fair price using addition, subtraction, multiplication, exponentiation, integer quotient and one final rational quotient. The expression is implemented in `StraightLine.lean` and `straight_line.py`. The derivation below proves it for every deck size. Its largest integer is already impractical for four cards. The construction explains how a fixed-length formula can coexist with both the algebraic impossibility theorem and the computational difficulty.
###### Two tables in a polynomial
Write $n$ for the number of cards of each color. First take $n\ge1$. Use $r,b$ for the numbers of red and black cards remaining, and set
$$
D=2^{4n+1},\quad B=4D,\quad h=2n+1,\quad u=B^h,\quad v=B,\quad z=u+v.
$$
Let $P(z)=(z^h-1)/(z-1)$. Its derivative has the finite expression $P'(z)=(h z^{h-1}-P(z))/(z-1)$.
The digit of $P(z)$ in base $B$ at position $hr+b$ equals $C(r,b)=\binom{r+b}{r}$ for $r+b\le2n$. Indeed the term of degree $r+b$ in the geometric series is $(u+v)^{r+b}$. All pairs in the triangle have distinct positions, since $0\le b
#### 1.4. Independent first-order obstruction by analytic continuation
Let $V_n$ be the optimal expected payoff starting with $n$ cards of each color at zero score.
**Theorem.** There is no rational function $q\in\mathbb C(X)$ with $V_{n+1}=q(n)V_n$ for all sufficiently large positive integers $n$.
In particular the price cannot be a single product or quotient of factorials of integer-affine functions of $n$, even multiplied by a rational function and a constant to the $n$th power.
The same conclusion holds for products of gamma factors whose arguments change by fixed integers at each step and which define a finite nonzero expression for all large $n$.
These are consequences of the factorial or gamma recurrence.
The proof has two parts.
Integrality and the analytic continuation of a hypergeometric generating function force an eventual geometric sequence.
The urn’s moving stopping boundary rules out that sequence.
##### 1. Counting decks
Write $B_n=\binom{2n}{n}$, $D_n=B_n V_n$, and $d_n=D_n/4^n$.
There are $B_n$ equiprobable color strings.
A deterministic optimal stopping policy exists by finite backward induction, and its payoffs are integers, so $D_n$ is an integer.
The sequence $V_n$ is hypergeometric exactly when $D_n$ is, since $B_{n+1}/B_n=2(2n+1)/(n+1)$.
Let $M$ be the largest score on a uniform bridge from zero back to zero in $2n$ steps.
Reflection at the first visit to a positive integer $h$ gives
$$
\Pr(M\ge h)= \binom{2n}{n-h}/B_n .
$$
A player who takes $h$ at the first visit and otherwise finishes at zero earns $h\Pr(M\ge h)$.
With $h=\lfloor\sqrt n\rfloor$, the probability tends to $e^{-1}$, by expanding the logarithm of the product $\prod_{j=0}^{h-1}(n-j)/(n+j+1)$.
The prophet who sees all the cards earns $E M=(4^n/B_n-1)/2$, by summing the same probabilities.
Consequently $V_n=\Theta(\sqrt n)$, $D_n=\Theta(4^n)$, and $d_n<1/2$ for $n>0$.
##### 2. What an integer hypergeometric sequence of this size can be
This step applies to any positive integer sequence $D_n=\Theta(4^n)$ that is eventually hypergeometric.
Suppose $D_{n+1}/D_n=P(n)/Q(n)$ eventually, for polynomials over $\mathbb C$.
The growth bound implies equal degrees and leading-coefficient ratio $4$.
Indeed a rational quotient tends to zero, to a nonzero constant, or to infinity.
The geometric mean of the positive consecutive quotients tends to the same limit, whereas $D_n^{1/n}\to4$.
Put $G(z)=\sum_{n\ge0}D_n z^n$ and $\theta=z\,d/dz$.
The recurrence gives
$$
[Q(\theta-1)-zP(\theta)]G(z)=H(z),
$$
where $H$ is a polynomial absorbing the finitely many exceptional coefficients.
For common degree $k>0$, the coefficient of the highest derivative is $z^k(q_k-zp_k)$, so the only potential singularities are $0,1/4,\infty$.
For $k=0$ the sequence is already eventually geometric.
The branch of $G$ analytic at zero extends throughout the slit plane $\mathbb C\setminus[1/4,\infty)$.
The ODE permits continuation there away from zero, and loops around zero have trivial monodromy for the analytic germ we started with.
Make the substitution
$$
z=\frac{u}{(1+u)^2},\qquad
w=\frac{1-u}{1+u}=\sqrt{1-4z}.
$$
It maps the open unit disk in $u$ conformally onto the slit $z$-plane.
Thus $L(u)=G(u/(1+u)^2)$ is analytic throughout the disk.
Its Taylor coefficients are integers because the substituted series has integer coefficients and zero constant term.
Furthermore $L$ extends analytically through a neighborhood of $u=i$.
Here $z(i)=1/2$ is an ordinary point of the ODE and the substitution is locally invertible, so the branch arriving from inside the disk continues across.
The Pólya–Carlson theorem says that an integer power series of radius one is rational or has the full unit circle as a natural boundary.
The continuation at $i$ excludes a natural boundary.
If the radius exceeds one the integer coefficients eventually vanish, also giving rationality.
Thus $L$ is rational. [Bell et al 2014](https://doi.org/10.1016/j.indag.2014.04.005 "Towards a Pólya–Carlson dichotomy for algebraic dynamics")
A rational solution cannot have a pole at an ordinary point of the pulled-back ODE.
The finite potential poles in $u$ are $0,1,-1$, and the series is regular at zero.
Infinity is also allowed.
In the coordinate $w$, the poles are therefore contained in $\{0,-1,\infty\}$.
Partial fractions express $G$ by integer powers of $w$ and terms $(1+w)^{-k}$.
For the latter use $(1+w)^{-k}=(1-w)^k/(4z)^k$.
The coefficients of an even power of $w$ are eventually $4^n$ times a polynomial in $n$ (possibly zero), by the binomial theorem.
The coefficients of an odd power are $B_n$ times a rational function of $n$: start from $w^{-1}=(1-4z)^{-1/2}$, then shift the exponent by an integer in the binomial coefficients.
A fixed coefficient shift from $z^{-k}$ preserves both classes.
It follows that, eventually,
$$
D_n=4^n A(n)+B_n S(n)
$$
with $A$ polynomial and $S$ rational.
The two basic sequences are independent over rational functions of $n$.
Indeed $4^n/B_n\sim\sqrt{\pi n}$, whereas a nonzero rational function has integer growth exponent.
Substitution of the decomposition into $D_{n+1}=q(n)D_n$ hence shows that each nonzero summand separately obeys the same recurrence.
If both were nonzero, their ratio would be constant for all large $n$, contradicting independence.
A lone term $B_n S(n)$ has order $4^n n^{k-1/2}$ for an integer $k$, incompatible with $\Theta(4^n)$.
A lone term $4^n A(n)$ has this order only if $A$ is constant.
We have proved
$$
D_n=C4^n\quad\text{for all sufficiently large }n,\qquad 02m$ this gives
$$
a_t(x)=J_t(x):=2CF_t(x)+p_t(x) R(t,x),\qquad
R(t,x)=-x\sum_{ij(j+1)$.
Since $j_r=O(\sqrt r)$, there are infinitely many distinct integers $j$ for which $j_r=j$ on arbitrarily long consecutive runs of $r$.
More precisely, for every fixed $L$ there are infinitely many distinct levels whose run length exceeds $L$. Otherwise the number of rows traversed up to gap $j$ would be $O(j)$.
Set $E_t(x)=J_t(x)-x p_t(x)$.
At the first-stopping frontier, $E_{2r+j_r}(j_r)=0$.
On a run with $j_r=j$, consecutive zeros imply
$$
K(t,j)=\frac{E_{t+2}(j)-E_t(j)}{p_t(j)}=0,\qquad t=2r+j .
$$
Now $K(t,x)$ is a *fixed rational function in two variables*.
In fact
$$
F_{t+2}(x)-F_t(x)=\frac{p_t(x+2)-p_t(x-2)}8,\quad
\frac{p_{t+2}(x)}{p_t(x)}=\frac{(t+1)(t+2)}{(t+2)^2-x^2},\quad
\frac{p_t(x\pm2)}{p_t(x)}=\frac{t\mp x}{t\pm x+2}.
$$
The explicit denominators are nonzero at the interior, large-time frontier states used here.
Clear denominators and let $d$ be the degree in $t$ of the numerator, assuming it is nonzero.
Choose infinitely many distinct $j$ whose run produces more than $d$ consecutive differences.
For each such $j$, the numerator polynomial as a function of $t$ has too many distinct roots and is identically zero.
Its coefficients as polynomials in $j$ vanish for infinitely many $j$.
Thus the numerator is identically zero after all.
This is impossible at $x=1$.
For odd $t$, symmetry gives $F_t(1)=(1+p_t(1))/2$, and hence
$$
E_t(1)=C+p_t(1)\big(C-1+O(t^{-1})\big).
$$
It tends to $C$ and differs from $C$ for all sufficiently large odd $t$ because $C\le1/2$.
But the identity $K(t,1)=0$ would make $E_t(1)$ constant along that very sequence.
This contradiction proves the theorem.
The conclusion excludes every single hypergeometric term, including arbitrarily large fixed factorial products and arbitrary finite changes at the beginning.
The companion proof excludes all polynomial-coefficient linear recurrences, including finite sums and products of hypergeometric terms. [Which closed forms can solve Problem 14?](#proof-factorials-and-problem-14-md)
### Appendix 2. Exact and certified price computation
#### 2.1. Certified band solver and comparison with the article’s C implementation
##### Certified numerical computation
The C program uses two different arguments to discard states.
* **High positive balance.** With $t$ cards remaining, the code proves that $x\ge\sqrt{5t/2}$ is high enough to stop immediately.
Below this line it still takes the better of stopping and drawing at each state.
The proof in `fast.c` constructs an explicit upper bound on the future value that equals the cash in hand above the cutoff.
* **Deep negative balance.** On first reaching $-h$, the restricted rule commits to drawing the rest of the deck for zero.
Compared with optimal play, the loss is at most $n$ on decks that ever reach $-h$ and zero on all other decks.
By reflection,
$$
0\le V_n-V_n^{(h)}\le n\frac{\binom{2n}{n-h}}{\binom{2n}{n}}
\le n\exp[-h^2/(n+1/2)] .
$$
The program chooses $h$ by conservative integer comparisons.
For a fixed truncation budget $\varepsilon$, this takes $O(n^{3/2}\sqrt{\log(n/\varepsilon)})$ arithmetic operations and $O(\sqrt{n\log(n/\varepsilon)})$ working space for large $n$.
All interpolation weights and values are nonnegative.
One pass rounding every operation down and a second rounding up bound floating-point error as well.
The program prints both endpoints in decimal and hexadecimal.
Its budget argument controls the tail.
The **returned interval** measures the full error, including rounding.
Timings below are wall seconds on one AMD EPYC 9V74 machine using GCC 14.2.
The article's block-and-skip implementation used the faster of block sizes 400 and 1,000 for each configuration, with three runs per median.
The interval solver used one thread, two passes, and a $10^{-9}$ truncation budget.
Its first two entries are medians of seven runs.
The million-pair entry is a single run. [Gwern et al 2022](https://gwern.net/problem-14#blocks-skipping "Blocks + Skipping")
| Pairs $n$ | Article, 1 thread | Article, 8 threads | Certified, 1 thread | Certified value, rounded |
|---:|---:|---:|---:|---:|
| 10,000 | 0.02585 s | 0.00997 s | 0.00465 s | 52.19220646 |
| 100,000 | 2.285 s | 0.3547 s | 0.1224 s | 165.075847 |
| 1,000,000 | — | — | 3.83 s | 522.03353 |
At 100,000 pairs the interval is $[165.07584652820207,165.07584653807451]$.
At one million pairs it is $[522.03353247022857,522.03353276764461]$.
#### 2.2. Exact aggregate values and Catalan returns
The current executable replaces the packed multiplication described below with an exact cyclic transform. The original implementation is in `baseline/exact-packed.cpp`. [Transform derivation and timings](#proof-exact-fermat-md)
`exact.cpp` takes **pairs** (cards of each color). The 52-card game has 26 pairs. Build with a C++17 compiler and GMP headers and libraries.
```sh
c++ -O3 -std=c++17 exact.cpp -lgmpxx -lgmp -o exact
./exact 26
./exact 26 --boundary
python3 exact_test.py ./exact
```
The first command after compilation prints `41984711742427/15997372030584`. The second prints CSV giving, for every number of remaining red cards, the first number of remaining black cards for which stopping is optimal. Stop at or above that count. At exact ties the output chooses to stop. The thresholds apply to arbitrary decks with those remaining counts.
##### Eliminating the negative half of the board
Let $r,b$ count remaining reds and blacks, $x=b-r$ be current score relative to a balanced starting deck, and $C(r,b)=\binom{r+b}{r}$. Let $A(r,b)$ sum the optimal final score over the $C(r,b)$ equally likely color sequences. On each sequence the stopping rule knows only previously exposed colors. Splitting these sequences by first card gives the integer Bellman equation
$$
A(r,b)=\max\left\{(b-r)C(r,b),\ A(r-1,b)+A(r,b-1)\right\}.
$$
The edges are $A(0,b)=b$ and $A(r,0)=0$. The desired value is $D_n/\binom{2n}n$, where $D_n=A(n,n)$.
At a negative score, drawing every remaining card guarantees the higher score zero. Play must therefore continue at least until the next visit to zero. Starting with $(r,r-1)$, the number of first passages to $(j,j)$ is the Catalan number $K_{r-j-1}=\binom{2(r-j-1)}{r-j-1}/(r-j)$. Remove the last upward step and replace every earlier score $x$ by $-1-x$ to get a nonnegative Dyck path. Every such prefix can precede every continuation deck at $(j,j)$. The entire negative triangle reduces to one convolution
$$
A(r,r-1)=\sum_{j=0}^{r-1}D_j K_{r-j-1}.
$$
Each new diagonal entry can now be found from the first positive-score neighbor and the convolution. This identity counts all decks exactly, including arbitrarily deep negative excursions.
The code computes this convolution online by bisecting row-index intervals. Once the left half of an interval is solved, one polynomial product adds its contributions to every row in the right half. Each pair of source and later target belongs to a unique split or to the same leaf. Coefficients are packed into the digits of a large integer, and GMP multiplies the two integers. The radix is large enough to prevent carries into any required coefficient. Within 1,024-row leaves, direct Pascal additions on the local negative triangle cost less. Contributions from earlier leaves have already arrived.
##### Finding the stopping boundary
Write $W(r,b)=A(r,b)/C(r,b)-(b-r)$ for optimal gain over stopping now. Adding a black card cannot improve $W$. A player in the shorter deck can insert a virtual black at a uniformly random position, simulate any longer-deck policy, and obtain at least its score. Adding a red cannot reduce $W$. Mark a red by choosing a uniformly random red rank in advance, and follow a shorter-deck policy while ignoring this red for decisions. Any marked red actually drawn can only add to the gain. Private randomization cannot beat the best deterministic policy.
Consequently each row has a stopping threshold, and any black count below the previous row's threshold is also a continuation state of the new row. Below that threshold the program only adds the two child aggregates. At and beyond it, the upper neighbor has stopped, so its aggregate is a binomial coefficient times its current score. The code compares the exact stop and continue payoffs, terminating a row on the first tie or loss. The few binomials needed are advanced by exact divisions.
Boyce published an integer Pascal algorithm for this urn in 1973. His Theorem 4.2 normalizes the *gain over stopping*. The Catalan convolution above uses the *absolute final score*, which is harmonic throughout the negative half. [Boyce 1973](https://sites.math.rutgers.edu/~zeilberg/EM13/boyce1973.pdf "On a simple optimal stopping problem").
##### Complexity
For $n$ pairs the positive continuation strip has $O(\sqrt n)$ width, by the stopping bound in the main report or Shepp's asymptotic boundary. The program discovers the frontier exactly. It evaluates $O(n^{3/2})$ strip cells, with $O(n)$-bit integers. Each splitting level packs $O(n^2)$ bits in total. With quasi-linear integer multiplication, the convolution takes $\widetilde O(n^2)$ bit operations, including the logarithmic number of levels. The full algorithm takes $O(n^{5/2})+\widetilde O(n^2)$ bit operations and $O(n^2)$ bits of memory. The direct integer triangle takes $\Theta(n^3)$ bit operations for its negative half. These are bit complexities and do not imply a faster way to print all the quadratic number of individual off-diagonal values.
##### Verification and timings
The independent Python test uses the untransformed rational Bellman equation, checks all exact fractions and stopping thresholds through 128 pairs, and checks the packed algorithm against the exact triangle immediately around the leaf boundary and for a multi-level case. The `--triangle` comparison fills the negative triangle with one GMP addition per cell. It uses the same frontier, reduction, and output code as the accelerated implementation.
Single process, one run per cell, AMD EPYC 9V74, GCC 14.2, `-O3`. Times are user plus system CPU seconds, including printing the entire fraction to a pipe. The two outputs were compared byte for byte. At 1,000 pairs both paths use a single local triangle.
| Cards | Pairs | Catalan blocks | Exact triangle | Speedup |
|---:|---:|---:|---:|---:|
| 2,000 | 1,000 | 0.010 s | 0.010 s | 1.0× |
| 8,000 | 4,000 | 0.420 s | 0.338 s | 0.80× |
| 16,000 | 8,000 | 2.05 s | 2.48 s | 1.21× |
| 32,000 | 16,000 | 11.0 s | 40.3 s | 3.67× |
| 48,000 | 24,000 | 29.4 s | 145.1 s | 4.93× |
To reproduce a row, run `./exact 16000` and `./exact 16000 --triangle` with an external timer, and compare the two fractions.
#### 2.3. Cyclic transforms and bit complexity
Build and run from this directory. The argument counts cards of each color.
```sh
c++ -O3 -std=c++17 exact.cpp -lgmpxx -lgmp -o exact
./exact 26
./exact 26 --boundary
python3 exact_test.py ./exact
```
The older exact solver packs the whole polynomial product into the digits of a single GMP integer. This variant computes a cyclic product over $\mathbb Z/(2^M+1)$ and reads its middle coefficients. It also reuses the GMP storage for the positive-score strip.
A divide-and-conquer node $[l,h)$ with midpoint $m$ multiplies the $m-l$ diagonal numerators $D_l,\ldots,D_{m-1}$ by the first $h-l-1$ Catalan numbers $C_k$. It needs only the coefficients at indices $m-l-1$ through $h-l-2$. If $L$ is the next power of two at least $h-l-1$, coefficients wrapping modulo $X^L-1$ land strictly below that interval. Choose $M$ as the first multiple of $L/2$ at least $2(h-2)$. The root $2^{2M/L}$ gives an invertible $L$-point transform modulo $2^M+1$. At every shorter radix-two stage the half-length power of its root is $-1$, so butterfly inversion works whether or not the modulus is prime. Twiddles reduce to binary shifts with a signed wrap.
To see that residues determine the exact coefficients, the reflection-principle prophet bound gives $D_i<4^i/2$. Each target $j
#### 2.4. Computing the diagonal along the exercise frontier
Let $n$ count **cards of each color**. The following algorithm finds the exact optimal payoff and the stopping column for every black count through $n$. With fast integer multiplication it costs $\widetilde O(n^2)$ **bit operations** and $O(n^2)$ bits of working storage in the linear-workspace multiplication model. The previous exact algorithm's positive strip used $O(n^{5/2})$ bit operations. This implementation trades that strip for polynomial products. For the deck sizes benchmarked here the separate Fermat-ring solver is faster in wall time.
```sh
c++ -O3 -std=c++17 frontier.cpp -lgmpxx -lgmp -o frontier
./frontier 26
./frontier 26 --boundary
python3 test_frontier.py ./frontier ./exact
```
The value is $41984711742427/15997372030584$. In the CSV, stop if and only if **remaining black minus remaining red is at least the printed gap**. Stop on ties.
##### Two possible decisions per column
Let $A(r,b)$ be the sum of optimal *final scores*, expressed relative to the origin of a balanced deck, over all color orders of the $r$ red and $b$ black remaining cards. Immediate stopping at score $b-r$ gives $(b-r)\binom{r+b}{b}$. Drawing instead gives $A(r-1,b)+A(r,b-1)$. Define $D_b=A(b,b)$ and $D(z)=\sum_{b\ge0}D_bz^b$.
Write $k_b$ for the smallest red count making continuation strictly profitable when $b$ black cards remain. Adding a black cannot help, so $k_b$ is nondecreasing. Adding one of each color strictly improves a previously favorable urn, so $k_{b+1}\le k_b+1$. The first stopping gap $q_b=b-k_b+1$ consequently satisfies $q_0=0$ and $q_b-q_{b-1}\in\{0,1\}$. The inequalities are also valid for the initial empty and one-card cases. [Boyce 1973](https://sites.math.rutgers.edu/~zeilberg/EM13/boyce1973.pdf "On a simple optimal stopping problem")
For $U=(1+\sqrt{1-4z})/2$, put $H_j=U^jD$ for integer $j$. The coefficient $[z^b]H_j$ gives $A(b-j,b)$ throughout the continuation portion of column $b$ and at its **first** stopping gap. Here is the justification. On the zero gap this is the definition of $D$. On gap $-1$, first return to zero gives the Catalan convolution $H_{-1}=D/U$. For instance the coefficient at $b$ is $\sum_{i=0}^b D_i C_{b-i}$, where $C_k$ is the $k$th Catalan number. To extend toward positive gaps, $U^2=U-z$ implies $H_{j+1}=H_j-zH_{j-1}$. This is Pascal's equation solved for the red child of a continuing parent. At every gap $1\le j\le q_b$, the parent with one extra red card strictly continues. Its black child is also favorable (or lies on the nonpositive side) and has gap $j-2$. Induction on gap therefore reaches the first stopping state itself.
Suppose columns through $b-1$ are solved. Let $q=q_{b-1}$ and form two candidates
$$
S_j=j\binom{2b-j}{b}-[z^b]U^j\sum_{i0$ and $k>0$ they are $-(j/k)\binom{2k-j-1}{k-1}$ with the generalized integer binomial convention, by Lagrange inversion of $U=1-z/U$. The implementation generates the low coefficients and the negative tail by adjacent-term ratios, jumping across the intermediate zeros.
Only a constant number of polynomial products per node is needed. The program uses signed Kronecker substitution. It packs coefficients into a power-of-two base larger than twice the largest possible absolute convolution coefficient, multiplies with GMP, and reads the requested middle digits. For a previous negative digit the raw representation borrowed one from the current digit. Its high bit tells the decoder to add that one back. A sign-extended prefix handles negative packed products. Short products use direct GMP multiply-adds.
##### Bit complexity and checks
At a node of length $s=h-l$, the polynomials supplied for multiplication have $O(s)$ coefficients. The recentring polynomials have degree at most $m-l$. Coefficients of $U^j$ truncated through degree $s$ have $O(n)$ bits: for example $U=1-z\sum C_kz^k$, so Cauchy's coefficient bound on $|z|=1/8$ bounds their absolute values by $8^s K^j$ for a fixed $K$. A similar bound applies to $p_d$, or directly use its binomial coefficients. The incoming arrays are actual truncated products $U^jF$. Since $D_i$ is a sum of at most $4^i$ integer scores of magnitude at most $i$, its size and that of every incoming coefficient are $O(n)$ bits. Temporary sums and products of two such coefficients, including the extra carry guard, remain $O(n)$ bits.
Packing and unpacking require $O(sn)$ bit operations and each multiplication acts on $O(sn)$-bit integers. The direct fallback is used only when a dimension is bounded by a fixed constant. The nodes at one depth have total interval length $O(n)$. With quasilinear integer multiplication this gives $\widetilde O(n^2)$ bit operations after all $O(\log n)$ levels. Generating each kernel by its adjacent rational ratios, updating the binomials, and reducing the final fraction also fit this bound. Traversal is depth-first, so the outstanding array lengths decrease geometrically, giving $O(n^2)$ bits of data and buffers. The algorithm in fact determines all $D_1,\ldots,D_n$, whose total binary length is $\Theta(n^2)$ since $D_i=\Theta(4^i)$. There is no implied $\Omega(n^2)$ bound for the single-price problem.
`test_frontier.py` compares exact fractions and the complete column policy against the independent stopping thresholds of the previous row-oriented GMP implementation. It checks every price through 129 pairs, another ten sizes through 2,049 pairs, and every column at test sizes 26, 129, 1,025 and 2,049. The complete reduced fractions also agreed at 4,000 and 8,192 pairs. In sequential single-core runs the frontier prototype took 1.38 and 7.08 CPU seconds respectively. The cyclic Fermat solver took 0.20 and 1.05 seconds on those same decks.
#### 2.5. Certified fixed-point heat recursion
Build with `cc -std=c11 -O3 -march=native heat.c -lm -o heat`. The program accepts a pair count and optional positive truncation budget (default 1e-9), or `full` to disable the negative wall. Output includes exact rational endpoints and 12 decimal places rounded outward. Python 3 can run `heat_test.py ./heat` for independent exact checks. The pair count can range from 0 through one billion; the direct recurrence can be expensive for large inputs.
##### Heat equation
Let t be cards remaining and x current score. Let p_t(x) = 2^-t binom(t,(t+x)/2) and U_t(x) be the optimal expected final score from that state. The weighted score a_t(x)=p_t(x)U_t(x) obeys
a_t(x) = max(x p_t(x), (a_(t-1)(x-1)+a_(t-1)(x+1))/2).
Missing terms at the physical deck edge have weight zero. Finishing gives zero; therefore a_t is always nonnegative and negative x need only the averaging operation. Also a_t≤1: by symmetry and unimodality there are x+1 parity-compatible masses at least p_t(x) between -x and x when x≥0. Thus x p_t(x)≤1, and averaging preserves the inequality. At x≥sqrt(5t/2) use the same proven positive cutoff as fast.c. An artificial negative wall at -W commits to finishing for zero. The clipped game never exceeds the true game and still receives the optimal immediate payoff above the positive cutoff. The initial price changes by at most n·P(hit -W) ≤ n exp(-W²/(n+1/2)) for n cards of each color, by the bridge reflection bound in fast.c. An unclipped physical edge needs no wall charge.
##### Integer enclosure
In units of Q=2^62, round each heat average down via unsigned add and shift. The clipping is entirely independent of the error analysis. The mass array for exercise is another heat equation, kept only on its nonnegative half and computed in the same units. At the outer positive edge a high precision anchor is needed. Track this edge, which moves by exactly ±1 each time, in 2^-95 integer intervals, using p_t(y)=t p_(t-1)(x)/(t+y) for an upward step, and replacing +y by -y for a downward step. The center is maintained separately from p0(0)=1; even times copy their previous odd mass, odd t multiply by t/(t+1). Every 128 layers, reset the mass array using that center and p_t(x+2)/p_t(x)=(t-x)/(t+x+2). All anchor arithmetic uses outward 128-bit interval endpoints. Each averaging step loses less than one Q-unit; its children lie in the previous mass layer, with symmetry copying the center as required. Consequently the mass error in Q-units is at most the greatest anchor width since the most recent reset, plus the age of that reset. The code rounds that bound up by one additional unit.
The weighted value estimates never exceed their exact clipped-game counterparts. If the maximum weighted error at the previous layer is E, then an average has error at most E+1 and an exercise has error at most x times its mass error. Taking a maximum therefore yields weighted error at most T plus the greatest exercise-error bound observed up through T. The negative wall has zero error for the clipped game. If the wall budget is n 2^-b, add ceil(n·P_hi/2^b) weighted integer units, where P_hi ≥ Q p_T(0) is the outward-rounded central anchor. Return lower/Qp_high and upper/Qp_low, capped on the upper weighted numerator by the proven bound Q. If b≥120 the wall error is under one unit because n·P_hi ≤ 10^9·2Q < 2^120. All numbers used for interval endpoints are integers. Changing the decimal budget affects only the chosen wall and explicit allowance. The proof never assumes that binary floating point rounded the requested budget in a particular direction.
The negative half of the hot loop uses one addition and one right shift. There is one value pass rather than two directed-rounding passes. Work and memory are O(nW+n^(3/2)) and O(W+sqrt(n)), respectively; the mass reanchoring expense is confined to the positive half. Technical edge checks cover zero pairs, physical edges, parity changes, saturated small walls, no clipping, and 128-layer resets.
##### Endpoints and implementation limits
The decimal endpoints are rounded outward by integer division in units of 10^-12. The rational endpoints retain full precision. The truncation budget controls only the negative-wall charge; the reported interval includes fixed-point errors as well. For instance the interval for one million pairs with the default budget is [522.033532618285, 522.033532620055], with rational endpoints 1358260719377406619/2601864888956427 and 1358260719382008220/2601864888956426.
The implementation needs a C11 compiler with unsigned 128-bit integers (e.g. GCC or Clang). The positive budget is parsed as a double and decomposed with frexp to choose b without materializing a subnormal power of two. Payoffs, updates, bounds and reported endpoints use integer arithmetic throughout. Since n≤10^9, times and scores fit in signed 32 bits, products of a 2^95 anchor and a transition numerator fit in 128 bits, and adding two weighted values at scale 2^62 fits in 64 bits. The upper endpoint of every anchor is intersected with the known bound 1. The central mass is at least 1/(2n+1); at most n down-roundings, each smaller than 2^-95 and never amplified at the center, preserve a strictly positive denominator.
#### 2.6. Compressed return kernel and frontier bands
The entry point `./catalan PAIRS` returns a certified dollar interval. It uses binary64, directed rounding and unsigned 128-bit integers. Its input range is 0 to 100,000,000 pairs. Work still grows with deck size, so use the large-deck certificate for cent pricing. The two hexadecimal endpoints are exact binary floating-point values.
##### Compressing a first-return convolution
Let $p_t(x)=2^{-t}\binom{t}{(t+x)/2}$ and let $H_t(x)$ be this weight times the optimal final payoff at score $x$ with $t$ cards remaining. The continuation value in these units is the average of the two child entries. Finishing gives zero, so all negative states must continue. Write $d_r=H_{2r}(0)$.
From score $-1$ the first return to zero with $2i$ cards left contributes a Catalan factor. Normalizing each step by its fair-walk probability gives the exact identity
$$H_{2r-1}(-1)=\sum_{i=0}^{r-1}d_i g_{r-i},
\qquad g_m=\frac{C_{m-1}}{2\,4^{m-1}},
\quad C_k=\frac1{k+1}\binom{2k}k.$$
This is the weighted version of the first-return identity already verified in `Excursions.lean`. It is the only information the positive half needs from the negative half.
The solver represents $g_m$ by 208 positive exponential terms $\sum_j w_j q_j^{m-1}$. Each term needs just one stored number, updated as $s_j\gets q_js_j+d_{r-1}$. To choose candidate nodes, use the beta integral
$$g_m=\frac1\pi\int_0^1 x^{m-3/2}(1-x)^{1/2}\,dx.$$
Substitute $x=\exp(-\exp y)$ and apply the equally spaced trapezoidal rule with step 0.2 on $y=-36,-35.8,\ldots,5.4$. The parameters are performance choices.
Before using those nodes, the program **verifies the actual floating-point coefficients for every $m\le n$**. It bounds the exponential moments by directed multiplication and addition, and bounds the true moments independently by $g_1=1/2$ and $g_m=g_{m-1}(2m-3)/(2m)$. Even an inaccurate system exponential or square root could only worsen the certified error if it passed the positivity checks. Tiny terms are replaced by $0$ or $10^{-100}$ in the appropriate bound.
The reflection-principle bound from the expected running maximum gives $0\le d_i\le(1-p_{2i}(0))/2\le1/2$. Half the sum of the absolute moment errors is therefore a valid error allowance on the negative child, for every possible exact diagonal history. The states themselves are updated with one-sided interval arithmetic. Negating the lower endpoints allows a single upward-rounding mode during the entire Bellman pass.
##### Following the stopping frontier
Let $B_t$ be the first score of the correct parity where stopping is optimal. At $B_{t-1}+1$ both children stop, so the continuation payoff is at most the current score. Below $B_{t-1}-1$, the state obtained by removing a red card is strictly favorable, and restoring that red card preserves favorability. On each time layer smaller scores have more red and fewer black cards and preserve strict favorability. These are the classical monotonicity properties of the urn. [Boyce 1973](https://sites.math.rutgers.edu/~zeilberg/akherim/BoyceUrn.pdf "On a simple optimal stopping problem")
The result is $B_{t-1}-1\le B_t\le B_{t-1}+1$ (using $B_0=0$). The code keeps a **certified interval** for this frontier. It compares continuation and immediate exercise only inside the possible frontier interval. Overlapping numerical bounds keep both actions possible. A separate proven stopping bound $x\ge\sqrt{5t/2}$ caps the width of the positive layer. All states strictly below the possible frontier need only the average of two values. GCC vectorizes these loops on the benchmark machine. The probability at the edge and the normalization at zero use outward 95-bit fixed-point arithmetic.
The work is $O(n^{3/2}+208n)$ and the working memory is $O(\sqrt n+208)$, including certification of the exponential approximation. The method returns the optimal price to its reported numerical precision. The exact integer numerator still calls for the GMP solver.
#### 2.7. A direct cent check for the historic computation
Let $N=267{,}574{,}000$ be the total number of cards, half of each color.
The article's body reports $6,038.22, while its summary says $6,038.32.
This certificate encloses the discrete optimum using ordinary desktop arithmetic.
It gives **[$6,038.215222, $6,038.220246]** in 64.38 seconds on one AMD EPYC 9V74 core (GCC 14.2), so the result rounds to **$6,038.22**.
[Gwern et al. 2022](https://gwern.net/problem-14#blocks-skipping "Problem 14 Dynamic Programming Solutions")
##### A comparison martingale
Let $t$ be the number of remaining draws and $x$ the current score.
Write $Z_t$ for an independent, unrestricted symmetric random walk starting at zero and put
$$
p_t(x)=2^{-t}\binom{t}{(t+x)/2},\quad
F_t(x)=\Pr(Z_tw)\le 2\exp(-w^2/(2T))<4\cdot10^{-14}$, obtained from $\cosh s\le e^{s^2/2}$.
The upper excess is at most $T$, the maximum feasible eventual score.
Only the negative tail matters for the lower excess, and there $Q_T(x)\le Q_T(0)\le T$.
Indeed, in $F_t(x)/p_t(x)=1/2+\sum_{j\ge1}p_t(x-2j)/p_t(x)$ each mass ratio increases with $x$, by the adjacent binomial-coefficient ratios.
The bound at zero follows from $p_T(0)\ge1/(T+1)$.
Both cutoff tail allowances are smaller than one microdollar before the density adjustment.
##### One billion cards
For $N=1{,}000{,}000{,}000$, the lower bound also uses the fact that the cutoff policy receives its terminal correction only on paths that survive to $T$.
The program checks that $B_t\le K=10{,}000$ for $T\le t\le U=140{,}000{,}000$ by bounding the increasing positive root at $U$.
Take any cutoff score $xh)$.
The remaining transition to zero from time $U$ to $N$ has mass at most $p_{N-U}(0)$.
Consequently each survivor has weight at most $p_T(x)\Pr(-h\le Z_d
#### 2.8. An independent fixed absolute-error comparison
The independent fixed-error comparison uses a 262,144-card cutoff and a minimum gap of 1/500 dollar at 3,600 cards. Appendix 2.10 derives the common binomial integral and proves the shrinking bound. Source worksheet: `derivations/2.8-an-independent-fixed-absolute-error-comparison.md`.
#### 2.9. Survival corrections from a single layer
Let $N$ denote the total number of cards. This certificate builds one lower payoff layer at $T=262{,}144$ remaining cards and bounds how often an optimal-stopping comparison can reach it. It yields the following *absolute* deductions from $Q_N(0)$, uniformly for every even $N$ from the indicated threshold onward. Here $Q_t(x)=c_*F_t(x)/p_t(x)$, $p_t$ is the fair-walk mass and $F_t(x)=\Pr(Z_t0$, Wallis gives
$$
\frac{2}{\pi(d+1)}\le p_d(0)^2\le\frac{2}{\pi d}.
$$
The verifier substitutes $3.141592<\pi<3.141593$, then uses integer square roots and the exact adjacent-binomial ratios, rounding outwards in units of $2^{-50}$. Each stored lower prefix is the sum of *lower masses* and each upper prefix sums *upper masses*. Subtracting entries of the same prefix table therefore encloses an interval mass without subtracting independently rounded approximations to cumulative probabilities. The other interval operations use checked 128-bit integers.
At $T$, the evaluator first quantizes $L_T$ downward. It uses $c_*<0.589056438025$, which follows by substitution from $\alpha>0.83992367569237$. All charges include the $-x/T$ correction with the appropriate sign. The negative tail $x<-w$, $w\ge8\sqrt T$, has fair-walk probability at most $e^{-32}$; there $Q_T(x)-x/T\le T+1$, using the increasing ratio $F_T(x)/p_T(x)$ and $p_T(0)\ge1/(T+1)$. The unrestricted density factor is below two. This costs less than the one extra microdollar included in each printed certificate.
##### Reproducing the certificate
From this directory run:
~~~sh
cc -std=gnu11 -O3 -march=native -frounding-math -ffp-contract=off verify_multislab.c -lm -o verify_multislab
./verify_multislab
python3 test_multislab.py
~~~
The verifier uses the sibling `record.c` for the directed terminal layer and checked arithmetic. A single process rebuilt all three universal deductions in 0.53 seconds on an AMD EPYC 9V74. That timing includes generating the common Bellman layer, all binomial masses, and all survival weights. The test independently checks 719 exact binomial interval masses and 342 survivor densities against counts of complete walks at multiple horizons. It uses eight intervals to force grouping on small decks. The full certificate uses 480.
#### 2.10. Proof of the uniform fifth-root price enclosure
Use $N$ for the **total** even number of cards and $V_{N/2}$ for the exact price.
With the Brownian stopping constant $\alpha$ and $c_*=2(1-\alpha^2)$, for every even $N\ge65536$,
$$
c_*\sqrt{\pi N/8}-\frac{0.137}{(N+1)^{1/5}}
\ \leq\ V_{N/2}\ \leq\ c_*\sqrt{\pi(N+1)/8}.
$$
The lower endpoint comes from an exercise policy and an exact harmonic comparison. The upper endpoint comes from a separate supermartingale. Both are proved below. The comparison uses a fixed finite table once. Its two endpoints can subsequently be evaluated for any $N$ with scalar roots, using a correspondingly accurate enclosure of $\alpha$ for very large $N$.
##### The comparison function
Let $p=2/5$, $m=(t+x)/2$, $b_t(x)=2^{-t}\binom t m$, $F_t(x)=\Pr(Z_t0$, giving $H_t(B_t)\le B_t$.
##### Positivity on the exercise boundary
On writing $z=e^{2i\theta}$ in Fourier coefficient extraction and taking real parts, one obtains
$$
b_t(x) R_t(x)=\frac2\pi\int_0^{\pi/2}(\sin\theta)^p(\cos\theta)^{t-p}\cos(x\theta+p\pi/2)\,d\theta .
$$
The sign at the physical upper edge does not enter this identity for the permitted lower policy. The fractional powers are the branches positive at the origin of the generating series. The boundary integral follows by taking the radius up to one; the factors are bounded on the closed disk for these positive exponents. Write $a=\sqrt{t-p}$ and $y=B_t/a$. For $t\ge16384$, $0< y <0.85$ by $B_t\le0.84\sqrt{t+1}+1$.
After the change of variables $u=a\theta$ and omission of a positive constant, the integral has weight $(a\sin(u/a))^p(\cos(u/a))^{a^2}$. Compare it to the Gaussian weight $u^p e^{-u^2/2}$ on $[0,\infty)$, extending the former by zero. Write $M_j=\int_0^\infty u^{p+j}e^{-u^2/2}du$. The trigonometric weight is everywhere bounded above by the Gaussian. For $u/a\le1/2$, with $v=u/a$, we have $(\sin v/v)^p\ge 1-v^2/6$ and $\log\cos v\ge -v^2/2-v^4/3$. The latter bound follows by integrating $\tan v-v\le4v^3/3$ (use $\tan v\le2v$ here). Thus the relative pointwise loss is bounded by $u^2/(6a^2)+u^4/(3a^2)$. On $u>a/2$ bound the relative loss by $1\le4u^2/a^2$. Integrating and using $M_{j+2}=(p+j+1)M_j$ shows the total absolute error, even after multiplying by the cosine of the phase, is less than $7.5M_0/a^2$.
For the Gaussian integral itself, expand $\cos(yu+p\pi/2)$ as a difference of products. Use the Maclaurin polynomial through degree six as a global lower bound for $\cos v$, and through degree five as a global upper bound for $\sin v$, for every $v\ge0$ (repeated integration of $\cos v\le1$ proves the signed remainders). Dividing by $M_0$ yields the lower bound $C(y)\cos(p\pi/2)-(M_1/M_0)S(y)\sin(p\pi/2)$, with
$$
\begin{aligned}
C(y)&=1-(p+1)y^2/2+(p+1)(p+3)y^4/24-(p+1)(p+3)(p+5)y^6/720,\\
S(y)&=y-(p+2)y^3/6+(p+2)(p+4)y^5/120.
\end{aligned}
$$
Differentiating shows $C$ decreases and $S$ increases on $[0,0.85]$. Substitution gives $C(0.85)>0.584$ and $S(0.85)<0.644$. Cauchy–Schwarz gives $M_1/M_0\le\sqrt{1+p}<1.184$. Since $\cos(\pi/5)>0.8$, $\sin(\pi/5)<0.59$, the Gaussian integral exceeds $0.017M_0$. The trigonometric error above is smaller, so $R_t(B_t)>0$ as required.
##### Closing the argument at a single finite cutoff
At $x=0$ the Fourier integral is a beta integral. Using $B(v,w+1)/B(v,w)=w/(v+w)$ for both the fractional and ordinary mass gives
$$
R_{t+2}(0)/R_t(0)=1-p/(t+1)\quad(t\text{ even}),\qquad
R_N(0)\le R_T(0)\left(\frac{T+1}{N+1}\right)^{1/5}.
$$
For the inequality, take logarithms, apply $\log(1-z)\le-z$ and bound $\sum_{j=T/2}^{N/2-1}(2j+1)^{-1}$ below by its integral.
For $T=65536$, the cutoff is $B_T=216$. At every surviving feasible score $x\le214$, the integer Bellman calculation in `shrinking_layer.c` and the rational check in `shrinking_check.py` verify $H_T(x)\le V(T,x)$ and $R_T(x)>0$. They cover every negative physical state and incur no omitted-tail debit. After the cutoff, the lower Bellman table forces exercise at scores of at least 512. The integer kernel rounds every continuation down in units of $2^{-30}$. Its numerator is at most $2^{62}$; it multiplies by $\lfloor(2^{64}-1)/t\rfloor$ using a 128-bit product and takes the high 64 bits. This yields a valid lower bound even when an extra unit is lost. A zero-valued action is available by playing to the terminal state. For reproduction, the recurrence in $m$ follows by logarithmically differentiating $(1-z)^p(1+z)^{T-p}$:
$$
R_0=1,\quad d_0=0,\qquad d_{m+1}=\frac{md_m+2pR_m}{T-m},\quad R_{m+1}=R_m-d_{m+1},
$$
where here $R_m=R_T(2m-T)$ and $d_m=R_{m-1}-R_m$. Also $F/b$ starts at $1/2$ and updates by $h_{m+1}=1/2+(m+1)(h_m+1/2)/(T-m)$. The code rounds outwards with integer endpoints in units of $2^{-150}$, uses a rational upper bound on $c_*$ for the cutoff comparison, and verifies that the required multiplier of $R_T$ is $<0.197510<1/5$. Finally $(1/5) R_T(0) (T+1)^{1/5}<0.137$.
At exercise and at cutoff the attainable payoff bounds $H$ from above. Optional stopping under the stated policy gives $V_{N/2}\ge H_N(0)=c_*/(2 b_N(0))-R_N(0)/5$. The central binomial bound $b_N(0)\le\sqrt{2/(\pi N)}$ proves the assertion. The nonzero coefficients of the cubic and fractional corrections are choices verified by the inequalities above.
##### The contact estimate
Set $c_*=2(1-\alpha^2)$, $c=0.5890564381/3$. Thus this last part contributes at most $4(s+1)e^{-s^2/4}$ after multiplying by $s(1-\alpha^2)(s+y)$. The two tails together are below $0.001$. Consequently $s(Q^c_t(B_t)-B_t)\le s(Q^{c_*}_t(B_t)-B_t)<7/128+0.744+0.001<0.81$. Meanwhile $s B_t/t\ge\alpha-1/128>0.81$.
##### The upper endpoint
Write $N=2n$, let $t$ be the number of cards remaining and $x$ the current score. Use $p=p_t(x)=\Pr(Z_t=x)$ for an unconditioned symmetric walk, $F=\Pr(Z_t0.58905$ used below are checked with rational arithmetic in the accompanying Python file.
Thus $H$ stays nonnegative everywhere, including off the physical deck.
Dividing by $p$ makes $M$ a supermartingale under the deck bridge, since its move probability to $y=x\pm1$ is $p_{t-1}(y)/(2p_t(x))$. At an impossible child one discards a nonnegative heat numerator.
We show $M_t(x)\ge x$ when $t\ge 3600$.
For the unperturbed term set
$$
s=\sqrt{t+1},\quad y=(x-1)/s,\quad
A(y)=\int_0^\infty e^{yv-v^2/2}\,dv,\qquad f(y)=(1-\alpha^2)A(y).
$$
The beta integral for the binomial CDF gives, for $k=(t+x)/2>0$,
$$
F/p=\tfrac12+k\int_0^1(1-u)^{t-k}(1+u)^{k-1}du
=\tfrac12+k\int_0^\infty e^{(x-1)v}\operatorname{sech}^{t+1}(v)\,dv.
$$
The substitutions are the usual beta tail starting at $1/2$, then $u=\tanh v$.
Since $\log\cosh v\le v^2/2$, $2k=s(s+y)$ and $A'=1+yA$, we obtain
$$
cF/p-x\ \ge\ s g(y)+g'(y),\qquad g(y)=f(y)-y .
$$
The defining equation for $\alpha$ is $f(\alpha)=\alpha$, and it gives $f'(\alpha)=1$.
Also $f''(\alpha)=2\alpha$ and $f'',f'''>0$ by the integral.
For $y\ge\alpha$ both $g$ and $g'$ are nonnegative.
For $h=\alpha-y>0$, $g(y)=\int_y^\alpha (v-y)f''(v)\,dv\ge h[-g'(y)]/2$, because $f''$ increases, and $-g'(y)\le 2\alpha h$.
Consequently $sg+g'\ge0$ for $h\ge2/s$.
In the remaining strip $00$.
In the exceptional strip it exceeds $\alpha/s$ since $0.1\alpha s>4.96$.
For $x\le0$, use $H\ge0$.
For $1\le x\le3$ use $F\ge1/2$ and $p\le1/\sqrt t$ (the central binomial bound), whereas $D\ge-.55(t+3)/(t-1)-.56/(t+2)>-1$.
This proves the obstacle inequality in every state for every $t\ge3600$.
At $T=3600$ we additionally have the uniform gap $M_T(x)-V(T,x)>1/500$ at all 3,601 states, where $V(t,x)$ denotes the optimal **final** score from that state.
The accompanying `shrinking_check.py` checks this finite assertion by unbounded integer arithmetic.
It starts with the ordinary Bellman recurrence after multiplication by the count of deck orders. The two weighted child values add, the stop value is $x\binom{t}{k}$, and the terminal value is zero.
The cutoff comparison uses the lower rational coefficient $c_0=0.58905$ in place of $c$.
It obtains the needed enclosure for $\alpha$ from $A'=1+yA$ and the defining equation. The coefficients satisfy $a_0=\sqrt{\pi/2},a_1=1,a_j=a_{j-2}/j$. For $0
#### 3.1. Certified coefficients at arbitrarily large horizons
At time t let s=√(t+1) and η=1/256. Pick any rational C/2^k whose square root β obeys 0≤(α−β)s≤η. Use the nearest feasible-parity point to βs, breaking ties upward. For a positive feasible cash balance x, stop precisely when
2^k (x+1)^2 > C(t+1).
Equality means continue. Consecutive target positions differ by at most α/(√(t+1)+√t)+η<1 for t≥65536. Their rounded positions differ by less than three, hence by exactly one as their parities differ. This argument allows a different approximation at every time, so no initial deck count is needed. At T=65536 the rational inequalities with 0.83992367569237<α<0.83992367569238 put even B_T at 216. The low-time rule 79T≤112x²+109x+14 first holds at x=216 since 5,152,492<5,177,344≤5,249,030. Surviving even scores satisfy x≤214.
For every unsigned 64-bit horizon use C=13013657395120439157 and k=64. It is the exact floor of 2^64 times (83992367569237 / 10^14)^2. The downward displacement is at most 1/256 on that entire domain. The code, integer coefficient certificate and all-argument no-wrap bounds are in cent/native.
For arbitrary integers, cent/native/play.py uses k=ceil(bitlength(t+1)/2)+10 when t exceeds the uint64 range. It encloses α in an interval of width at most 2^(−k), takes the lower endpoint l and returns C=floor(2^k l²). Since l>.8, 0≤l−√(C/2^k)≤2^(-k)/l<1.25·2^(-k). The total error is <2.25·2^(-k), covering η since 2^k≥1024s. Values are cached by requested precision.
The coefficient generator uses rational bounds on π via the alternating Machin arctangent series. The coefficients of A satisfy a₀=√(π/2), a₁=1, and aⱼ=aⱼ₋₂/j. At a precision of P bits, directed integer arithmetic bounds truncation and rounding; omitted coefficients after two consecutive upper bounds of 2^(-P) contribute less than 7·2^(-P) for y≤.85. Ambiguity at a bisection midpoint is handled by a neighborhood of radius 2 max(|F_lo|,|F_hi|), using F=(1−y²)A−y and −F′=y(1+y²)A+y²>1/2. If a neighborhood fails to tighten the bracket at a given precision the routine widens its working precision; an exact dyadic zero causes no infinite sign test. Truncation and fixed-point errors tend uniformly to zero as P increases: each arctangent uses O(P) terms at error ≤2^(−P) each, A₀ inherits O(P2^(−P)) error, coefficient errors contract under /j, and Horner evaluation accumulates at most a geometric factor 1/(1−.85).
##### Contact with the proved lower comparison
Set y=(B_t−1)/s and h=α−y. For t≥65536, 0≤sh≤2+η. In the existing exercise contact proof the smooth-fit contribution equals ∫₀ʰ(sv−1)f″(y+v)dv, with f=(1−α²)A. Up to min(h,2/s) its original bound 7/s² holds verbatim; the constant f″(y) part integrates nonpositively and f‴≤f‴(α)<3.5. If h>2/s, the remaining interval contributes at most (η/s)(1+η)2α<.0066/s because f″≤f″(α)=2α. The Laplace comparison depends only on y≤α and still applies. Thus s(Q_t(B_t)−B_t)<.8166, whereas s B_t/t ≥α−(1+η)/s>.83 for s≥256. The cubic correction remains negative. Positivity of the fractional correction still holds from B_t≤.84s+1. Consequently H_t(B_t)≤B_t with the identical coefficient, and the finite cutoff verification is unchanged.
#### 3.2. Attainment by the actual policy at the 65,536-card switch
Use \(t\) for the number of remaining cards, \(x\) for the current balance, and \(N\) for the initial card count; \(N\) is even.
For \(t>T=65536\) stop when \(x\) reaches the parity-compatible integer closest to \(\alpha\sqrt{t+1}\), ties upward.
For \(t\le T\) stop when \(x>0\) and \(79t\le112x^2+109x+14\).
Otherwise draw.
The prior comparison in `shrinking.md` uses a function \(H_t\) harmonic at all states the upper-time rule continues through.
At the upper-time exercise boundary its value is no greater than the cash taken.
It has the initial value \(Q_N(0)-R_N(0)/5\), while \(Q_N(0)\) bounds the optimal game price above and \(R_N(0)/5<0.137/(N+1)^{1/5}\).
Only its comparison at the switch needs replacing.
At \(T\), the large-time boundary is 216 and the 79 rule takes 216.
Every surviving state therefore has even \(x\le214\).
The program `cutoff79.c` checks at each of the 32,876 such states that the 79 rule itself attains at least \(H_T(x)\).
In units of \(2^{-32}\) dollars, the recurrence takes the immediately available score at its prescribed stopping frontier and otherwise rounds the conditional weighted average of its children downward.
At the artificial negative wall it uses zero; this lower bound applies even to a fixed policy, since this policy cashes out only at a positive balance and completing the deck gives zero.
Beyond the wall the same lower bound suffices.
The sum in the recurrence lies below \(2^{57}+1\); no floating-point operations are used.
The comparison of the lower payoff row to \(H_T\) uses the fractional coefficient and mid-CDF recurrences of `shrinking.md`, with outward integer bounds in units of \(2^{-44}\).
The verified multiplier for the fractional correction is at most \(197356261/10^9<1/5\).
Optional stopping now gives the regret bound \(0.137/(N+1)^{1/5}\) for this explicit hybrid policy for every even \(N\ge T\).
It is below one cent for even \(N\ge482618\), since \((137/10)^5=482617.24457\).
The analytic comparison starts at 482,618 cards, so the last even size requiring the finite check is 482,616. The released finite sweep includes 482,618 as an overlapping check.
```sh
cc -O3 -std=c11 cutoff79.c -o cutoff79
./cutoff79
```
Expected output:
```
79 rule: all 32876 cutoff survivors passed; multiplier <= 197356261/10^9
```
#### 3.3. Monotone exact-product threshold
Section 2 gives both the exact central product and its threshold. This note records the rounding directions and the unreduced endpoint fractions. Source worksheet: `derivations/3.3-monotone-exact-product-threshold.md`.
#### 3.4. Global finite sweep through 482,618 cards
For **every even deck size from 2 through 482,618 cards**, the candidate policy's expected dollar regret is at most **2,075,264 / 4,294,967,296 = 0.0004831850528717041015625**. This is the largest computed *upper bound* over these 241,309 roots. It occurred at 482,618 cards. A zero-card deck has zero regret.
For positive score x and t cards remaining, stop when 79t ≤ 112x²+109x+14 if t ≤ 65,536. For larger t stop when x reaches the integer of parity t nearest to α√(t+1), choosing the larger integer on ties. The earlier enclosure 0.83992367569237 < α < 0.83992367569238 suffices. The checker verifies at each of the 417,082 relevant times that the whole enclosure lies strictly between consecutive integer milestones after multiplication by √(t+1). It also checks the same integer part for √(β(t+1)), where β=13013657395120439157/2⁶⁴ is the native player's squared coefficient. The integer part determines the nearest same-parity score.
##### Reproduction
~~~bash
set -e
cc -O3 -march=native -std=gnu11 certify.c -o certify
./certify
python3 test.py
~~~
The full scan took **5.97 seconds** on one AMD EPYC 9V74 core with GCC 14.2. The scan requires GNU C or another C implementation with unsigned 128-bit integers. No floating-point operation enters the certificate. A second argument to `./certify 482618 rows.tsv` records the deck size, lower integer for the optimum, lower integer for the rule, and upper regret numerator for every even deck. The tests independently compare all 80 starting values through 160 cards to exact rational arithmetic and match all post-switch decisions against integer square roots.
##### Why the computation proves a regret bound
One backward pass visits all remaining times t. Table rows depend only on t and current score x, so the entry at x=0 on every even row solves a separate starting deck. At t=0 the value is zero. Inside the artificial walls, the unrestricted optimal Bellman entry is the maximum of cash x, zero obtainable at expiry, and the weighted continuation. The fixed-rule entry takes cash exactly on the stated boundary and otherwise continues. The next score is x+1 with probability (t−x)/(2t), x−1 with probability (t+x)/(2t).
At either wall |x|=w=3072, the clipped game gives cash on the positive side and zero on the negative side. Its fixed-rule value bounds the real policy from below because the policy already exercises on the positive side, and the real policy's payoff is nonnegative on the negative side. For the optimum, couple decisions until a wall is reached. The change in total payoff is at most n on a deck of 2n cards. Reflection bounds the probability of reaching either wall by twice binom(2n,n+w)/binom(2n,n), taking the numerator zero for w>n. Write the one-sided ratio as a product of (1−z)/(1+z) for z=(j+1/2)/(n+1/2), j=0,…,w−1. Bounding each factor by exp(−2z) gives a ratio at most exp(−w²/(n+1/2)). For the supported maximum 500,000 cards, w²/(n+1/2)>50(7/10) and exp(7/10)>2. Thus the two walls cost the optimum less than 2n/2⁵⁰ dollars. The comparison at a root t=2n adds this amount, rounded up to a whole fixed-point unit.
Each array stores dollars multiplied by S=2³² and rounded downward. For integer weighted sum v and denominator d=2t, the code computes floor(v floor(2⁶⁴/d)/2⁶⁴). Since v<2⁶⁴, this underestimates the exact mean v/d by less than two units. All entries are at most wS, and the weighted sum is at most 2twS<2⁶⁴. By induction the approximation error at any state is at most 2t units. Weighted averages and maxima preserve lower bounds and are nonexpansive. For unscaled lower integers A and B printed for the clipped optimum and fixed policy, respectively, the unconditional regret on this root is at most (A−B+2t+ceil(tS/2⁵⁰))/S. A denominator-free integer check tests this value against 1/100 on every deck through the selected horizon.
#### 3.5. Finite regret, constructive transport and scalar formalization
The finite-table semantics, constructive transport and integer debit checks are documented here. Section 7 gives the full-history composition and states its outstanding input obligations. Source worksheet: `derivations/3.5-finite-regret-constructive-transport-and-scalar-formalization.md`.
### Appendix 4. Compact policies and the economics of information
#### 4.1. Alternative 52-card rules and outcome risk under ties
Section 1 compares all three mnemonic rules and gives both optimal tie conventions. This workbook also includes the resulting payout distributions. Source worksheet: `derivations/4.1-alternative-52-card-rules-and-outcome-risk-under-ties.md`.
#### 4.2. Pathwise equivalence of preview and recall, and positional signals
A player who can see the next two cards and a player who can backdate retirement by up to two draws obtain the same opportunities on every shuffle. On a 52-card deck either privilege is worth about $0.75715 above the usual game. Full foresight adds about $1.41619.
The contract matters. The second player commits to ending the game, and may then select the current score or any within the last two draws. The cards keep their order, drawing extra cards has no separate cost, and the payoff is the score at the selected time.
##### Preview and recall
If a player would stop at draw j with k-card foresight, an ordinary observer can recognize that decision by draw min(N,j+k) and retire at the earlier score. Conversely, if a recall player commits at draw s and chooses draw j, the decision used observations through s. Since s ≤ j+k, the preview player can recognize that choice in time to stop at j. At the horizon both players have seen the entire sequence. The stock Lean 4.19.0 file proves that both rules can select exactly the same time as a function of the realized path, for arbitrary observations and any fixed finite horizon. Run `lean PreviewRecall.lean`. A continuous-time financial precedent is [Ernst et al 2017](https://www.sciencedirect.com/science/article/pii/S0304414917300923 "The value of foresight").
##### What a single piece of information buys
On a 52-card deck, revealing the color of any one of the first four cards before play is worth exactly zero. Opening the same way is optimal until the information has arrived through normal play. Revealing the last card's color before play is worth $0.1148703917 and is best among the 52 fixed positions. The fifteenth card's color is worth $0.04795453, the twenty-sixth's $0.03614676. Each fixed-position signal contains exactly one bit under the uniform shuffle.
A voucher to see the next card once, exercised at a moment of the player's choosing, is worth $0.284679905. If the privilege renews at every draw it is worth $0.452351826. One well-timed peek therefore captures about 63% of the value of continuous one-card foresight. To price the voucher, compare three actions at every state: stop, draw while keeping the voucher, or spend it and choose whether to draw after seeing the next color.
The positional signals and voucher are evaluated by exact integer dynamic programs. The small-deck results were also checked against enumerating all color histories through five pairs. The arithmetic experiment is Python. The policy equivalence is proved in Lean.
Run `python3 position_peek.py 26` to reproduce `standard-deck-signals.csv`. Run `python3 -c 'from position_peek import one_peek_on_demand; print(one_peek_on_demand(26))'` for the exact 52-card voucher game value before subtracting the ordinary price.
#### 4.3. Quadratic grammar, complete denominator search and strict decisions
For a standard 52-card deck, let $x$ be your current profit and $t$ the number of cards left. **Cash out if $x>0$ and $t+8\le(x+2)^2$.** For example, with a profit of \$3, cash out with 17 cards left and draw with 19 left. This rule makes an optimal decision in every state through 31 pairs, or 62 cards. Its first mistake comes with 26 red and 32 black cards left, when it draws instead of cashing out \$6.
A single quadratic works through **8,242 pairs**, or 16,484 cards. Cash out if
$$x>0\quad\text{and}\quad 79t\le112x^2+109x+14.$$
At **8,243 pairs** every quadratic with real coefficients loses some expected return, even if one chooses the coefficients specifically for that deck. The displayed policy’s first loss is between $1.24300479\times10^{-38}$ and $1.24300497\times10^{-38}$ dollars, because the single bad decision requires 107 consecutive opening reds. For every balanced deck through 65,535 pairs, the expected loss stays below \$0.0000001232.
##### Optimal rules by denominator
The grammar is “cash out iff $x>0$ and $dt\le ax^2+bx+c$,” where $d$ is a positive integer and $a,b,c$ are arbitrary integers. The table lists every denominator at which the maximum exact range increases. At each row the listed triples are the complete set at its smallest denominator. Every integer between the indicated values of $c$ works. Exactness in this table means choosing an optimal action at every remaining-count state.
| Smallest denominator $d$ | $a$ | $b$ | $c$ | Last perfect deck, pairs | First wrong remaining hand, red / black |
|---:|---:|---:|---:|---:|---:|
| 1 | 1 | 4 | −4 to −3 | 31 | 26 / 32 |
| 2 | 3 | 1 | 4 to 5 | 54 | 47 / 55 |
| 5 | 7 | 7 | 3 to 4 | 67 | 59 / 68 |
| 7 | 10 | 8 | 7 to 9 | 337 | 317 / 338 |
| 19 | 27 | 24 | 16 to 17 | 859 | 826 / 860 |
| 43 | 61 | 58 | 8 to 9 | 1,361 | 1,319 / 1,362 |
| 67 | 95 | 92 | 8 to 13 | 3,261 | 3,195 / 3,262 |
| 79 | 112 | 109 | 14 to 15 | 8,242 | 8,136 / 8,243 |
The familiar diffusion boundary $x=\alpha\sqrt t$ suggests a quadratic coefficient $1/\alpha^2=1.4174911413\ldots$, where $\alpha=0.8399236757\ldots$. The finite-deck optimum above has $112/79=1.4177215190\ldots$, 0.0163% higher. The linear and constant terms enter the exact discrete comparisons. [Brownian comparison in this project](#proof-shrinking-md)
##### Four states exclude every real quadratic
Write $q(x)=Ax^2+Bx+C$. Strict optimal decisions require the following inequalities.
| Remaining red | Remaining black | $x$ | $t$ | Required action | Constraint |
|---:|---:|---:|---:|---|---|
| 7 | 10 | 3 | 17 | Cash out | $q(3)\ge17$ |
| 826 | 860 | 34 | 1,686 | Draw | $q(34)<1686$ |
| 4,782 | 4,864 | 82 | 9,646 | Cash out | $q(82)\ge9646$ |
| 8,136 | 8,243 | 107 | 16,379 | Draw | $q(107)<16379$ |
For every quadratic,
$$-10950q(3)+25675q(34)-29419q(82)+14694q(107)=0.$$
Substitution of the four constraints makes the left side less than $-748$. The same weighted inequalities with weak bounds would still give a contradiction.
Each state is reachable with positive probability under any initially optimal policy from any balanced deck of at least 8,243 pairs. First draw black–red pairs until the target number of black cards remains. At every prefix, the score is zero or negative and at least one black card remains. Drawing to the first positive score or to exhaustion has positive expectation, since drawing all remaining reds first reaches a positive score. Thus each prefix strictly favors drawing. Now draw the specified 3, 34, 82, or 107 reds in succession. The verifier certifies strict continuation at every prefix up to the target state. Hence an initial optimal policy must also make each of the four decisions.
With 8,243 pairs the 79-rule misses only the last state. The probability of its all-red approach is $\binom{8243}{107}/\binom{16486}{107}\simeq4.35939\times10^{-33}$. Conditional on arrival, drawing improves the expected payoff by between \$0.00000285132818 and \$0.00000285132859. Multiplying gives the opening loss above.
##### Held-out decks
The table bounds the expected dollar loss of the 79-rule relative to optimal play. The fit used decks of at most 8,243 pairs.
| Starting pairs | Lower loss | Upper loss |
|---:|---:|---:|
| 10,000 | $1.5339\times10^{-9}$ | $1.6338\times10^{-9}$ |
| 16,000 | $6.8795\times10^{-9}$ | $7.0394\times10^{-9}$ |
| 32,000 | $3.9551\times10^{-8}$ | $3.9872\times10^{-8}$ |
| 65,535 | $1.2252\times10^{-7}$ | $1.2319\times10^{-7}$ |
The simultaneous upper bound over all 65,535 starting sizes is exactly $34673417/2^{48}$ as an outward-rounded certificate.
##### Verification
For $r$ red and $b$ black remaining, $t=r+b$ and $x=b-r$. The value of drawing is $D=(rV(r-1,b)+bV(r,b-1))/t$. Optimal play takes $\max(x,D)$. To verify one policy, replace the maximum by its selected action. Both values are zero at exhaustion. A red-only hand has value zero and a black-only hand cashes out for $b$.
`verify.cpp` rounds every conditional expectation outward to multiples of $2^{-48}$. It compares the integer numerator bounds to $t2^{48}x$ before division. For $x\le0$, every rule draws and exhaustion guarantees at least zero. Induction under the Bellman recurrence proves the enclosures. With $n\le65535$, the exact value is at most $n$, and up to $2n$ rounding units suffice for accumulated error. Hence $n2^{48}+2n<2^{64}$, and each weighted sum, including the upward rounding increment, fits comfortably in 128 bits. Stopping comparisons use signed 64-bit expressions for the quadratic. The regret run brackets both the played policy and the optimum independently, and checks every balanced initial hand as it goes.
`search.py` uses exact rational interpolation and integer inequalities. At each profit $x\le128$, the verifier records the largest mandatory stopping time $L_x$ and smallest mandatory drawing time $U_x$. It checks every intervening state so that the constraints can be truncated to each candidate starting size. Whenever both limits exist, $L_x\le q(x) "$work_dir/witnesses.csv"
python3 further/rules/search.py "$work_dir/witnesses.csv"
python3 further/rules/test.py "$work_dir/verify"
"$work_dir/verify" regret 65535
lean -o "$work_dir/Problem14.olean" Problem14.lean
LEAN_PATH="$work_dir" lean further/rules/SquareRule.lean
```
`QuadraticReal.lean` imports mathlib v4.19.0. Run `lake env lean /absolute/path/to/QuadraticReal.lean` from that mathlib checkout.
#### 4.4. Strategic bits, exactly fair signals and fixed positions
A uniformly shuffled deck has $n$ red and $n$ black cards. Each red adds one dollar and each black subtracts one. The player may stop at any prefix, including the starting and terminal zero. An adviser sees the entire shuffle and sends one of $M$ messages before the first card. Both parties know the encoding and play to maximize expected payout.
With 26 pairs, one optimally designed bit raises the expected payout from **$2.624475549 to $3.236409379**, a gain of **$0.611933830**. This bit can be exactly fair. It earns 5.33 times the premium for learning the last card’s color and captures 43.21% of the value of complete foresight.
| Bits | Effective messages | Optimal expected dollars | Dollars short of full foresight |
|---:|---:|---:|---:|
| 0 | 1 | 2.624475549 | 1.416189226 |
| 1 | 2 | 3.236409379 | 0.804255396 |
| 2 | 4 | 3.690630982 | 0.350033793 |
| 3 | 8 | 3.981263639 | 0.059401135 |
| 4 | 16 | 4.040655522 | 0.000009253 |
| 5 | 26 | 4.040664775 | 0 |
The exact one-bit value is $14459417937065/4467734531064$ dollars. The exact premium is $21676380499927/35422752353436$. [Exact fractions for every budget from 1 through 26 messages](#src-further-signals-messages52-csv)
##### The optimal question
**“Should I take the first nomination or wait for the second?”** The nominations are online stopping rules. Their thresholds depend only on the remaining counts, available nominations, and best previous nomination. The adviser simulates the rules on the known shuffle and announces the more valuable nomination. The player can then stop at the selected nomination without looking ahead.
To prove optimality, fix any signal and its $M$ contingent stopping policies. Simulate all $M$ policies on a single deck. The highest payout among them bounds the payout from the signal on that deck. Conversely, given any $M$ contingent policies, an adviser can announce the index of the highest payout. The optimum over all signals thus equals the optimum over all $M$-policy lists of the expected maximum.
Equivalently, a player may nominate up to $M$ stopping times and receive the largest nominated payoff. Simulated policies yield such nominations, and an adaptive nomination strategy can be implemented by $M$ separate online policies. Policy $j$ internally simulates the common strategy and stops at its $j$-th nomination, or at exhaustion if that nomination never comes. The order statistics of finitely many stopping times are stopping times. Multiple nominations at one time provide the same payout. A player may ignore nonpositive payouts because exhaustion returns zero. [Lean proof of the encoder and nomination equivalence](#src-further-signals-nominations-lean)
For $r,b$ remaining cards let $s=b-r$, $D=\binom{r+b}{r}$, and let $U(q,h,r,b)$ be the optimal payout total over the $D$ equally likely suffixes, with $q$ nominations available and incumbent $h$. With no nominations, $U=hD$. The same formula holds whenever $h\ge b$, since the greatest possible future score is $b$. At all other states let
$$
C=U(q,h,r-1,b)+U(q,h,r,b-1),
$$
omitting missing children. If $s\le h$, the value is $C$. Otherwise it is
$$
U(q,h,r,b)=\max\{C,U(q-1,s,r,b)\}.
$$
A nomination at the current score leads to the second term. The answer for $M$ messages is $U(M,0,n,n)/\binom{2n}{n}$. Computing the entire curve up through $M$ takes $O(Mn^3)$ integer arithmetic operations and $O(n^3)$ live numeric cells. The implementation can retain decision bits to produce an encoder and an online decoder for individual deals. [Exact solver and encoder](#src-further-signals-advice-py)
###### An exactly fair optimum for 52 cards
The rules favor nomination when nomination and continuation have equal value, provided the nomination can improve the incumbent and the state has positive remaining upside. Unused labels stop at exhaustion.
| Outcome | Number of shuffles |
|---|---:|
| The first nomination strictly wins | 220,614,616,016,926 |
| The second nomination strictly wins | 201,242,929,835,476 |
| Both pay zero | 74,060,987,095,702 |
| Total | 495,918,532,948,104 |
Assign label two to the first 46,716,336,638,576 tied deals in lexicographic order, with `B` before `R`. Assign the other tied deals to label one. Both labels now occur on exactly 247,959,266,474,052 decks, with identical payouts on every reassigned deck. The last tied deal assigned label two is `RBBBBRBBBBBBBRRRRRBBBRBBBRRBBBBRRRRBBBRRRRRRRBBRRRRR`. A forward recurrence counts the three outcomes. A separate backward recurrence ranks tied deals without listing them. [Implementation](#src-further-signals-advice-py)
##### When does the adviser match a prophet?
**Exactly $n$ messages suffice and are necessary** to match the pathwise maximum on every balanced deck with $n\ge1$, hence exactly $\lceil\log_2 n\rceil$ bits suffice in a fixed-width encoding.
For sufficiency, use labels $1,\ldots,n$. Label $j$ means “stop the first time the score reaches $j$, or at exhaustion if it never does.” Announce the peak if positive, or send any label when the peak is zero.
For necessity, consider the $n$ decks $R^j B^n R^{n-j}$ for $1\le j\le n$. Each has a unique peak at time $j$. On two such decks with $j
#### 4.5. The sharp optimality threshold for capped peaks
Let $H$ be the maximum running score of a balanced deck with $n$ pairs, including the initial zero. With $m\ge1$ messages, the adviser can announce $\max(1,\min(H,m))$. The recipient stops on first reaching the announced level, or at expiry. This earns $\min(H,m)$ on every deal. Let $m_0(n)$ denote the smallest budget for which this rule is optimal in expectation.
**For every $n\ge1$**,
$$
m_0(n)=
\begin{cases}
3 & n=4,\\
4 & n=6,\\
\lceil n/2\rceil & \text{otherwise}.
\end{cases}
$$
The capped rule is optimal exactly when $m\ge m_0(n)$. In that range, reflection gives the exact price
$$
V_m(n)=\frac{\sum_{j=1}^{\min(m,n)}\binom{2n}{n-j}}{\binom{2n}{n}} .
$$
For the 52-card game, this first holds with **13 messages**. The full prophet value still requires 26.
##### Verification by one-step deviations
Use the equivalent game of $m$ online nominations, where the best nomination is paid and missing nominations earn zero. Denote the incumbent by $h\ge0$, the number of nominations left by $q$, the red and black cards left by $r,b$, and the current score by $s=b-r$. It suffices to consider nominations strictly above $h$. Any policy can ignore a non-improving nomination while internally simulating the original policy, keeping one more nomination in reserve. Consequently $h+q\ge m$ on all reachable states. Write $P_\ell$ for the probability of reaching level $\ell$ from the current state, inclusive.
The candidate strategy nominates every score strictly above its incumbent when it has a nomination available. With $q=0$, its value is $h$. With $q>0$, its conditional value is
$$
W=
\begin{cases}
h+\sum_{\ell=h+1}^{h+q}P_\ell & s\le h,\\
s+\sum_{\ell=s+1}^{K}P_\ell,\quad K=s+q-1 & s>h .
\end{cases}
$$
These are sums of successive unit increments in its realized payout. At $s\le h$, waiting is the only undominated move. At $s>h$ the strategy nominates now. Compare it with waiting exactly one draw and resuming the candidate strategy. On a red draw the alternative may capture one extra dollar, precisely when its remaining path hits $K+1$. On a black draw it loses one dollar if the path never recovers to $s$. If $s>h+1$, it also loses a dollar on paths subsequently hitting $K$, because it nominates the lower score $s-1$ immediately. This last event is disjoint from failure to recover. For $s=h+1$ the red gain and failure-to-recover loss give the exact difference.
Put $t=r+b$. Among the $\binom{t}{r}$ suffixes, the red-gain event has $\binom{t-1}{b-K-1}$ members. After a forced red, reflect the path up to its first visit to $K+1$. This exchanges its initial excess of $K-s$ red cards for black and leaves $r-1-(K-s)=b-K-1$ red cards. The converse path must hit the reflected level because its endpoint lies below that level. When $K=s$, every red draw qualifies. Out-of-range binomial coefficients are zero.
The black failure-to-recover event has $\binom{t-1}{r}-\binom{t-1}{r-1}=(s/t)\binom{t}{r}$ members. The first term counts all black-first paths and the second counts those recovering to $s$ by the same reflection. This is the strict ballot count. Thus for optimality it is enough to establish
$$
\binom{t-1}{b-K-1}\ \le\ \frac{s}{t}\binom{t}{r}
\tag{1}
$$
in all states with $s>h,\ q>0$. Backward induction then proves the candidate optimal. Choosing a nomination at a given time merely reduces $q$ and updates the incumbent to $s$, so same-time choices admit the same induction by remaining nominations. Expiry gives zero additional reward.
##### The inequality
Suppose $m\ge4$ and $n\le2m$. We have $K=s+q-1\ge\max(s,m)$. For $s\ge m$, the red-gain event is contained in a first red, of probability $r/t\le s/t$, since $r=b-s\le2m-s\le s$.
For $1\le s0$. Following the original instructions on every deck outside this prefix makes the unconditional gain strict.
When $(n,m)=(4,2)$ or $(6,3)$, use the prefix consisting of a single red. Here $h=0,\ s=1,\ q=m,\ b=n$, and the one-step gain criterion is exact. Its normalized red-gain side is $3\cdot2/5=6/5$ and $5\cdot4\cdot3/(7\cdot8)=15/14$, respectively, against a failure-to-recover side of $1$. Waiting then resuming the candidate again strictly improves its payout. These are the two exceptions.
[Exact local and global checks](#src-further-signals-test-capped-py) compare every one-step deviation through 12 remaining black cards, and every admissible message budget on decks of one through 40 pairs against the unrestricted dynamic program.
#### 4.6. Peak menus and the four-message construction
Write H for the largest balance in a uniform shuffle with n red and n black cards. Reflection gives W(t) = binomial(2n,n−t) deals with H≥t. Four related experiments have different rules.
* **Fixed target menu.** Agree on m thresholds. The dealer sends the highest attained threshold, or any unattained threshold when none was reached. The player stops at the announced balance, or receives zero at the end. The total over all shuffles for targets t₁<⋯0.557, versus 0.522038 for ordinary play. The function `fair_peak` optimizes c in this family.
* **Four two-stage targets.** A two-bit message identifies a row of the following four policies. Until three quarters of the deck is drawn, use a target from (0.4,0.7,1.0,1.4)√n. At the switch and thereafter use the paired target from (0.2,0.5,0.8,1.1)√n. Stop on reaching or exceeding the active target. Round to nearest attainable integer level, with ties upwards. Failure to hit either threshold pays the terminal zero. The adviser chooses the best resulting policy.
For the two-stage strategy, write H₁,H₂ for the segment maxima including their shared endpoint. Let Qₐ,Qᵦ round each maximum down to the largest reached target or zero. The adviser earns at least max(Qₐ(H₁),Qᵦ(H₂)): an early hit pays ≥ its paired late target, and, after an early miss, a late hit pays at least its target. For exact finite calculations, condition on the score between segments, use reflection separately on the two segments, and sum the masses. The Python test also enumerates all deals through seven pairs.
In the limit measure height in units of √n. For the split d=3/4, the intermediate score Z is normal with variance s²=2d(1−d). Conditional on Z=z, the segments are independent bridges. For positive u,v, given z below min(u,v), the conditional joint probability of staying below the two barriers is
$$
(1-e^{-u(u-z)/d})(1-e^{-v(v-z)/(1-d)}).
$$
Above either barrier the probability is zero. At an infinite barrier omit its factor. Integrating over z≤min(u,v) gives the joint CDF F(u,v). To average the rounded heights, sort all eight levels h. Each gap h−hprev contributes (h−hprev)(1−F(u,v)), where u and v are the smallest early/late targets at least h, or infinity. Completing the square reduces each integral to a normal CDF. `two_stage.py` encloses the CDF by integrating the degree-158 Taylor polynomial of exp(−x²/2) and enclosing the signed remainder, with outward interval arithmetic throughout. It verifies a normalized value between 0.70678907 and 0.70678908. The bridge invariance principle passes this bounded functional to the limit since individual barrier contacts have a continuous maximum distribution. The ordinary and full-information limits are 0.522037676 and √π/2=0.886226925 in these units. This particular menu therefore recovers at least 50.7295% asymptotically. [Dimitrov & Wu 2021](https://doi.org/10.1007/s00440-021-01030-y "KMT coupling for random walk bridges")
The unrestricted signal computed in `../signals/advice.py` may depend on the entire order of the deal. It dominates each of these menus. The half-premium result above is a constructive lower bound. The two-nomination upper bound establishes necessity of a second fixed-width bit.
```bash
set -e
python3 peak_menus.py --pairs 26 --messages 26 --bins --check | cmp - peak-menus-52.tsv
python3 two_stage.py --check # needs mpmath
```
For arbitrary pre-game messages the sharp [capped-peak theorem](#proof-further-signals-capped-peak-md) turns a high-budget query into a single binomial coefficient plus O(min(m,n−m)) adjacent-coefficient updates. `advice_price.py` sums from whichever end is shorter and delegates other budget sizes to the full nomination solver. Runtime here counts arithmetic operations, with large integer operands. On one host seven repeated in-process batches gave median times of 1.67 µs for `price(26,16)` and 29.88 ms for the unrestricted `advice_values(26,16)`. Both return exact values. Run `python3 advice_price.py --pairs 26 --messages 16 --exact` and `python3 test_caps.py`.
#### 4.7. Adaptive voucher timing, saturation, and fixed schedules
With 26 red and 26 black cards, **21 adaptively timed peeks give exactly the same value as seeing the next card before every decision**. Twenty peeks miss by exactly $1 divided by 495,918,532,948,104, the number of distinct shuffles. With a fixed schedule of peek opportunities the minimum rises to **45**, covering draw positions 6 through 50.
For every budget and every initial color composition there is an optimal policy with one switch. **Draw blind until a chosen stopping time. Then collect successive reds until the first black or the budget runs out, and stop.** This gives a one-pass exact solver for an arbitrary budget.
A peek reveals the next card before the decision to take it. A player may stop and leave that card undrawn. A voucher is consumed whether the card is taken or left. A fixed schedule reveals information only when play reaches the indicated position. Announcing a future card's color before play is a different experiment.
##### 52 cards
All entries are expected dollars from the initial balance of zero. The percentages measure the fraction of the unrestricted one-card preview's advantage over blind play. The unrestricted value is exactly 508618572583783/165306177649368 dollars. Every best fixed schedule in this table is unique.
| Peeks | Adaptive value | Preview advantage captured | Best fixed value | Fixed draw positions |
|---:|---:|---:|---:|:---|
| 0 | 2.624476 | 0% | 2.624476 | ∅ |
| 1 | 2.909155 | 62.9333% | 2.660393 | 13 |
| 2 | 3.017894 | 86.9718% | 2.691596 | 13, 15 |
| 3 | 3.056541 | 95.5153% | 2.717116 | 13, 15, 50 |
| 4 | 3.070087 | 98.5099% | 2.741447 | 13, 15, 17, 50 |
| 5 | 3.074659 | 99.5206% | 2.763387 | 13, 15, 17, 28, 50 |
| 6 | 3.076167 | 99.8541% | 2.783591 | 13, 14, 15, 22, 23, 50 |
| 21 | 3.076827 | 100% | | |
One on-demand voucher is worth 28.468¢ above blind play. The best predetermined opportunity adds 3.592¢. With one voucher, an optimal policy first spends as early as position 7, after six reds. Its most common spending position is 50, on 7.1535% of all decks. It uses the voucher on 72.9045% of all decks. With 21 vouchers, the policy spends **1.234265 on average**, uses none on 23.4714% of deals, and spends all 21 on exactly 27 deals. These distributions preserve vouchers on ties, stop on blind stopping ties, and stop on black after a peek when taking black exactly breaks even. Other optimal policies can have different timing distributions.
##### The single terminal run theorem
Write \(r,b\) for the remaining red and black counts. Work in expected gains over the current cash. Let \(L\) be the initial run of red cards in a uniform suffix and define \(g_m(r,b)=\mathbb E\min(m,L)\). With \(t=r+b\), \(k=\min(r,m)\), and \(P=\binom{t}{b}\), the hockey-stick identity gives
\[
P g_m(r,b)=\sum_{i=1}^{k}\binom{t-i}{b}
=\binom{t}{b+1}-\binom{t-k}{b+1}.
\]
We take a binomial coefficient to be zero when its lower argument exceeds its upper one. If \(b>0\), this bonus is harmonic under one blind draw. For each \(i\le r\), exchangeability gives equal probabilities that positions 1 through \(i\), or positions 2 through \(i+1\), are all red. Terms with \(i>r\) vanish. Thus the expected capped red run before drawing equals its expected value just after drawing. On the all-red axis \(g_m(r,0)=\min(m,r)\).
First restrict the player to a blind phase followed by collecting one capped red run. Let \(W_m\) be that restricted game's value. The player can always delay switching on an all-red suffix, collecting all \(r\) dollars. Write \(W_m=g_m+Z_m\). Harmonicity gives the ordinary blind stopping recurrence for \(Z_m\), with a new all-red terminal reward. With \(p=r/t\), \(q=b/t\), and subscripts \(R,B\) indicating the red- and black-draw child,
\[
Z_m(r,0)=(r-m)_+,\qquad Z_m(0,b)=0,\qquad
Z_m(r,b)=\max\{0,\ p(1+Z_{m,R})+q(-1+Z_{m,B})\}.
\]
This defines an auxiliary blind game in which stopping in a mixed state pays zero further dollars and reaching an all-red state liquidates its remaining cards for \((r-m)_+\). In the original game, switch when stopping solves this auxiliary recurrence. If all remaining cards are red, take them without spending vouchers.
To prove the restricted and unrestricted games coincide, the comparison we need is
\[
Z_m(r,b)\ \ge\ Z_{m-1}(r-1,b),\qquad r,m\ge1.
\]
Tag a uniformly chosen one of the larger deck's \(r\) red cards and simulate the smaller deck's blind policy, ignoring the tag. Its red rank can be privately randomized before play and recognized upon drawing. When the simulated policy requests a draw, draw until the next untagged card. The untagged deck is uniform. If the simulation stops before the all-red boundary, collecting a tagged red adds a dollar and can only help. On reaching that boundary, either the tag remains, adding one to the remaining red count and exactly offsetting the larger penalty, or it has been drawn, in which case the extra dollar covers any difference in liquidation values. The larger game can therefore realize at least the smaller expected payoff. Randomizing the tag cannot exceed the optimum over all policies.
Now induct on the number of remaining cards, simultaneously for all budgets. A blind move followed by unrestricted play has the restricted child values by induction. Also \(W_m\) increases weakly with \(m\), since any switching rule can collect a longer red run. If the first move is a peek and taking black is optimal after that peek, a blind draw with all \(m\) vouchers retained does at least as well. Taking red is always strictly optimal. In the remaining case the peek stops on black, and its value is
\[
p(1+W_{m-1,R})
=g_m(r,b)+p Z_{m-1,R}
\ \le\ g_m(r,b)+Z_m(r,b)=W_m(r,b).
\]
Here the identity conditions the capped run on its first color, and the inequality uses the tagged comparison and nonnegativity of \(Z\). Stopping is available directly and \(m=0\) is ordinary blind play. Every admissible first move is covered. This proves that a single terminal run attains the fully adaptive optimum for arbitrary \(r,b,m\).
Multiplying the recurrence by the binomial masses makes every update a maximum, an addition or a subtraction of integers. The solver `streak_value` computes a single requested budget using \(O(rb)\) integer operations and \(O(b)\) stored integers, independently of \(m\). It makes two binomial evaluations for the run bonus at the requested starting state. Integer widths grow with deck size. This removes the budget dimension from point-value calculations.
Lean 4.19 verifies the reduction for all natural \(m,r,b\). The theorem `Problem14.TerminalStreak.value_eq_single` in `../formal/TerminalStreak.lean` identifies the unrestricted rational voucher Bellman recurrence with the terminal-streak bonus plus the ordinary obstacle. Its `single_step` theorem verifies the one-switch stopping recurrence, and `bonus_binomial` proves the exact binomial expression for the streak at every budget. In `VoucherBridge.lean`, `strategy_single` identifies it with the optimum over every legal history-dependent strategy in the original deck tree. Run `../formal/check-streak.sh /path/to/mathlib` to rebuild all components. The proof establishes the tagged-red comparison by conditional expectation, with separate terms for the first red being tagged or untagged.
For any finite deck and any remaining composition the premium above blind play is at most \(1-2^{-m}\) dollars. With at most as many reds as blacks, each successive red in the streak has conditional probability at most one half. With more reds than blacks the blind strategy can lock in the gain \(r-b\) by drawing to exhaustion, which already covers the mean full red streak \(r/(b+1)\). These inequalities bound the immediate switching reward, and blind continuation preserves a uniform bound. Lean checks the result for every legal strategy in `../formal/VoucherPremium.lean`.
##### The exact saturation threshold
Let \(u(r,b)\) denote the unrestricted one-card-preview gain. For \(b\ge1\), define
\[
h(b)=\max\big(\{0\}\cup\{r\ge1:u(r,b-1)<1\}\big),\qquad h(0)=0.
\]
The set is bounded by \(b-1\) because drawing every remaining card guarantees \(u(r,b-1)\ge r-b+1\). Its nonzero members form an initial interval. In fact \(u\) is nondecreasing in the number of reds and nonincreasing in the number of blacks.
For the red comparison, tag one uniformly chosen red card of the larger deck. Simulate the smaller game by collecting the tag if it comes up and otherwise following the simulated policy with one-card preview. Deleting the tag leaves a uniform smaller deck and collecting it only adds to the payoff. For the black comparison, simulate the larger deck from the smaller by inserting a virtual black in a privately randomized uniform slot. When that slot becomes next, apply the simulated strategy to the imaginary black. If the strategy accepts it, advance the simulation without paying its dollar cost. In all other slots use the real preview. Both constructions are feasible online and compare expected payoffs. These comparisons imply that \(h(b)\) is nondecreasing in \(b\).
The exact smallest budget that attains the unrestricted value is
\[
\boxed{K(r,b)=\min(r,h(b)).}
\]
With both colors available, the full-information red branch always strictly continues. Its black branch strictly stops exactly when \(u(r,b-1)<1\). In this region a peek is strictly necessary to attain the full value. Outside it, blindly drawing attains that value provided the children retain full information. On a black-branch tie, draw blind. The first required peek therefore occurs with at most \(\min(r,h(b))\) reds left. Each succeeding peek either consumes a distinct red or ends the game with at least one red still present. This proves sufficiency. For necessity, follow the positive-probability event of drawing all the reds first. An optimal policy must continue on each of these red cards. As the red count falls with \(b\) fixed, it must inspect each of the \(\min(r,h(b))\) mixed states belonging to the strict region. This lower bound applies to arbitrary adaptive policies including randomized ones.
For 26 black cards the two witness values are
\[
u(21,25)=\frac{6548573221142}{6943526580276}<1,\qquad
u(22,25)=\frac{19226111464341}{14833897694226}>1.
\]
Thus \(h(26)=21\). On a deck beginning with reds the first forced inspection comes after five reds, and each succeeding red is inspected. There is even a pair of optimal policies at budgets 20 and 21 whose payoffs differ on exactly one shuffle. Follow the unlimited policy just described and truncate its terminal red run after 20 reds. The computed thresholds are \(h(26)=21\) and \(h(25)=20\). By monotonicity, a switch with 21 reds left is possible only with all 26 black cards still present, immediately after five initial reds. Truncation loses one dollar exactly when the remaining 21 reds also arrive before any black. This singles out the deck with **all 26 reds first**, followed by all 26 blacks. On every other deck the payouts agree. The checked optimum gap of one aggregate dollar proves this particular truncated policy optimal at budget 20 as well.
The function `saturation` computes \(h\) in one streaming pass without evaluating voucher prices.
##### Direct verification and fixed schedules
The independent multilayer Bellman table stores integer aggregate gains \(D_m=PV_m\). An unavailable child's mass and aggregate are both zero. Define the value of drawing blind by
\[
C_m=D_{m,R}+P_R+D_{m,B}-P_B.
\]
Then \(D_0=\max(0,C_0)\), and when \(m>0\),
\[
D_m=\max\{C_m,\ D_{m-1,R}+P_R+\max(0,D_{m-1,B}-P_B)\}.
\]
This supplies the exact policy maps and forward timing distributions. With unrestricted peeks one can always observe the next color, so use the second term with unrestricted child values. The direct capacity recursion considers the minimal budgets under a peek or a blind draw that both attain the unrestricted value. A peek costs one plus the maximum child capacity over strict continuation branches. A blind draw is feasible only if taking black is weakly optimal, and reserves the maximum capacity of both children. Ending on a black tie after a peek avoids wasting capacity.
For fixed positions, the revealed layer uses the unrestricted color-conditioned recurrence, and an unrevealed layer takes the better of stopping and drawing blind. The C++ search enumerates every position subset of each indicated size, sharing rows for schedules with common suffixes. Thus each entry of `fixed.csv` compares all \(\binom{52}{m}\) choices of that size, including dates where a player may already have stopped. The implementation bounds decks at 30 pairs so signed 64-bit arithmetic suffices.
To certify the 45 necessary positions without searching \(\binom{52}{45}\) choices, begin at the root and propagate only branches where **every** full-value policy must continue, including red but omitting black-continuation ties. At each reached mixed state where the black branch strictly stops, any full-value fixed schedule must include that draw position. The witness states in `required.csv` cover every position from 6 to 50. Running the fixed-schedule recurrence on precisely those 45 positions yields the unrestricted value. This proves both directions of the minimum.
For every balanced deck with \(n\ge2\), the unique minimum fixed schedule has the explicit form
\[
\{n-h(n)+1,\ldots,2n-2\},\qquad \text{size }n+h(n)-2.
\]
For each \(b=2,\ldots,n\), follow a prefix of \(n-b\) blacks and then reds. Every black in that prefix is strictly worth drawing under full preview. On encountering the first black, \(u(n,n-1)>1\), since drawing all but a final black strictly improves upon the guaranteed payoff of one dollar. Every later black leaves an even larger guaranteed payoff. Reds always strictly continue. Keeping \(b\) fixed and lowering the red count from \(h(b)\) to 1 therefore forces inspections at every position from \(2n-b-h(b)+1\) to \(2n-b\). These intervals cover the stated range because \(h\) is nondecreasing and \(h(2)=1\). Earlier positions have more than \(h(n)\) reds left. The last two positions have either known color or the mixed state \((1,1)\), where blind drawing is optimal. The stated range is thus sufficient as well as necessary. The empty or two-card balanced deck needs no peeks.
##### Reproduce
Run from this directory. Python uses its standard library. The schedule search requires a C++17 compiler.
```sh
set -e
python3 test_vouchers.py
python3 vouchers.py 26 --value 20
python3 vouchers.py 26 --saturation
python3 vouchers.py 26
python3 vouchers.py 26 --strategy 1
python3 vouchers.py 26 --timing 1
python3 vouchers.py 26 --usage 21
python3 vouchers.py 26 --necessary
c++ -std=c++17 -O3 fixed_schedule.cpp -o /tmp/p14-fixed-schedule
/tmp/p14-fixed-schedule 26 6
```
`--strategy M` gives the chosen action and the exact probability of reaching every state visited under that budget. `--positions 13 15 50` prices a specified schedule. The tests enumerate complete color decks through five cards of each color, exhaust fixed schedules on four pairs, cross-check the one-voucher and rolling-preview solvers when installed, and verify the 52-card figures. The unrestricted saturation law is also compared against the independent capacity recursion at all rectangles through 80 cards of each color.
#### 4.8. Exact totals and policy semantics for vouchers and nominations
The full-history voucher and nomination programs check the exact totals, attainment and saturation described in Section 6. Source worksheet: `derivations/4.8-exact-totals-and-policy-semantics-for-vouchers-and-nominations.md`.
#### 4.9. Exact rolling preview and finite classifications
There are \(n\) red and \(n\) black cards, scoring \(+1\) and \(-1\). Let \(V_k(n)\) be the optimal payout when each decision sees the next \(k\) cards for free and in order. Perfect foresight earns the expected maximum of the balanced walk, \(P(n)=(4^n/\binom{2n}{n}-1)/2\). We seek the smallest integer \(k\) with \(2V_k(n)\ge V_0(n)+P(n)\).
For a standard 52-card deck, **two visible cards suffice**. The target is $3.332570162. One card earns $3.076827375 and two earn $3.381628365. A 200-card deck needs six, a 400-card deck ten, and a 1,200-card deck 26. `ranges.csv` reports runs of equal minima. `thresholds.csv` certifies each deck individually, so the run boundaries do not assume monotonicity in deck size. More information can always be ignored, which does prove monotonicity in \(k\).
The full strip sweep and a targeted extension settle all 700 balanced deck sizes up to **1,400 cards**. Preview 27 covers 620–645 pairs, 28 covers 646–671, 29 covers 672–697, and 30 is necessary and sufficient at 698, 699 and 700 pairs. The last range ends at the computation limit. At 700 pairs the 29-card signed margin is at most −$0.009492746512 and the 30-card margin is at least +$0.075666336631.
`thresholds.csv` gives an upper bound on the margin \(2V_{k-1}-V_0-P\) and a lower bound on \(2V_k-V_0-P\), in dollars, rounded outward. `exact_examples.csv` gives both adjacent unrestricted rational values at selected sizes through 800 cards. For \(n=1\), the ordinary player already earns the full prophet value.
##### The compressed exact recursion
The player can equivalently choose a past score at an ordinary stopping time, with a recall window of the last \(k\) steps including the current time. A preview choice made at time \(t\) can be committed to at \(\min(t+k,2n)\). Conversely, a recall commitment can be recognized by the preview player by the time its chosen score would be taken. The repository's `PreviewRecall.lean` proves equality of the attainable selected times.
At score \(s\), an older point is dominated if a newer point has at least its score. After discarding dominated points, the older scores strictly above \(s\) have heights \(1,\ldots,h\) above \(s\). Write their ages in increasing order as \(a_1,\ldots,a_h\), one per height. The nearest-neighbor walk implies each successive age gap is a positive odd integer, starting at age zero, and \(a_h\le k\). Conversely these lists are possible: between successive most-recent heights, the backward walk can spend each extra pair of steps one level below its next target. Equivalently, each possible ending age is an ordered sum of odd parts. Counting these lists, including the empty list, gives \(F_{k+2}\), with \(F_0=0,F_1=1\). This replaces the prior ordered-window solver's \(2^k\) states.
Bit \(a-1\) stores age \(a\). Drawing red drops the least significant occupied bit, ages the remainder and discards the expired age. Drawing black adds the old current score at age one after aging existing records. The empty history is the starting state for **every** balanced deck. In both transitions the old age-\(k\) bit has no influence on the successor state. If that bit is absent, the best current score remains available after one more draw, so the continuation dominates immediate exercise. If it is present, the continuation is identical to that for the same mask with that bit cleared; compare it with immediate exercise. There are therefore at most \(F_{k+1}\) structurally distinct continuation sums per nonterminal cell; collapse can eliminate more.
At \(r\) red and \(b\) black cards remaining, the score is \(s=b-r\). The integer DP stores the total over \(D=\binom{r+b}{r}\) equiprobable completions. Continuation adds the red and black child totals. Exercise contributes \((s+h)D\). At the terminal state the payoff is \(h\). Negative exercise can be discarded because waiting until the end always secures zero. The empty history minimizes the value, and the all-black history maximizes it, because it has the highest possible candidate at each age. The solver collapses the entire cell when those two agree. Histories whose best old score is nonpositive can also be forgotten. No denominator reduction is needed during the recursion.
The 52-card threshold therefore needs only two continuation totals per cell. For two-card recall write \(X_{rb}\) for the empty history, \(Y_{rb}\) for a one-dollar record one step old, \(s=b-r\), and \(D_-=\binom{r+b-1}{r}\). Then
\[
X_{rb}=X_{r-1,b}+Y_{r,b-1},\qquad
Y_{rb}=X_{r-1,b}+\max\{Y_{r,b-1},(s+1)D_-\}.
\]
Start from \(X_{00}=0,Y_{00}=1\) and omit missing children, including the whole maximum when \(b=0\). The desired numerator is \(X_{nn}\). The standalone `two_cards.py` evaluates both cases using only Python integers, in \(O(n^2)\) additions and comparisons and \(O(n)\) stored totals. For one-card preview there is just one continuation total, with \(X_{rb}=X_{r-1,b}+\max\{X_{r,b-1},sD_-\}\) and \(X_{00}=0\).
`rolling.cpp` computes the exact unrestricted rationals. Its worst-case time is \(O(n^2 F_{k+2}L)\) and its rolling storage is \(O(n F_{k+2}L)\) machine words, where \(L=O(n/\text{word bits})\) holds counts over the suffixes. It also handles \(k=0\) and \(k\ge 2n-1\) directly; the last unknown card is determined by the deck composition.
##### Scaling the exact minimum further
`band.cpp` allows the player to stop normally until the walk first reaches \(+w\) or \(-w\), where it commits to the better of its available maximum and the guaranteed final zero. It evaluates this policy class with \(q\) fractional bits, rounding each conditional continuation downward. Each such rounding loses less than \(2^{-q}\), and there are at most \(2n\) draws. If the lower fixed-point result is \(L\) dollars, then
\[
L \le V_k(n) \le L+2n\,2^{-q}
+ 2n\,\frac{\binom{2n}{n+w}}{\binom{2n}{n}}.
\]
For the last term, mimic an unrestricted optimal strategy up to exit. On a path hitting either boundary the loss is at most \(n\); on the other paths it is zero. Reflection gives the exact probability of reaching each one-sided boundary; the sum of the two probabilities bounds the union. Take \(\binom{2n}{n+w}=0\) for \(w>n\). The two integer margin columns emitted by `band` multiply the lower and upper signed margins by \(2^q\binom{2n}{n}\). A negative previous upper bound and a nonnegative current lower bound settle the exact integer minimum. The unrestricted rational expected payoff itself comes from `rolling`.
The conditional mean is rounded using a 128-bit multiply by \(\lceil 2^{64}/t\rceil\) for \(t=r+b\). The program checks that the numerator times \(t\) is less than \(2^{64}\), so the shifted high product is precisely the integer quotient. Every inside-band payoff is at most \(w+k\). These bounds permit 32-bit stored values on the default runs. A 64-bit specialization resolves unusually small margins. At \(n=594, k=25\), for instance, a 33-fractional-bit run at width 118 puts the signed margin between −0.000070032 and −0.000069618 dollars.
For one \(k\), the band computation takes \(O(nwF_{k+2})\) word operations and \(O(w F_{k+2})\) words of working space, in addition to the ordinary-game table. The exact ordinary totals take \(O(n^2)\) big-integer operations and one row of storage. The largest figures in this directory are finite-deck results. Extrapolating the observed ratio of \(k\) to deck length does not establish a limit.
##### Reproduction
Requires Python 3, C++17, and GMP with its C++ bindings. From this directory:
```bash
set -e
make check
python3 two_cards.py 26
./rolling 26 2 26
./band64 594 25 118 33 594
python3 examples.py
python3 classify.py --max-k 29 --extend 700 70 --cache /tmp/rolling-preview-cache
python3 benchmark.py --runs 3
```
`rolling MAX_PAIRS K [MIN_PAIRS]` emits exact totals for every eligible balanced deck in the requested range, using one DP. `check.py` compares 48 exact rational results against the previous ordered-window recursion, checks that both precision modes enclose exact margins, and compares 120 deterministic random fixed-point strip computations bit-for-bit with a separate raw-history recursion. The default classification uses \(n_{\max}=\max(36,25k+35)\), \(w=\lfloor\sqrt{18n_{\max}}\rfloor+1\) capped by \(n_{\max}\), and 24 fractional bits. If an integer sign remains unresolved, it retries that particular deck with 33 fractional bits and a wider strip. The 30-card extension only needs positive lower witnesses at the three remaining sizes, since the broad 29-card sweep already bounds the previous margins from above. It uses \(w=70\), 24 fractional bits, and took 225 s with 874 MiB peak resident memory. The main 29-card sweep took 236 s. The published large runs used one pinned AMD EPYC 9V74 virtual CPU and GCC 14.2.0 with `-O3` (the main strip sweep also used `-march=native`).
At 26 pairs and 12 visible cards, the earlier Python ordered-window recursion took 0.871370 s, the same recurrence in native one-word C++ took 0.008123 s, and the exact recall solver took 0.002960 s. Three-run medians include process launch for each C++ solver and exclude interpreter startup for the already-imported Python implementation. `benchmark.csv` gives all three window sizes. `ordered_small.cpp` is the native control; its one-word totals cover at most 31 pairs. The algorithmic state count at 29 visible cards is 1,346,269, compared with 536,870,912 ordered windows. The complete 29-card band run, which evaluated all decks through 760 pairs to locate the cutoff, took 236 s and peaked at 777 MiB. Other work briefly shared the pinned core during that run. Increasing the preview by one multiplies the asymptotic state count by the golden ratio. At 40 visible cards, a single dense 32-bit cell already takes 1,071,657,184 bytes (267,914,296 histories), before storing its neighbors or transition indices.
#### 4.10. Short-preview and voucher limits
Write N=2n for the deck size and Sᵢ for the balance after i draws. Write Vₖ for the optimal expected payout with a rolling k-card preview, V₀ for ordinary play, and Wₘ for play with m one-card peek vouchers. Each voucher may be exercised after seeing the past, before taking the next card.
For fixed k, **Vₖ−V₀ → k dollars** as N→∞. More generally, (Vₖ−V₀)/k→1 for every sequence k≥1 with k·2ᵏ=o(√N). By comparison, **Wₘ−V₀ → 1−2⁻ᵐ dollars** for every fixed m. If m→∞ the latter premium approaches one dollar. The first three optimally timed one-use vouchers approach incremental values of 50¢, 25¢ and 12½¢.
##### The ordinary stopping point
Choose an optimal ordinary policy that stops on ties. With t cards left and balance x, a sufficient stopping condition is x≥2√t. The finite-deck supermartingale proof is in the accompanying `ordinary-bound.md`. Write τ for this policy's stop. Given ε>0 there are δ>0 and C<∞ such that
$$
\liminf_{N\to\infty}\Pr\{N-\tau\ge\delta N,\ |S_\tau|\le C\sqrt N\}>1-\varepsilon .
$$
Indeed the scaled walk converges weakly in the uniform topology to a standard Brownian bridge. Its supremum is tight. A Brownian bridge crosses 2√(1−u) strictly before time one almost surely. By reversal and the representation B(s)=W(s)−sW(1), this follows from the Brownian law of the iterated logarithm at zero. The probabilities of a strict crossing on compact intervals [0,1−2δ] increase to one as δ decreases to zero. Such a crossing is an open event in the uniform topology, survives the vanishing mesh error, and forces the discrete policy to have stopped while at least δN cards remain. At those ordinary stopping states the unseen deck's red fraction converges in probability to 1/2. [Dimitrov & Wu 2021](https://doi.org/10.1007/s00440-021-01030-y "KMT coupling for random walk bridges")
##### Waiting for the bad news
Any ordinary player can recognize a preview player's stopping decision at most k cards late. The balance can fall by at most k in between. Hence Vₖ−V₀≤k. The Lean file `PreviewPremium.lean` proves the pathwise bound and its finite-expectation consequence.
For the reverse bound play ordinarily until τ. Launch the following experiment only if the preceding good-state inequalities hold. Choose m a multiple of k with k·2ᵏ≪m≪√N. Inspect the next block of k cards. If they are all black, cash out immediately. Otherwise draw the entire block and repeat, up to m draws. On timeout cash out then. This is an admissible rolling-preview policy. Compare its payout with that of the ordinary observer who finishes the first all-black block, or finishes at the same timeout. The observer's stopping rule is determined by the cards already drawn. The preview player gains exactly k relative to that observer on success and zero on failure.
Up to the timeout, the ordinary per-card conditional drift equals −x′/t′. Its magnitude stays below (C√N+m)/(δN−m). Summing for the stopped process shows that the ordinary observer's expected loss from the original stop is at most m(C√N+m)/(δN−m)=o(1). At each of the m/k block starts the conditional probability of an all-black block is at least
$$
\left(\tfrac12-\frac{C\sqrt N+m}{2(\delta N-m)}\right)^k
=2^{-k}(1-o(1)).
$$
The bound applies conditional on every surviving history and on each preceding black in the block. Since k=O(log N), the relative error tends to zero. The probability every block fails tends to zero by iterated conditioning, because m/(k·2ᵏ)→∞. So the starting game earns at least V₀+(1−ε−o(1))k−o(1). Send ε to zero.
At longer horizons the upper bound eventually changes character. By Hoeffding's bound for samples without replacement, every length-j interval has probability at most 2 exp(−a²/2j) of an absolute balance movement of at least a. There are at most Nk intervals of length at most k. With A=√(2k log(2Nk)), integration of the union bound gives
$$
0\le V_k-V_0\le\min\{k,\ A+k/A\}.
$$
In particular k≫log N implies (Vₖ−V₀)/k→0. The precise crossover at k proportional to log N is open here. For capturing a fixed fraction of the prophet premium the relevant scale is linear in N, as established in the accompanying `rolling.md`. [Hoeffding 1963](https://doi.org/10.1080/01621459.1963.10500830 "Probability Inequalities for Sums of Bounded Random Variables")
##### The price of a handful of vouchers
The single-switch theorem in `../vouchers/README.md` says to play blind until an ordinary stopping time, then take a capped run of reds, stopping before its first black. Write gₘ(r,b) for the expected length of that run. If the balance x=b−r is negative, switching to the run yields at most
$$
x+g_m(r,b)\le b-r+\frac{r}{b+1}=b\left(1-\frac{r}{b+1}\right)\le0.
$$
Playing to exhaustion guarantees zero there. We can therefore choose an optimal switch that occurs at nonnegative balance or at the terminal zero. At such a switch r≤b, so the chance that the next j cards are all red is at most 2⁻ʲ. Consequently gₘ≤1−2⁻ᵐ, and the expected balance at the switch is at most V₀ since its timing is ordinary. On every balanced deck,
$$
0\le W_m-V_0\le1-2^{-m}.
$$
For a matching asymptotic lower bound, switch at the ordinary optimum τ. For each fixed j, conditional on the ordinary good states, the next j cards are all red with probability tending uniformly to 2⁻ʲ. Summing for j=1,…,m proves the claimed limit for fixed m. Monotonicity in m and the absolute upper bound of one dollar give the result for m→∞. This argument prices unrestricted adaptive vouchers because the single-switch theorem was proved for that full game.
#### 4.11. The positive limiting preview fraction
Let `N=2n` count cards, and let \(S_i\) be the score after \(i\) cards from a uniformly shuffled balanced deck.
The player sees the next \(k\) cards at every turn and takes the score at the chosen stopping time, including the option to finish at zero.
Write \(V_{N,k}\) for the value and \(P_N=E\max_{0\le i\le N}S_i\) for full foresight.
Let \(k_*(N)\) be the smallest preview giving at least \((P_N+V_{N,0})/2\).
**Theorem.** The fraction \(k_*(N)/N\) converges to a constant \(d_*\) strictly between \(1/1280\) and \(1/20\). The 30-block certificate later in this appendix sharpens the upper bound to \(1/30\).
Every preview of \(o(N)\) cards buys a vanishing fraction of the prophet's premium.
More generally each fixed fraction of that premium strictly between zero and one requires its own asymptotically positive, uniquely determined fraction of the deck.
The proof below is mathematical; the upper endpoint uses a reproducible integer calculation.
##### Turning a preview into a trailing maximum
Let \(\mathcal F_i\) contain the first \(i\) cards.
A preview stopping time \(\tau\) satisfies \(\{\tau\le i\}\in\mathcal F_{(i+k)\wedge N}\).
Then
\[
V_{N,k}=\sup_{\sigma\text{ an ordinary stopping time}}
E\max_{(\sigma-k)^+\le i\le\sigma}S_i.
\]
In one direction \(\sigma=(\tau+k)\wedge N\) is ordinary and its window contains \(\tau\).
Conversely, take the first maximizer \(\eta\) in the trailing window at an ordinary \(\sigma\).
For \(\eta\le i\), one must have \(\sigma\le i+k\); for each such value of \(\sigma\) the maximizing index is determined by the revealed path.
Thus \(\eta\) is a preview stopping time and its score equals the trailing maximum.
The same foresight-to-lookback representation was established for a continuous stock-price process by [Ernst, Rogers & Zhou 2017](https://www.sciencedirect.com/science/article/pii/S0304414917300923 "The value of foresight"), proposition 1.
##### The limiting stopping problem
For a standard Brownian bridge \(B\) from zero to zero on \([0,1]\) with its usual filtration, define
\[
v(d)=\sup_{0\le\sigma\le1} E\max_{(\sigma-d)^+\le t\le\sigma} B_t,
\qquad 0\le d\le1,
\]
where \(\sigma\) runs over ordinary stopping times.
If \(k/N\to d\), then \(V_{N,k}/\sqrt N\to v(d)\).
Here is a finite-grid proof that accounts for the information available to the stopper.
The linear interpolation \(X_N(i/N)=S_i/\sqrt N\) converges weakly in the uniform topology to \(B\) by the bridge invariance principle (equivalently apply the integer-valued coupling to the zero/one increments before rescaling).
Reflection gives
\[
\Pr(\max |S_i|\ge h)\le2\binom{2n}{n-h}/\binom{2n}{n}
\le 2e^{-h^2/N},\qquad 1\le h\le n.
\]
For the second bound, take logs of the product of \((n-j)/(n+j+1)\) over \(0\le jv(d_1)\).
[Peskir & Shiryaev 2006](https://doi.org/10.1007/978-3-7643-7390-0 "Optimal Stopping and Free-Boundary Problems").
The usual Brownian stopping value is \(v(0)=(1-a^2)\sqrt{\pi/2}=0.36913638\ldots\), where \(a=0.83992367569\ldots\) solves \((1-a^2)\int_0^\infty e^{au-u^2/2}\,du=a\).
Reflection gives \(\Pr(\max B\ge x)=e^{-2x^2}\) for \(x\ge0\), hence \(v(1)=\sqrt{\pi/8}=0.62665707\ldots\).
The unique solution of \(v(d_*)=(v(0)+v(1))/2\) therefore targets \(0.49789672\ldots\) per \(\sqrt N\).
For each fixed \(dd_*\) it exceeds it.
Monotonicity in \(k\) squeezes \(k_*(N)/N\) to \(d_*\).
The same argument works for any fraction strictly between zero and one.
The numerical threshold enclosure is also checked in [Coefficient.lean](#src-asmproof-coefficient-lean).
[Ekström & Wanntorp 2009](https://www.cambridge.org/core/journals/journal-of-applied-probability/article/optimal-stopping-of-a-brownian-bridge/AC73024AFDDD7FE2127B4123F3978FF9 "Optimal stopping of a Brownian bridge").
##### An explicit necessary fraction
For \(d=1/m\), write \(B_t=W_t-tW_1\).
For any ordinary stop the trailing maximum minus the endpoint is bounded by the largest downward increment \(W_s-W_t\) with \(0\le t-s\le d\), plus \(d(W_1)^+\).
Every such increment lies inside one of the \(m\) intervals \([jd,\min((j+2)d,1)]\).
The maximum drawdown within an interval of length \(2d\) has the law of \(\sup_{t\le2d}|W_t|\), by Lévy's reflection identity.
Reflection and the Gaussian tail bound give tail at most \(4\bar\Phi(x/\sqrt{2d})\le2e^{-x^2/(4d)}\).
Integrate the union bound, splitting at \(2\sqrt{d\log(2m)}\), to get
\[
v(d)-v(0)\le2\sqrt{d\log(2m)}
+\sqrt{d/\log(2m)}+\frac d{\sqrt{2\pi}}.
\]
At \(m=2304\) the right side is below \(0.12837\), while half the advantage exceeds \(0.12875\).
[Pitman & Yor 2018](https://arxiv.org/abs/1802.09679 "A guide to Brownian motion and related stochastic processes"), equation 78.
To improve the bound, cover each interval of duration \(d=1/1280\) by a block starting on the finer mesh \(d/9\) and having duration at most \(h=(1+1/9)d=1/1152\).
There are \(J=9\cdot1280\) such blocks, each contributing a drawdown tail at most \(4\bar\Phi(x/\sqrt h)\).
With \(z=4.1\), integrate this union bound beyond \(z\sqrt h\) and use \(\int_z^\infty\bar\Phi(u)du=\phi(z)-z\bar\Phi(z)\le\phi(z)/(1+z^2)\), the latter by integration by parts (the lower Mills bound).
This gives
\[
v(1/1280)-v(0)\le \sqrt h\left(z+\frac{4J\phi(z)}{1+z^2}\right)+\frac{1}{1280\sqrt{2\pi}}<0.127954.
\]
For the decimals it suffices that \(\sqrt h<0.02947\), \(1/\sqrt{2\pi}<0.399\), and \(e^{-z^2/2}<0.000224\); the last follows from the first 21 terms for \(e^{z^2/2}\).
##### A sufficient fraction using whole blocks
Divide the unit interval into \(m=20\) blocks.
At each block's beginning the player sees the full block and can take its peak or pass to the next block.
Let \(H_j(x)\) be this policy's optimal value before revealing a block, at score \(x\) with \(j\) blocks remaining.
Set \(H_0=0\).
If \(Z\) is standard normal and \(E\) is an independent unit exponential, the next endpoint \(Y\), its block peak \(M\), and the value are given by
\[
Y=\tfrac{j-1}{j}x+\sqrt{\tfrac{j-1}{jm}}Z,\qquad
M=\tfrac12\left(x+Y+\sqrt{(x-Y)^2+2E/m}\right),\qquad
H_j(x)=E\max\{M,H_{j-1}(Y)\}.
\]
The second formula follows by reflecting a bridge of duration \(1/m\) with fixed endpoints at a level above both endpoints.
Each value is nonnegative since waiting for the end pays zero, and nondecreasing in \(x\) by coupling both increments with the same \(Z,E\).
The strategy is available in the trailing-window model by evaluating the block's peak at its right endpoint.
Run `python block_certificate.py --audit` with NumPy to reproduce \(H_{20}(0)\ge2053/4096=0.501220703125\).
It exceeds the half-premium target.
The computation uses a money unit \(1/4096\), endpoint states in \([-2,2]\), and 1,024 equal-probability normal and 256 equal-probability exponential bins.
It rounds both quantiles, the next endpoint, the peak and the final expectation down.
It bounds continuation below the state grid by zero, and above it by the last grid value, using monotonicity.
The bottom normal bin also contributes zero.
Every quadrature term thus bounds the actual conditional contribution from below.
The floating-point normal and exponential inverse CDFs only propose bin endpoints.
Rational arithmetic checks the CDF inequalities by integrating degree-46 and degree-48 Taylor bounds for \(e^{-u^2/2}\) and using a degree-33 Taylor lower bound for \(e^{-u}\).
The normalizing constant is enclosed between \(39894227/10^8\) and \(39894229/10^8\), as follows by squaring from \(3.14159265<\pi<3.14159266\).
Every proposed integer square root is checked by squaring.
The array sums use signed 64-bit integers: \(|z|<4\cdot2^{16}\) in fixed-point units, \(|x|\le8192\), and the largest scaled endpoint numerator has absolute value below \(2\cdot10^{16}\).
The code bounds the distance table and checks every new value row.
With `--audit`, it also recomputes the two endpoints and the center in each of the 20 rows by a direct double sum with arbitrary-precision Python integers, checking the optimized suffix-sum computation including its final answer.
No simulation enters this bound.
#### 4.12. One-bit impossibility, prefix codes, and absolute boundary regret
##### Exactly two bits for half the value of foresight
For all sufficiently large balanced decks, one pre-game bit is insufficient and two bits suffice. In the limit, the best bit captures **less than 35%** of the premium. The previously constructed two-bit contract captures at least **50.7295%** (rounded). These are bounds on optimal performance. The exact limiting one-bit price is still open in this analysis.
Work in dollars per $\sqrt N$. The limiting unaided value is $v_1=0.3691363807\ldots$, the full-foresight value is $p=\sqrt{\pi/8}=0.6266570687\ldots$, and the midpoint is $0.4978967247\ldots$. By the advice/nominations equivalence, the optimal bit is worth the expected best of **two** adaptively nominated balances on a standard Brownian bridge, with zero available at expiry. A short polynomial certificate bounds this entire game by $0.49$. A tighter integral certificate gives $0.4592$. The four-message protocol achieves at least $0.7067890754/\sqrt{2}=0.4997753481\ldots$ in these units. [Ekström & Wanntorp 2009](https://www.cambridge.org/core/journals/journal-of-applied-probability/article/optimal-stopping-of-a-brownian-bridge/AC73024AFDDD7FE2127B4123F3978FF9 "Optimal stopping of a Brownian bridge")
###### Bound the second chance first
Suppose the first mark is $x=y\sqrt r\ge0$ with time $r$ remaining. Negative marks can be omitted while simulating the same subsequent decisions. After rescaling by $\sqrt r$, the continuation bridge starts at $y$ and ends at zero at time one. With $u=t/(1-t)$ its value has the representation $(y+W_u)/(1+u)$ for standard Brownian motion $W$. Thus a second nomination at $u=T$ adds at most the supremum of $E[(W_T-yT)^+/(1+T)]$ to the normalized bank. Write $1/(1+T)=\int_0^\infty e^{-q}e^{-qT}\,dq$. For each $q>0$, set $\lambda=y+\sqrt{y^2+2q}$. The inequality $z^+\le e^{\lambda z}/(e\lambda)$ and optional stopping of the nonnegative exponential martingale bound the incremental value by
$$
g(y)=\frac1e\int_0^\infty \frac{e^{-q}\,dq}{y+\sqrt{y^2+2q}}.
$$
This covers unbounded stopping times by localization and Fatou. A mark at expiry contributes zero gain. The inequality allows a different optimizing time for every $q$, which only helps the player.
Set $A(y)=\int_0^\infty\exp(yu-u^2/2)\,du$ and $a=A(0)=\sqrt{\pi/2}$. Then $A''-yA'=A$, and $\sqrt{1-t}\,A(B_t/\sqrt{1-t})$ is a nonnegative local martingale for the bridge $B$ by Itô's formula. Consequently, if $y+g(y)\le c A(y)/a$ for every $y\ge0$, the two-mark expected payoff is at most $c$. Localize at times bounded away from one and use Fatou on paths with a first positive mark before expiry. Paths without such a mark pay zero.
###### A short numerical inequality with a rational certificate
Substitute $q=u^2/2$ in the integral for $g$. For $U$ half-normal, $EU=1/a$ and
$g(y)=a\,E[U/(y+\sqrt{y^2+U^2})]/e$.
The function inside the expectation is concave in $U$. For $y>0$ its derivative is $y/[\sqrt{y^2+U^2}(y+\sqrt{y^2+U^2})]$, which decreases. At $y=0$ the integrand is one almost surely. Jensen gives $g(y)\le 1/[e(y+\sqrt{y^2+a^{-2}})]$.
Take $s=797/1000<1/a$, $b=368/1000>1/e$. The positive Taylor coefficients of $A$ give $A(y)/a\ge p(y)=1+sy+y^2/2+sy^3/3$. Lower bounds for $y+\sqrt{y^2+a^{-2}}$ are $D_1=y+s$ and $D_2=8y/5+4s/5$. The latter uses the unit vector $(3/5,4/5)$. It suffices that $P_D=(0.49p(y)-y)D-b\ge0$. Use $D_1$ on $[0,13/50]$. Use $D_2$ on $[13/50,1/2]$, $[1/2,1]$ and $[1,\infty)$. For a finite interval $[l,h]$ check the coefficients of $(1+u)^4P_D((l+hu)/(1+u))$. For $[1,\infty)$ check $P_{D_2}(1+u)$. All coefficients are positive. The accompanying `onebit_polynomial.py` verifies them with exact fractions. Lean independently constructs the four transformed quartics and checks strict positivity of their twenty integer coefficients in `OneBitBound.lean`. This yields the fraction $(0.49-v_1)/(p-v_1)<0.46934$.
For a tighter bound, the actual second-mark bonus is at most $\min(g(y),v_1)$. Indeed $(W_T-yT)^+/(1+T)\le W_T^+/(1+T)$ for $y\ge0$, and the latter reward has value $v_1$ since a player can replace a negative stop by expiry. The verifier `onebit_integral.py` uses $v_1<0.37$. It upper-bounds the half-normal integral on 384 bins per unit of $u$ up to 6, bounding the Gaussian factor at each left endpoint and the fraction at its right endpoint. The Gaussian tail is less than $10^{-7}$. On $0\le y\le2$ it uses 1,024 intervals per unit, an upper value for the cash and bonus and a lower sixth-order Taylor sum for $A(y)/a$. A cubic polynomial bound suffices for $y\ge2$. The arithmetic uses integers and exact fractions, with outward rounding and integer square roots. It certifies the global upper $0.4592$, giving $(0.4592-v_1)/(p-v_1)<0.35$. The numerical proof assumes the certified threshold enclosure $0.83992<\alpha<0.83993$.
###### Why the Brownian bound applies to the finite decks
For each fixed number of nominations, round every legal mark up to a deterministic time grid of mesh $1/m$. Their order is preserved and ties can be pooled. The realized error in the largest marked score is bounded by one path modulus of continuity, regardless of how the marks were selected. For marks restricted to grid times, the complete interstitial past supplies no further advantage once the current endpoint, bank and number of marks have been recorded. This follows from the Markov property and backward induction. Conditional grid transitions of the scaled deck converge to the corresponding Gaussian bridge transitions for each sequence of starting scores converging on a compact set, by the hypergeometric local limit theorem. At the last grid date the endpoint is deterministically zero. Conditional second moments are locally bounded and the payoff grows at most linearly in starting scores and bank for a fixed grid. Backward induction therefore gives convergence of each fixed grid's values. For the whole path, the bridge invariance principle and the reflection bound $P(\max_i |S_i|\ge h)\le 2e^{-h^2/N}$ give uniformly integrable suprema and vanishing expected modulus as the mesh shrinks. Taking the mesh to zero gives convergence of optimal two-mark deck values to the Brownian value. The grid argument accounts for the information available at each stopping time. [Dimitrov & Wu 2021](https://doi.org/10.1007/s00440-021-01030-y "KMT coupling for random walk bridges")
###### Do we need all four distinct messages?
This is a sharper question than counting whole binary digits. Three messages recover **63.57%** of the premium on a 52-card deck and **50.23%** at 4,096 pairs. At **8,192 pairs**, three messages earn 63.449682883 dollars against a halfway target of 63.475357565 dollars, a shortfall exceeding 2.5 cents. Four suffice on that same deck. The earlier two-stage target menu alone earns **at least 63.973670085 dollars**, by an exact finite reflection count. Therefore this particular deck requires exactly four messages. At 16,384 pairs the computed three-message fraction is **49.702%**. Eventual insufficiency of three messages, and the asymptotic optimal three-message value, remain open.
For the three-message calculation the dynamic program absorbs at a strip boundary, with missed value bounded by twice the deck's pair count times the one-sided reflection probability. Inside the strip the recurrence uses positive weighted averages and maxima. Under ordinary round-to-nearest binary64 arithmetic, bounding both the local arithmetic error and its accumulation over the remaining draws keeps the error far below the 2.5-cent gap. The supplied program and certificate checker detail the computation. The four-message calculation conditions on the split score and reflects each segment (see the four-message construction above for the four thresholds).
##### What perfect foresight costs on average
The fixed-width optimum was $\lceil\log_2 n\rceil$ bits. Now let the dealer send a **prefix-free** binary codeword before play. A decoder for a word can be any online stopping policy. For perfect play on every shuffle, the smallest possible mean length is
$$
L_n^*=\tfrac12\log_2 n+O(1).
$$
This bound allows the dealer to select any policy that succeeds on the realized deck, including policies that use subsequently revealed cards to identify the peak.
**Lower bound.** Fix one ordinary policy. When it stops at a running record $x$ with $r$ reds and $b$ blacks left, its conditional chance of having selected the global maximum is $(x+1)/(b+1)$. Indeed $x=b-r$, and reflection says the chance of subsequently climbing one additional dollar is $r/(b+1)$. Stopping below the record cannot succeed. Hence the expected value of its success indicator times $(b+1)/(x+1)$, restricted to record stops, is at most one.
Write $H$ for the realized maximum, and on each shuffle choose the successful word of length $\ell$ sent by the dealer. Apply the preceding inequality separately to each decoder, restricting success further to paths assigned to that word. Multiply by the word's Kraft weight and sum. Kraft's inequality gives
$E[2^{-\ell}(b+1)/(H+1)]\le1$. Jensen therefore gives $E\ell\ge E\log_2(b+1)-E\log_2(H+1)$.
At each fixed draw index, the probability that the current balance is a global maximum (ties allowed) is exactly $1/(n+1)$. Rotating the balanced sequence to that index gives a uniform balanced bridge that stays nonpositive precisely on this event, and the Catalan count gives the probability. If the dealer's chosen stop leaves $R$ cards undrawn, the union bound over the last $j+1$ times gives $P(R\le j)\le(j+1)/(n+1)$ for $0\le j\le n$. Thus $R$ stochastically dominates a uniform integer on $0,\ldots,n$. Since $b+1\ge(R+2)/2$, $EH=(4^n/\binom{2n}n-1)/2$, and the logarithm is concave,
$$
E\ell\ \ge\ \frac{\log_2((n+2)!)}{n+1}
-\log_2\left(1+\frac{4^n}{\binom{2n}n}\right)
=\tfrac12\log_2 n-\log_2(e\sqrt\pi)+o(1).
$$
**Upper bound.** The dealer can describe $H$ directly. Use $d=\lceil(\log_2 n)/2\rceil$ fixed bits for the low digits and unary-code the quotient $\lfloor H/2^d\rfloor$ with a terminating zero. The result is prefix-free when the unary portion comes first. Its mean length is at most $d+1+EH/2^d=\tfrac12\log_2 n+O(1)$. The player stops on first hitting the named level.
**52 cards.** Assign zero-peak deals to the instruction “aim for three dollars”, and Huffman-code the instructions for positive peaks. The resulting mean is 3.116571426 bits. We can beat this by changing the instruction attached to the short word for three dollars. Also allow it to stop at one or two dollars if the last red has just appeared and the score equals the record so far. At that point every remaining card is black. The alteration preserves every deal previously served by that instruction. The dealer can reassign some deals whose peak was one or two dollars to the shorter word, saving one bit per reassigned deal. For $h=1,2$, the count with its last red arriving at its peak $h$ is
$\binom{2n-h-1}{n-1}-\binom{2n-h-1}{n-h-2}$ by reflection. This saves **31,872,759,742,852 bits over all 495,918,532,948,104 decks**, lowering the mean to **3.052301273 bits** with perfect play. An independent integer dynamic program gives a lower bound of **2.91309099294 bits** (rounded down). It computes the maximum fraction of shuffles that any $j$ policies can jointly cover. If a code tree has $j$ leaves at or above a given depth, at most that fraction of deals can receive a codeword of that length or shorter. Summing the resulting tail bounds and minimizing over binary tree shapes gives the lower bound. The coverage-maximizing menus across depths may be mutually incompatible, which leaves room to tighten it. In `AdviceCounts.lean`, Lean checks the arithmetic from the stated reflection counts through the code lengths, the 25 Huffman merges, the saved bits and the final upper bound. The script `variable_advice.py` reproduces both endpoints and independently enumerates all policies on decks through three pairs. The optimal mean lies in **[2.91309099, 3.05230128] bits**. [Huffman 1952](https://doi.org/10.1109/JRPROC.1952.273898 "A Method for the Construction of Minimum-Redundancy Codes")
##### The price of the 79-rule on unbounded decks
The earlier policy cashes out when $x>0$ and $79t\le112x^2+109x+14$, where $t$ cards remain. Its boundary is $c\sqrt t+O(1)$ with $c=\sqrt{79/112}$. Let $S_t^0$ denote a sum of $t$ independent fair signs, $p_t(x)=P(S_t^0=x)$, $F_t(x)=P(S_t^00$. The positive edge must be treated separately, and this rule always stops there. Optional stopping of this finite tree therefore gives
$$
E Q_\tau(X_\tau)=\frac{4^n}{2\binom{2n}n},
$$
where $\tau$ denotes the remaining time at exercise. A first crossing, with one-card steps, has $X_\tau=c\sqrt\tau+O(1)$ uniformly. The local binomial approximation gives $p_t(x)=2\phi(c)/\sqrt t+O(t^{-1})$, and the binomial CDF estimate gives $F_t(x)=\Phi(c)+O(t^{-1/2})$ there. Thus $Q_t(x)=A(c)x/(2c)+O(1)$, with $A(c)=\Phi(c)/\phi(c)$ as above. It follows that the policy earns $K(c)\sqrt n+O(1)$, where
$$
K(c)=\frac{\sqrt\pi\,c}{A(c)}
=\frac{\sqrt 2\,c\,e^{-c^2/2}}{1+\mathrm{erf}(c/\sqrt2)}.
$$
Subtracting its coefficient $0.5220376735556426\ldots$ from the optimal $0.5220376759871239\ldots$ gives regret asymptotic to **$2.43148123\times10^{-9}\sqrt n$ dollars**, or **4.65767 parts per billion** of expected optimal winnings. The absolute loss is unbounded. The first finite deck on which it loses a cent remains to be determined. These formulas use $\sqrt n$ for this rule and $\sqrt N$ in the two-mark proof, with $N=2n$ throughout.
###### A bounded rounding error can cost vanishingly few dollars
Let $\alpha=0.8399236757\ldots$ be the optimal Brownian boundary coefficient, equivalently the positive root of $\alpha A'(\alpha)=A(\alpha)$. A rule that first cashes on $x\ge\alpha\sqrt t+O(1)$, using a uniformly bounded boundary shift and always stopping at $x=t>0$, has **absolute expected dollar regret tending to zero**. For example, one may simply use $x>0$ and $x\ge\alpha\sqrt t$.
Here is why every bounded shift disappears to first order. For $z=x/\sqrt t$ on a compact interval, Stirling's formula gives $p_t(x)=2\phi(z)/\sqrt t+O(t^{-3/2})$. By symmetry, $2F_t(x)-1=F_t(x)-F_t(-x)$. For $x>0$ the difference is exactly the trapezoidal sum of the point masses from $-x$ through $x$, on the lattice of step 2, with half weights at the endpoints. The accumulated local mass error and the ordinary smooth trapezoidal quadrature error are both $O(t^{-1})$ on that compact range. Thus $F_t(x)=\Phi(z)+O(t^{-1})$ and $Q_t(x)=\sqrt t A(z)/2+O(t^{-1/2})$. Expanding at $\alpha$ for $x=\alpha\sqrt t+O(1)$ yields $x-2\alpha Q_t(x)/A(\alpha)=O(t^{-1/2})$ because the coefficient of the overshoot is $1-\alpha A'(\alpha)/A(\alpha)=0$.
The probability of first exercising with fewer than any fixed number of cards left tends to zero. Indeed a standard Brownian bridge crosses $(\alpha+\epsilon)\sqrt{1-u}$ before time 1 almost surely, by time reversal and the Brownian law of the iterated logarithm at zero. Choose finitely many test times strictly before 1 that detect such a strict crossing with probability arbitrarily close to one. Joint convergence of the sampled deck scores and the bounded boundary error transfer this conclusion to large decks. At bounded remaining times all errors are bounded. Taking expectations above and using the stopped harmonic identity gives policy value $(\alpha/A(\alpha))4^n/\binom{2n}n+o(1)=K(\alpha)\sqrt n+o(1)$. The finite-deck bounds already give $V_n=K(\alpha)\sqrt n+o(1)$ in absolute dollars, proving the claim. A fixed finite-precision approximation to the slope eventually shifts the boundary by more than a bounded number of dollars. The theorem applies to the true slope or to an implementation with a uniformly bounded boundary displacement.
#### 4.13. Finite three-message pricing and its arithmetic errors
A clairvoyant adviser picks one of three stopping policies before the first draw. The optimal expected return equals the expected best of three adaptive nominations, including an automatic zero fallback. To see this, run the three policies simultaneously and nominate their stops. Conversely, define policy j to stop at the j-th nomination, or at expiry if it never occurs.
Let t be the cards remaining, x the current score, h the highest banked score (initially zero), and k the remaining nominations. The chance of an up-step is p=(t−x)/(2t). At each state take the larger of the conditional expectation after waiting a draw and the value for k−1 at the same state with updated bank max(h,x). Zero nominations pay h, and zero cards remaining pay h. The computation stores two adjacent time layers. Three remaining nominations only require bank zero. The one- and two-nomination layers need all reachable banks.
The implementation requires absorption at |x|=w, where w=min(n,ceil(sqrt(40n))). Upon absorption use an available nomination and cash max(h,x). The resulting policy is feasible. Its value differs from the unrestricted value by at most 2n binom(2n,n+w)/binom(2n,n), since each payoff is in [0,n] and each side of the band has the stated one-sided reflection probability. At w=n the absorption is exact since the rest of the path is forced. Work is O(nw²) and memory is O(w²).
##### Reproduce
Run from this directory with a binary64 implementation using round-to-nearest. Each output row includes the pair count, the band width and the three prices in hexadecimal floating-point notation.
```sh
set -e
c++ -O3 -std=c++17 -ffp-contract=off three_messages.cpp -o /tmp/p14-three
/tmp/p14-three 1 2 3 4 5 6 7 8 26 100 256 512 1024 2048 4096 8192 16384 | python3 check_three_messages.py
```
The checker parses the exact printed binary64 values, independently verifies one through three nominations on decks through eight pairs when provided, and uses rational bounds for its comparison against half. Its prophet price is exactly (4^n/binom(2n,n)−1)/2.
##### Arithmetic certificate
Write u=2⁻⁵³. Integers entering the probabilities, indices and stopping payoffs are exactly representable over the accepted input range. The computed up and down probabilities have absolute errors bounded by u and 2u. For nonnegative continuation operands at most n+1, two rounded multiplications and their rounded addition have total absolute error at most 5(n+1)u, even using only the separate trivial bounds p,q≤1. Using the rounded weights adds at most another 3(n+1)u compared to exact probability weights. The exact weighted average is nonexpansive in the maximum norm, as is taking a maximum. Updating several nominations within one time layer only selects among existing values and freshly computed continuations. Therefore the error at the root relative to exact clipped arithmetic is at most 16n(n+1)u. This bound is below 1 throughout the accepted range, proving by induction that the computed operands never exceed n+1. Unreachable neighboring states used at a forced step have zero weight, or are zero-initialized. No positive subnormal products are needed for this bound: an additive underflow rounding error less than 2⁻¹⁰⁷⁴ is absorbed by the slack in the bound.
At 8,192 pairs three messages earn about 63.449682883, below the midpoint 63.475357565 between ordinary play and the prophet. At 4,096 pairs they remain above the midpoint. At 16,384 pairs they capture between 49.70214% and 49.70215% of the premium. These finite comparisons leave the limit open.
### Appendix 5. Machine implementation and benchmark experiments
#### 5.1. Scalar and vector code, game linkage and performance controls
Section 5 reports the paired timing controls and explains the arithmetic and ABI. This note supplies the original measurement protocol and scalar build experiments. Source worksheet: `derivations/5.1-scalar-and-vector-code-game-linkage-and-performance-controls.md`.
#### 5.2. Certifying the bytes of individual printed records
Lean proves the dollar interval and nearest cent for the **optimal stopping value of the original balanced deck**. At 133,787,000 pairs the interval is [$6,038.215406, $6,038.218246] and the unique nearest cent is $6,038.22.
From the project root, build the Linux x86-64 executable and the full proof graph with Lean 4.19.0 and mathlib v4.19.0. Python 3 and a built or cached mathlib checkout are required.
```bash
set -e
make proof-asm-full MATHLIB=/path/to/built/mathlib4
python3 asmproof/certify_price.py --game --mathlib /path/to/built/mathlib4 \
--exe ./price-asm 133787000 500000000 1000000000000
```
To regenerate the included five numerical examples, including the smallest and largest supported input:
```bash
set -e
python3 asmproof/certify_price.py --game --mathlib /path/to/built/mathlib4 \
--exe ./price-asm --self-test --emit asmproof/CheckedOutput.lean
```
`--game` reuses the compiled graph in `.asm-build/`. The fresh numerical certificates both validate the untrusted output and specialize `P14Entry.printed_game` to the observed inputs. For each output line, `gameDollars` bounds the true game in dollars, `allNearest` covers every nearest-cent convention at a tie, and `roundedCents` explicitly evaluates the round-half-up result or bounds it for an ambiguous line. These statements have no hypotheses about the coefficient, the game value, or the accuracy of a floating-point seed. Two finite Bellman cutoff checks in the imported game proof use Lean's native evaluator, which brings the Lean compiler into the trusted base. The five output checks themselves use kernel `by decide`.
| Pairs | Certified interval in dollars | Nearest cent in dollars |
|---:|---:|---:|
| 133,787,000 | [6038.215406, 6038.218246] | 6038.22 |
| 500,000,000 | [11673.115131, 11673.117310] | 11673.12 |
| 1,000,000,000,000 | [522037.675512, 522037.675988] | 522037.68 |
| 18,446,744,073,709,551,615 | [2242134745.644524, 2242134745.644542] | 2242134745.64 |
| 32,768 | [94.484004, 94.499635] | 94.48 through 94.50 |
The script parses the actual executable's ASCII stdout, checking requested pair counts, their order, punctuation and decimal widths. It converts amounts into integers by removing the decimal point. Independent Python integer routines propose the two square roots and the fifth-root debit. Lean checks the adjacent power inequalities, recomputes both endpoints and cent bounds, and verifies whether the line correctly reports a unique cent or a range. The self-test changes each endpoint by a microdollar, the cent by a cent, and the unique/range label. It requires all four changes to produce false Lean propositions.
For previously captured stdout, use `--replay FILE` with the corresponding pair counts in their original order. `--lean PATH` selects a Lean executable. A lightweight arithmetic-only run requires only Python 3 and Lean 4.19.0. Omit `--game` and `--mathlib` for that mode. Supplying just `--mathlib` adds a general result conditional on the analytic bounds for any candidate real-valued price.
#### 5.3. Repairing an x86 square-root estimate
The 74 bytes in `root_repair.S` implement
```c
struct root_result { uint64_t root, exact; };
struct root_result p14_root_repair(uint64_t lo, uint64_t hi, uint64_t hint);
```
For every $0\le y=2^{64}\mathtt{hi}+\mathtt{lo}<2^{128}$ and **every** unsigned 64-bit hint, the routine reaches its return instruction with $r=\lfloor\sqrt y\rfloor$ in RAX and the indicator of $r^2=y$ in RDX. This includes the all-ones input. Its floor root fits in a word and its mathematical ceiling can equal $2^{64}$.
`X86Root.lean` contains the raw bytes, decoder, projected small-step semantics, and universal theorem `Problem14.X86Root.root_repair_correct`. The decoder calculates each short branch target from its encoded displacement. Each of the two tests multiplies the candidate into RDX:RAX and compares against the two input words, including the low-word borrow. A candidate whose square is too large decrements until feasible. From a feasible candidate the upward loop stops on equality, overflow of the next candidate, or an infeasible next square. The natural-number termination measures are the candidate and the distance to the top of a word. A bad hint can therefore affect running time. The numerical quality of a floating-point hint is unnecessary for the correctness proof.
`X86RootQuote.lean` proves that the two output registers give precisely the quote specification's `floorSqrt`, its exactness flag and its mathematical `ceilRoot`. Both theorems were kernel-checked with Lean 4.19.0 and its standard library.
The CPU model tracks the general registers and flags that affect this routine. Its execution theorem ends at the decoded RET; control transfer to a valid caller and the platform's executable-memory/stack setup use the normal System V AMD64 ABI. The routine accesses no memory before RET. The unsigned instruction meanings used by the model can be checked in the instruction-set manual. [Intel 2023](https://cdrdv2-public.intel.com/774492/325383-sdm-vol-2abcd.pdf "Intel 64 and IA-32 Architectures Software Developer’s Manual, Volume 2")
From this directory with Lean 4.19.0 and GNU binutils available:
```sh
lean -o Quote.olean Quote.lean
lean -o X86Root.olean X86Root.lean
LEAN_PATH=. lean X86RootQuote.lean
python3 check_root_bytes.py /path/to/linked/priceasm
```
The checker assembles the current source and compares the exact symbol bytes in the relocatable object, linked shared library, and optionally the final executable to the literal Lean program. It also checks 15,096 native results against Python’s integer square root. The artifact digest is `04c846401cc896629a5860bb4b036727a106929ec65b3d2adfd6e2882b863d0a`.
#### 5.4. Guarded inverse comparisons and eight-lane batches
`price_batch` accepts the same deck sizes as `price-asm`, from 32,768 through 2⁶⁴−1 cards per color, and prints identical microdollar endpoints. It uses eight AVX-512 lanes on CPUs advertising AVX-512F, DQ, CD and IFMA. Other x86-64 machines, and short final batches, use SSE2 or the scalar assembly. Arrays and the command-line inputs may have any length.
```bash
set -e
make --directory=asmproof/experimental
asmproof/experimental/price_batch 133787000 500000000 1000000000000
asmproof/experimental/bench_batch --test
```
The C API is `p14_batch(count, counts, lower, upper)` in `threshold.h`. Supply three disjoint arrays of `count` unsigned 64-bit words. The output integers count microdollars. The benchmark also exposes `p14_threshold_seeded` and `p14_threshold8_seeded` for testing the fallback with arbitrary seeds. Direct use of the eight-lane entry points requires the listed CPU features. The build uses GCC on Linux x86-64 with binutils and `libm`.
##### Integer certificate
Put \(D=10^{12}2^{32}\), \(k=522037675987123866\), \(Y_0=2^{64}n\), and \(Y_1=Y_0+2^{63}\). Let \(L\) be the lower integer endpoint before subtracting the debit and \(H\) the upper endpoint. An estimated microdollar value \(j\) can be checked using
\[
L\ge j\iff \lceil jD/k\rceil^2\le Y_0,\qquad
H\le j\iff Y_1\le \lfloor jD/(k+1)\rfloor^2.
\]
Each inverse threshold takes a multiply by a constant and a right shift. The constants use 112 fractional bits, enough to give the exact integer thresholds over the accepted domain. Their adjacent values differ by more than 8,192. For either threshold \(t\), the fast path verifies \((t-8192)^2\le Y\le(t+8192)^2\) using one square and shifted additions on 128-bit integers. The two neighboring microdollar values are then the only possibilities. A failed check calls `quote_asm`. The guessed debit is checked against consecutive entries of the verified table and corrected when needed.
`Threshold.lean`, `VectorWords.lean`, `VectorThreshold.lean`, `VectorGuard.lean` and `VectorLane.lean` cover the inverse comparisons, actual limb constants, 52-bit multiply/add decomposition, 32-by-32 square products, modular carries, acceptance band and debit corrections. `VectorEntry.lean` composes the single-lane model. Source-level SSE/AVX intrinsics and the C compiler connect this arithmetic model to the vector executable. The standalone scalar assembly has a separate instruction-level check. All paths assume valid, disjoint memory and the normal masked floating-point exceptions. Floating-point accuracy affects acceptance frequency only.
##### Throughput
Median nanoseconds per quote, on one pinned AMD EPYC 9V74 virtual CPU, GCC 14.2.0 `-O3`, Linux x86-64. Every method processed the same 32,768-element arrays, stored both endpoints, and ran eight repetitions per sample. Seven timed samples used rotating method order. The three data sets were fixed before timing. The reference and matched C implementations were compiled for baseline x86-64. The latter uses the same floating root guesses, integer Newton correction, interpolation tables and exact debit repair as `quote.S`.
| Pair counts | Reference C | Algorithm-matched C | Scalar assembly | Scalar inverse C | AVX-512 batch |
| --- | ---: | ---: | ---: | ---: | ---: |
| Uniform 32,768–65,535 | 435.846 | 27.715 | 25.948 | 22.964 | 9.376 |
| Uniform bit length 16–64 | 320.162 | 26.586 | 22.833 | 21.303 | 6.864 |
| Uniform 64-bit integers | 122.826 | 33.287 | 25.370 | 25.042 | 6.511 |
The default kernel for small scalar tails uses inverse C. Larger scalar tails use assembly. Variation across reruns was comparable to the gap between these two scalar methods on large inputs. An individual CLI call includes process startup, parsing and printing. The reported AVX-512 throughput requires a batch.
```bash
set -e
taskset --cpu-list 7 asmproof/experimental/bench_batch
```
The tests compare with the original integer-only C reference at 589,304 inputs including debit boundaries, near-squares, the upper end of `uint64_t`, all four floating-point rounding modes and deliberately wrong hints. They check tail lengths 0 through 32 with sentinel output words. On a CPU without the vector features, the same command exercises the dispatched scalar routines.
#### 5.5. One-page ELF, header proof, and launch benchmark
##### What fits in 1,771 bytes
The first 64 bytes are the ELF64 header. The next 56 describe one read/execute `PT_LOAD` segment covering the file. At byte 120 Linux enters the assembly argument parser and quote program. All instructions and constants fit in one 4 KiB file-backed page. Linux separately supplies the stack. On successful short runs the executable writes the formatted rows to stdout and exits.
The build uses Python, GNU `as`, and `objcopy`. The assembler resolves the local branches, the build checks that zero relocations remain, and Python writes the ELF headers. The image contains zero section headers, shared libraries, dynamic-linker requests, C runtime startup routines, or writable data segments. The earlier static executable also had zero dynamic-linker requests. Linux uses the ELF `PT_INTERP` program header to select an interpreter when one is requested. [Linux man-pages 2026](https://man7.org/linux/man-pages/man2/execve.2.html "execve(2)")
Most of the space saving came from removing the 14,893-word table in the old assembly arithmetic. For a deck with `n` red and `n` black cards, the correction is the least integer `d` for which `d^5 (2n+1) >= 137000^5`. The new assembly computes the integer quotient `(137000^5 - 1) / (2n + 1)` and searches the 17–14,909 range for the first fifth power above it. A separate division path handles the 65-bit divisor at the top of the input range. The existing square-root repair, endpoint arithmetic, parser, formatter and error behavior are shared with the previous assembly.
| Image | Bytes | Purpose |
|---|---:|---|
| `price-minelf` | 1,771 | General table-free solver |
| `price-flat` | 121,832 | Direct assembly of the previous solver, preserving every instruction, constant and virtual address |
| `price-asm` | 122,120 | Previous stripped assembly executable |
| `price-startup-control` | 3,152 | Previous static assembly launcher with the original C arithmetic |
| `.asm-build/exit-minelf` | 127 | Same header layout plus seven bytes calling `exit(0)` |
##### Fresh-process measurements
The kernel was Linux 6.18.64 on an AMD EPYC 9V74. The harness pinned parent and child to CPU 4. Every child received the same environment, the same `argv[0]`, and the same three pair counts (133,787,000, 500,000,000, and 1,000,000,000,000). The parent opened `/dev/null` once for stdout. All images had equally long paths in the same directory. Timing covers process creation or spawn, `execve`, calculation, formatting, writing, exit, and the parent's wait. There were zero major page faults in these runs.
| Single-threaded caller | General solver | Exit only |
|---|---:|---:|
| `posix_spawn` + `waitpid` | 58.467 µs | 57.406 µs |
| `vfork` + `execve` + `waitpid` | **52.542 µs** | **51.662 µs** |
These are medians of 384 randomized, balanced block means, with 24,576 fresh processes per cell. Paired within blocks, switching the caller saved **4.353 µs** for the solver (95% sign interval 3.612–5.385 µs). With the faster caller, calculating and printing all three prices took **0.823 µs** over the exit control (0.091–1.463 µs). The latter difference includes parsing and I/O. The caller comparison applies when the launching code is under your control.
A separate run interleaved the compact solver, the previous 3,152-byte control, and the exit-only program, all using `posix_spawn`. Medians across 512 blocks were **67.061**, **67.208**, and **64.870 µs**, respectively, with 24,576 launches per image. The paired estimate for the compact solver's saving over the previous control was 1.726 µs (95% sign interval −0.456 to 3.690 µs). This run could not resolve a speedup from shrinking the binary. Absolute latency varied across runs. The paired intervals treat blocks as independent observations, and host load can correlate adjacent blocks.
The archive includes the four raw timing series and the summaries can be reproduced with `python3 minelf/summarize.py minelf/timings/mixed.csv`. Run `bash minelf/bench.sh 4` from the project directory to repeat all four series on CPU 4.
##### Correctness and reproduction
The comparison suite checks 90,786 inputs against independent arbitrary-precision calculations, including every in-range correction transition, the switch between one and two divisions, and the rare correction after 65-bit division. The existing CLI tests exercise invalid input, half-cent endpoints, default arguments, and buffered output. A binary checker resolves the changed reference addresses, compares the shared code against the previous release, and checks the new debit against the Lean instruction records. Flipping the low bit of each of the 1,771 file bytes in succession made every test image fail that check.
Lean decodes each executable’s actual 120 header bytes and proves the entry lies inside its only load segment. It also proves that the first and last loaded bytes of the 1,771-byte version occupy the same 4 KiB page.
The arithmetic proofs cover the two division paths, the exact fifth-power comparisons, bisection and termination on all supported inputs, plus the previous square-root and endpoint arithmetic. The theorem `P14Compact.machine_encloses_game` connects the resulting integer endpoints to the expected payoff for every supported deck. The finite game theorem retains its original two fixed calculations using Lean's native evaluator. The verification assumes the stated x86 instruction semantics, valid call stack and output memory, and the Linux execution interface. An independent certificate checks eight actual printed records byte for byte against the Lean decimal renderer and proves the stated bounds for those decks.
From the extracted `problem14/` directory:
```bash
set -e
make minelf
./price-minelf 133787000 500000000 1000000000000
readelf --file-header --program-headers --wide price-minelf
make check-minelf check-minelf-runtime
make proof-minelf-full MATHLIB=/path/to/built/mathlib4
```
The release binary's SHA-256 is `d7f23945b0d7196dc149faa87209b51f215faed55ad20b8eb1ba1b9b47bf2f7c`. Full proof checking uses Lean 4.19.0 and mathlib v4.19.0.
#### 5.6. Hardwired control, device and resident shell
The hardware and workload, printed records, one-syscall experiment and negative performance results appear in Section 5. The note also gives the controlled executable identities. Source worksheet: `derivations/5.6-hardwired-control-device-and-resident-shell.md`.
#### 5.7. Eight-byte and six-byte decision routines
On a standard 52-card deck the square rule amounts to comparing the signed current score with a threshold indexed by red cards remaining. In AMD64 System V registers, RDI contains the score, RSI the red count (a 64-bit size), and RDX points to the immutable 27-byte table. The caller reads the unsigned byte returned in AL.
```asm
cmp dil, byte ptr [rdx+rsi]
setge al
ret
```
The assembled bytes are `40 3a 3c 32 0f 9d c0 c3`. Including the table costs 35 bytes. Holding its pointer, maintaining the card counts, calling the function, dealing and I/O are outside the count. The table-free `pocket_square` in the same source occupies 21 bytes and takes the current score and total cards remaining. Code size and latency are distinct measurements.
`PocketBytes.lean` models the listed comparison, signed subtraction flags, SETGE and return of AL. Its kernel proof checks equality with `SquareRule.stop` for all 729 legal states. The square-rule proof establishes optimal play. The modeled instructions assume a valid table, a normal stack return and the stated calling convention. The native test compares the linked code and table directly against the Lean byte literals, then exercises both implementations against an independent exact-integer Bellman solver.
Run the native check on Linux/x86-64 with a C compiler and Python 3. To rebuild the Lean result from the project root:
```bash
set -eu
python3 further/machine/check_machine.py
build_dir="$(mktemp --directory)"
export LEAN_PATH="$build_dir"
lean -o "$build_dir/Problem14.olean" Problem14.lean
lean -o "$build_dir/SquareRule.olean" further/rules/SquareRule.lean
lean further/machine/PocketBytes.lean
```
With enough pre-game advice the optimal policy is a first-hitting level supplied by the dealer. This third entry, `pocket_advised`, uses `cmp edi,esi; sete al; ret`: six bytes (`39 f7 0f 94 c0 c3`) and no table. The deal driver stops at the first true return or pays the terminal zero. Lean's `advised_eq` verifies the comparison fragment for every pair of 32-bit register inputs; the native check verifies the emitted bytes and standard-deck scores.
#### 5.8. The integer module ABI and its verification
The kernel implementation uses integer-only arithmetic. This note contains the complete ABI, build and guest recipes, object audit and failure behavior. Source worksheet: `derivations/5.8-the-integer-module-abi-and-its-verification.md`.
#### 5.9. Calling the quote from a resident shell
The resident shell builtin removes process launch. This note gives direct and ioctl benchmark protocols with their controls. Source worksheet: `derivations/5.9-calling-the-quote-from-a-resident-shell.md`.
#### 5.10. Actual device validation in an emulated guest
A disposable Debian Linux guest loaded the built driver, exercised its device ABI, compared 50,969 deck sizes against an independent integer oracle, and unloaded it. The device node disappeared on unload. QEMU powered the guest down successfully.
| Quotes per request | Direct userspace, ns/request | Device ioctl, ns/request | Median paired slowdown | Median paired difference |
|---:|---:|---:|---:|---:|
| 1 | 943.5 | 2,237.0 | 2.397× | 1,295.8 ns |
| 3 | 2,832.4 | 4,043.5 | 1.428× | 1,221.9 ns |
These are QEMU 10.0.13 TCG software-emulation timings. Native module latency remains unmeasured. The ioctl took longer in all 15 paired blocks at both batch sizes. Each block timed 4,096 requests with the device already open. Both userspace and the kernel build used the same integer solver source with their respective compiler flags. The user processes ran directly in the guest. The benchmark alternated which implementation ran first, rotated through 133,787,000, 500,000,000 and 1,000,000,000,000 pairs, and verified output checksums. Its timing includes filling the input fields and consuming both output fields, with formatting, open, boot and module loading outside the timed interval.
The oracle used Python integers and `math.isqrt`. Inputs included all admissible neighbours of the debit transition at each candidate debit from 17 through 14,909, powers of two, random 64-bit inputs and random perfect squares with their neighbours. Every returned endpoint matched. The client checked one-, two- and three-entry requests, output clearing, rejected inputs and inaccessible userspace buffers.
The guest used kernel `6.12.117+deb13-cloud-amd64`, one emulated x86-64 CPU, 256 MiB RAM, a generated RAM filesystem, and a serial console. It had no block drive or network interface. In this run the module SHA-256 was `9059660fe080d3b9f500b5a11ef7f0a96152f891fb1aa50252db8fde7028f769`. The kernel image SHA-256 was `ed8f0dbdbefe3994093937f5ee934818ae902b88cb0b6bc423811c10d55b87b0`.
##### Reproduction
Use a Linux x86-64 kernel image and a matching module-build tree, a static x86-64 BusyBox, QEMU, Python 3, and a compiler with a static x86-64 C library. From this directory:
```bash
set -e
make module KDIR=/path/to/matching/kernel/build
python3 guest_test.py \
--kernel /path/to/vmlinuz \
--module ./p14quote.ko \
--busybox /path/to/static/busybox \
--accel tcg \
--log guest.log
```
The recorded run used Debian packages extracted into a scratch directory. An extra `--bios /path/to/seabios/bios-256k.bin` and `--qemu-data /path/to/share/qemu` located that tree's firmware. The guest console and all timed blocks are in `guest.log`. Each `P14_BENCH` line gives batch size, zero-based block index, request count, direct elapsed nanoseconds, ioctl elapsed nanoseconds and checksum, in that order.
### Finite regret for three exercise policies
Let N be the total number of cards, t the remaining number, and x the current score. The half-card rule stops when x>0 and (2x+1)² ≥ 4α²t, with α=0.8399236756923726896…. The previous hybrid uses 79t ≤112x²+109x+14 for positive x through t=65,536 and a nearest-lattice Brownian boundary thereafter. The third policy in the table keeps the 79 branch and uses the half-card rule thereafter.
| Policy | Maximum dollar regret over every even N from 2 to 482,618 |
|---|---:|
| Half-card throughout | 0.000023218580128… at N=220, unique maximum |
| Previous hybrid | [0.0002634075350, 0.0002634079877] |
| 79 through 65,536, then half-card | [0.000000049632, 0.000000049743] |
The standalone half-card rule attains the exact optimum through 108 cards. At 110 it first loses 2789854560504399388648199 / 1349687925069778859939436617184 dollars. The 79 rule attains the exact optimum on every balanced deck through 4,000 cards. At N=20,000 its loss is about 1.58×10⁻⁹ dollars, compared to 4.49×10⁻⁶ for the half-card rule.
The previous hybrid's actual regret at 65,536 is within [4.1348,4.1436]×10⁻⁸ dollars. At 65,538 it is within [4.1348,4.1440]×10⁻⁸. The eventual peak is between 6,357 and 6,371 times the switch-time regret. The coarse fixed-point estimate in the review locates that peak at 324,112. Its rigorous upper bound there is 0.000263406457 dollars, below the attained lower bound at 326,148. The 52-fractional-bit point estimates peak near 326,148. These 52-bit enclosures alone do not identify a unique maximizing input. The separate 92-bit and heat estimates now isolate the 326,148-card maximum through 8,388,608 cards.
##### Certificate
A single Bellman sweep treats x=0 at every even remaining time as the initial state of a separate balanced deck. For each policy and the optimum, compute their values inside |x|n the probability is zero. The C code checks N·2⁻⁵⁵ bounds the expected dollar loss on the entire supported range. On N≤65536 it uses N·2⁻¹⁰⁰. Both checks use exp(7/10)>2, which already follows from the first five terms of its Taylor expansion.
Use integer payoff units S=2⁵². At each cell, continuing requires the weighted sum v=(t−x)u + (t+x)d, divided by D=2t. Let s=floor(log₂(D−1)) and m=floor(2^(64+s)/D). The implementation obtains floor(vm/2^(64+s)) by splitting v into 64-bit limbs. This underestimates v/D by less than three units: D≤2^(s+1), v≤DwS and wS<2⁶⁴. All intermediate limbs fit their specified unsigned widths. Taking a maximum and applying transition probabilities are nonexpansive, so the error of either root in the clipped game is at most 3N units. Both clipped roots round down. The difference of the two computed roots therefore differs from true regret by at most (3N+ceil(S·tail))/S. The code checks that the certified enclosure 0.83992367569237<α<0.83992367569238 yields the same boundary on every layer.
At N=220 the exact specialized calculation gives the fraction printed in output.txt. It is also the unique worst input throughout the covered range: in units 2⁻⁵² its lower bound is 104567188153, versus largest competing upper bound 104518502216 (at N=218). All finite claims concern balanced starting decks, not arbitrary conditional states at the same remaining time. These calculations alone give no infinite-horizon supremum.
~~~sh
set -e
cc -std=gnu11 -O3 -march=native certify.c -o /tmp/rule-certify
/tmp/rule-certify /tmp/rule-rows.tsv
python3 inspect.py < /tmp/rule-rows.tsv
python3 exact.py
~~~
Rows are N followed by raw, lower, and upper integer-unit regret in each of three consecutive policy columns. Running all three rules at once took 15.3 seconds on one AMD EPYC 9V74 core, GCC 14.2. The exact Python check uses unnormalized integer path totals and Pascal's identity, without numerical truncation or finite precision.
##### Use the rule
~~~sh
set -e
cc -O3 -std=gnu11 half64.c -o /tmp/half64
/tmp/half64 65600 216
python3 half_player.py 65600 216
python3 half_player.py --hybrid 52 0
python3 test_players.py
~~~
The native program accepts a remaining-card count through 2⁶⁴−1 and a signed current score of either sign. The Python program accepts arbitrarily large feasible states. At exhaustion both return stop. The callable native function takes the positive part of the score.
For the whole finite sweep, the chosen dyadic slope and the exact α yield identical decisions. The verifier checks the transition to stopping for both on *every layer*. The native program uses c=13013657395120439157/2⁶⁴, a certified lower approximation to α², and tests (2x+1)²≥4ct. It compares x(x+1) to ceil(ct−1/4) via the two limbs of its single 64×64-bit product. If x≥2³²−1 the comparison is always true for a valid 64-bit deck. The exact integer inequality (0.83992367569238−1/(256·2³²))² ≤ c ≤ 0.83992367569237² proves 0≤(α−√c)√t≤1/256 on this domain.
Beyond uint64, the Python player selects k=ceil(bit_length(t+1)/2)+10. The Taylor series of A and the negative derivative of the root residual produce a certified bracket [l,h] for α of width ≤2⁻ᵏ. It uses c=floor(2ᵏl²)/2ᵏ. Consequently 0≤α²−c<3·2⁻ᵏ and (α−√c)√t<3/1024<1/256, because α+√c>1. Equalities can be decided with integers even at a possible exact threshold tie. The analytic argument in contact.md permits this tiny downward displacement for all later times. It covers the exact-slope policy and the executable; they may make different decisions outside the verified finite range.
### The half-card boundary at unbounded horizons
Let $T=65536$, $s=\sqrt{t+1}$ for $t\ge T$, and let $\alpha$ be the Brownian stopping constant.
Put $\ell=.83992$, $h=.83993$; the previously verified root bracket gives $\ell<\alpha.70$ and $\sqrt{c_t}+\alpha>1$, so the difference in (1) is at most $\sqrt{t}/(256s)$.
The same condition holds if $0\le\alpha-\sqrt{c_t}\le 1/(256s)$.
The exact slope is allowed.
Let $B_t$ be the smallest positive integer of the same parity as $t$ with $B_t+1/2\ge\rho_t$.
Write $Q_t=c_*F_t/p_t$ for the unconditioned fair walk's midpoint CDF divided by its point mass, multiplied by $c_*=2(1-\alpha^2)$.
Write $R_t$ for the fractional harmonic function with $p=2/5$ and $J_t(x)=[x^3-(3t-2)x]/[t(t-1)(t-2)]$, as in Appendix 2.10.
**Claim.** At every $t\ge T$, $s[Q_t(B_t)-B_t]<1.744<(17/8)sB_t/t$, $R_t(B_t)>0$, and $J_t(B_t)<0$.
Consequently, for every $a\ge17/8,\ \kappa,\lambda\ge0$, the harmonic comparison
$$
H_t(x)=Q_t(x)-a x/t+\kappa J_t(x)-\lambda R_t(x)
$$
satisfies $H_t(B_t)\le B_t$.
Optional stopping can therefore use the cash payoff at first contact. The surviving states at the finite cutoff use their separate payoff comparison.
**Rounding and reachability.**
Parity gives $\rho_t-1/2\le B_t<\rho_t+3/2$.
With $y=(B_t-1)/s$, $\delta=y-\alpha$, this implies
$$
-2/s<\delta<1/(2s).
$$
Indeed $\alpha(s-\sqrt t)=\alpha/(s+\sqrt t)$ and $3/2+1/256+\alpha/(s+\sqrt t)<2$.
In particular $0\alpha s-1$, and therefore
$$
(17/8)sB_t/t>(17/8)(\ell-1/256)=11369787/6400000>1.7765.
$$
**Exact derivative bounds.**
Put $A(y)=\int_0^\infty e^{yu-u^2/2}du$, $b=1-\alpha^2$, $f=bA$, $g=f-y$.
Integration by parts gives $f'=b+yf$. The defining root equation then gives $f(\alpha)=\alpha$, $f'(\alpha)=1$.
All derivatives of $f$ are positive by differentiation under its integral.
Let $v=.843$, $d=v-\ell$, $\bar b=1-\ell^2$.
Since $f'$ is increasing,
$$
f(v)\le\alpha+(v-\alpha)f'(v)\le h+d\{\bar b+v f(v)\}.
$$
Set $F_0=(h+d\bar b)/(1-dv)$, $F_1=\bar b+vF_0$, $F_2=F_0+vF_1$, $F_3=2F_1+vF_2$, and $F_4=3F_2+vF_3$.
Differentiating the ODE gives $f^{(j)}(v)\le F_j$, and exact rational arithmetic gives
$$
F_2=\frac{105376567144193}{62337722500000}<1.691,\qquad
F_4=\frac{496663942043882611257}{62337722500000000000}<7.968.
$$
**Taylor contribution.**
The midpoint binomial beta integral gives the exact identity
$$
Q_t(B_t)-B_t=sg(y)+g'(y)+b(s+y)\{I_s(y)-A(y)\},\qquad
I_s(y)=\int_0^\infty e^{yu}\operatorname{sech}(u/s)^{s^2}\,du .
$$
If $\delta\le0$, put $D=-\delta\le2/s$. Then
$$
sg(y)+g'(y)=\int_0^D(sv'-1)f''(y+v')\,dv'.
$$
The constant $f''(y)$ contributes $f''(y)(sD^2/2-D)\le0$. On this interval $\lvert sv'-1\rvert\le1$. By the mean value bound and $f'''(\alpha)=2+2\alpha^2$,
$s^2g(y)+s g'(y)\le sD^2 f'''(\alpha)/2<7/s$.
If $\delta\ge0$, the facts $g(\alpha)=g'(\alpha)=0$ and $s\delta\le1/2$ give
$$
s^2g(y)+s g'(y)\le\{(s\delta)^2/2+s\delta\}F_2
\le(5/8)F_2<1.057.
$$
Hence $1.057$ bounds both cases.
**Laplace contribution.**
Write $D(u)=u^2/2-s^2\log\cosh(u/s)$. The inequalities $v'-v'^3/3\le\tanh(v')\le v'$ for $v'\ge0$, followed by integration, give $0\le D(u)\le u^4/(12s^2)$.
For $0\le u\le12$, use $e^{D(u)}-1\le D(u)e^{1728/s^2}$.
After multiplication by $s b(s+y)$, the integral over this region is at most
$$
(1+1/s)e^{1728/s^2}f^{(4)}(v)/12
\ \le\ (1+1/256)F_4/[12(1-1728/256^2)]<.685.
$$
This replaces the exponential by $1/(1-z)$ for $0\le z<1$.
For $12\le u\le s$, $D(u)\le u^2/12$ and $e^{D(u)}-1\le D(u)e^{D(u)}$.
Use $yu\le u^2/12$ and $4\log u\le u^2/12$ for $u\ge12$.
Thus $u^4e^{yu-5u^2/12}\le e^{-u^2/4}\le e^{-3u}$, and the scaled contribution is at most $(1+1/256)e^{-36}/36$.
For $u\ge s$, convexity gives $\log\cosh(u/s)\ge u/(3s)$, using $\cosh(1)>3/2>e^{1/3}$.
As $y\le s/12$, the integrand in $I_s$ is at most $e^{-su/4}$.
The scaled tail is bounded by $4(s+1)e^{-s^2/4}$, decreasing for $s\ge256$.
Together the last two bounds are below .001, for instance by $e>2$.
This proves $s b(s+y)(I_s(y)-A(y))<.686$.
Combining with the Taylor contribution gives $s(Q_t(B_t)-B_t)<1.743<1.744$.
**Signs of the remaining corrections.**
We have
$$
00$ at every physical grid point with $0\le x/\sqrt{t-2/5}\le.85$ and $t\ge16384$; its estimate uses only this normalized argument range.
The same bound implies $B_t^2<3t-2$, so $J_t(B_t)<0$.
This proves the stated comparison.
##### Pointwise cutoff inequalities for the two half-card policies
The companion contact.md supplies the analytic contact inequality for all t above the cutoff T. This note gives the terminal condition, integer evidence, and central regret arithmetic. Write Q=cF/p for the mid-CDF harmonic function with c=2(1−α²), J=(x³−(3t−2)x)/(t(t−1)(t−2)), and R for the earlier normalized fractional coefficient of order 2/5.
For each reachable x below the half-card exercise boundary at T, the standalone verifier checks the terminal policy payoff is at least Q−(17/8)x/T+κJ−λR. It reaches every one of these scores, including the extreme negative physical edge. On states at the exercise boundary the policy cashes immediately. The earlier all-time upper comparison gives V_N ≤ Q_N(0) for balanced starts N≥3600. The preceding contact estimate and positivity proof give, by optional stopping, regret ≤λR_N(0) for N≥T. Here J(0)=0 and R_N(0) decreases in even N.
| T, cards | Cutoff policy | κ | Certified λ at most | Certified R_T(0) at most |
|---:|---|---:|---:|---:|
| 482,618 | half-card | 135,000 | 0.194547099 | 873941876893/2⁴⁴ |
| 482,618 | 79 then half-card | 135,000 | 0.194501683 | 873941876893/2⁴⁴ |
| 1,048,576 | half-card | 300,000 | 0.179780061 | 748318041695/2⁴⁴ |
| 1,048,576 | 79 then half-card | 300,000 | 0.179735647 | 748318041695/2⁴⁴ |
The first two rows give a common upper bound of $0.009664681 above T. The last two rows give $0.007647297 above T for either policy, and the extended finite sweep handles all smaller decks. The finite sweep is tighter below either cutoff. Combining the terminal bounds with the analytic contact and R positivity proves this common all-size ceiling.
The cutoff policy DP uses direct downward 2⁻³² rounding for a weighted mean of children. More precisely, multiply its weighted sum v by floor(2⁶⁴/t) and take the high 64 bits. At the artificial lower wall force zero, the full game's terminal payoff. The actual policies only realize nonnegative payoffs, so this can only lower the bound. Positive exercise decisions are checked against the exact bracketing rationals for α, and all legal scores at or above the first exercise score stop. The exercise-boundary increment is checked against these exact predicates every layer. All preceding value estimates lie below 2048·2³² and every sum v fits in uint64 even at the maximal allowed T. The edge t=1 has no interior continuations.
The implementation bounds R and F/p by outward fixed-point recurrence from the most negative physical score in $2^{-44}$ units, as in the original cutoff79.c. For every survivor it checks R>0 and upper-bounds the needed ratio (Q−(17/8)x/T+κJ−lower policy payoff)/R, rounding upwards to billionths. The ratio may be negative, in which case no deduction is required. Computing all cubic, tilt, fractional-CDF and divisional intermediates uses integer arithmetic; quotient conversion ranges are asserted. The main cutoff compares all 241,601 survivor scores for each policy. The larger cutoff compares 524,718.
~~~bash
set -e
cc -O3 -std=gnu11 cutoff.c -o /tmp/half-cutoff
/tmp/half-cutoff 482618 17 1 135000
/tmp/half-cutoff 482618 17 2 135000
/tmp/half-cutoff 1048576 17 1 300000
/tmp/half-cutoff 1048576 17 2 300000
cc -O3 -std=gnu11 -DEXTEND certify.c -o /tmp/extend
/tmp/extend
~~~
The default finite sweep's bound at the 220-card unique maximum also holds in the extended run through 1,048,576. The extended finite sweep uses walls at ±4094 and tail bound N·2⁻⁴⁵ above 65,536 cards; the payoff scale stays at 2⁵². The full extended sweep took 44.0 seconds on one AMD EPYC 9V74 core with GCC 14.2.
Together these contact and terminal comparisons give an all-deck expected dollar loss strictly below 0.007647297 for the half-card rule and 0.007645408 for 79 followed by the half-card correction. The large cutoff is 1,048,576 cards. Both mixed and unmixed calculations use the cubic weight 300,000. The mixed multiplier is at most 179735647/10⁹ and the unmixed multiplier at most 179780061/10⁹. Multiplying each by 748318041695/2⁴⁴ gives the displayed strict upper bounds. All larger even central coefficients decrease. The finite directed sweep covers the complementary decks. The half-card decision uses the exact coefficient or the distributed downward dyadic approximation, whose decisions coincide throughout the finite certificate and whose exercise contact obeys the displacement allowance thereafter.
### Fractional caloric comparisons and the critical exponent
Let $V_n$ be the optimal fair price with $n$ cards of each color, $\alpha$ Shepp's positive root, $K=(1-\alpha^2)\sqrt\pi$, and
$$
Q_{2n}(0)=(1-\alpha^2)4^n/\binom{2n}{n},\qquad \Delta_n=Q_{2n}(0)-V_n.
$$
**Theorem.** The gap is bounded above and below by positive constants times $n^{-p_*/2}$. If $p_*$ is the first positive zero of $p\mapsto D_p(-\alpha)$, then
$$
\lim_{n\to\infty}\frac{\log\Delta_n}{\log n}=-\frac{p_*}{2},
\qquad p_*/2=0.23116668673448591914917012465\ldots .
$$
The first pair of barriers gives, for each $0
0$.
Substitute $u=2z/(1+z)$ and multiply by $(1+z)^t$.
With falling factorials and $0\le m\le t$, this gives exactly
$$
R_t^{(p)}(2m-t)=1-\sum_{k=1}^m 2^k a_k (m)_k/(t)_k .
$$
Hence $R\le1$ everywhere on the deck and decreases in $m$.
The same expansion one coefficient beyond the positive physical edge gives $C_{t,t+1}^{(p)}=-2^{t+1}a_{t+1}<0$: terms with $k\le t$ are polynomials of degree at most $t$, and only $k=t+1$ contributes.
Negative-index coefficients vanish.
In particular $-R$ is a **supermartingale** on the entire deck: discarding the impossible positive neighbor discards a positive numerator for $-R$.
2. **The central power and the boundary profile.** If $x/\sqrt{t}\to y$ along compatible parities, then
$$
t^{p/2}R_t^{(p)}(x)\to
r_p(y)=\sqrt{2/\pi}\, e^{y^2/2}\int_0^\infty u^p e^{-u^2/2}\cos(yu+p\pi/2)\,du
=e^{y^2/4}D_p(-y).
$$
Indeed Fourier coefficient extraction gives
$b_t(x)R_t(x)=(2/\pi)\int_0^{\pi/2}(\sin\theta)^p(\cos\theta)^{t-p}\cos(x\theta+p\pi/2)\,d\theta$.
Substitute $u=\sqrt t\,\theta$.
The scaled integrand is bounded by $u^p e^{-u^2/4}$ once $t\ge2p$; dominated convergence and the lattice local CLT, with lattice span two, give the first equality.
In particular $R_{2n}^{(p)}(0)\sim r_p(0)(2n)^{-p/2}$ with $r_p(0)>0$.
3. **The first zero changes sign.** A useful representation, for $0
0$ below it and $r_p(\alpha)<0$ above it.
##### Two barriers for the gap
**Upper bound on the gap.** Let $B_t$ be the parity-compatible integer nearest $\alpha\sqrt{t+1}$, ties upward.
Appendix 2.10 proves $Q_t(B_t)-B_t\le B_t/t$ for $t\ge16384$.
Fix $p0$ for every sufficiently large $t$.
Choose a single even $T$ beyond that point.
At $t=T$ all states $x\le B_T$ have strictly positive $R^{(p)}_T(x)$ by monotonicity.
There are finitely many, so choose $L>0$ large enough that
$$
H_T(x):=Q_T(x)-x/T-LR_T^{(p)}(x)\le V(T,x)\quad(x\le B_T).
$$
At earlier exercise opportunities, $H_t(B_t)\le B_t$.
Start at $(2n,0)$, hit $B_t$ or switch to optimal play at $T$.
The boundary and score each move by one, so every first crossing is at equality.
On every state where the strategy continues, $Q_t$, $x/t$ and $R_t$ are harmonic, including at the negative edge; it never continues on the positive edge.
Optional stopping yields $V_n\ge Q_{2n}(0)-L R_{2n}^{(p)}(0)$.
**Lower bound on the gap.** Use the majorant in Appendix 2.10 $M_t$, specified for all states by its heat numerator
$$
b_t(x)M_t(x)=b_t(x)Q_t(x)+0.55[b_t(x-4)-b_t(x-2)]
+0.14[b_t(x+2)+b_t(x-2)-2b_t(x)].
$$
Appendix 2.10 establishes that $M\ge0$ is a deck supermartingale, $M_{2n}(0)\le Q_{2n}(0)$, and $M_{3600}(x)-V(3600,x)>1/500$ at every physical score.
Its obstacle proof is strict at every feasible $(t,x)$ for $t\ge3600$.
For $x<0$ use nonnegativity.
At $x=0$ positivity follows from the original nonnegative heat data with a strictly positive central entry $1-\alpha^2-0.28$.
For $1\le x\le3$ the proof gives $Q\ge(1-\alpha^2)\sqrt t$ and $M-Q>-1$.
For $x\ge4$ its perturbation $M-Q$ is strictly positive, and strictly exceeds $\alpha/\sqrt{t+1}$ in the only strip where $Q$ can undershoot cash, by at most that amount.
These inequalities are the finite-cutoff and obstacle results in Appendix 2.10, under “The upper endpoint”.
Fix $p_*x$ gives a positive minimum margin and $R\le1$; choose $\lambda>0$ smaller than that margin and $1/500$.
Consequently $M-\lambda R^{(q)}$ dominates cash on all layers above the cutoff and dominates the Bellman value at the cutoff.
It is a supermartingale by property 1.
Backward induction gives $V_n\le M_{2n}(0)-\lambda R_{2n}^{(q)}(0)\le Q_{2n}(0)-\lambda R_{2n}^{(q)}(0)$.
Property 2 at zero and limits $p\uparrow p_*,q\downarrow p_*$ prove the theorem.
##### At the critical exponent the bounds match
In fact $\Delta_n=\Theta(n^{-p_*/2})$.
The following argument removes the exponent slack without presuming a convergence rate for the optimal boundary.
Write $p=p_*$ and $r=r_p$.
The profile approximation sharpens uniformly on each compact range $|y|=|x|/\sqrt t\le A$ to
$$
t^{p/2}R_t^{(p)}(x)=r(y)+O_A(1/t).
$$
For $u\le\sqrt t/2$ Taylor bounds give an error at most $C(u^2+u^4)/t$ between $(t-p)\log\cos(u/\sqrt t)$ and $-u^2/2$, while each exponential is at most $e^{-u^2/4}$.
Also $|(\sin v/v)^p-1|\le C v^2$ for $0\le v\le1/2$.
The integrated scaled Fourier numerator error is therefore $O(1/t)$, uniformly even in its oscillatory phase; both tails beyond $\sqrt t/2$ are exponentially small.
Stirling's formula gives $\sqrt t\,b_t(x)=\sqrt{2/\pi}e^{-y^2/2}(1+O_A(t^{-1}))$ on the same compact sets.
The Laplace representation gives $r'(\alpha)<0$ by differentiation since $\Gamma(-p)<0$.
Consequently a fixed nonzero lattice displacement from $\alpha\sqrt{t}$ controls the sign for all large $t$.
For the **upper bound on the gap**, use
$$
S_t^-(x)=C_{t+2,m}^{(p)}/\binom t m
=R_{t+2}^{(p)}(x-2)\binom{t+2}{m}/\binom t m.
$$
This is harmonic wherever the lower policy continues.
At $x=B_t$, the shifted score satisfies $B_t-2\le\alpha\sqrt{t+2}-1$ and is within four units of $\alpha\sqrt{t+2}$.
The strengthened profile gives strict positivity at $B_t$ for all large $t$; monotonicity of $R_{t+2}$ gives strict positivity at every score below it, including the physical negative edge.
The same finite-cutoff argument with $Q_t-x/t-LS_t^-$ applies.
At the origin the binomial ratio tends to 4, so $S_{2n}^-(0)\sim4r(0)(2n)^{-p/2}$.
For the **lower bound on the gap**, set $S_t^+(x)=C_{t-2,m}^{(p)}/\binom t m$.
Put $k=t-2$.
If $m\le k$, this is $R_k^{(p)}(x+2)\binom{k}{m}/\binom t m$, and the binomial ratio lies in $(0,1]$.
If $m=k+1,k+2$, its numerator is negative.
The positive-edge ghost at $m=k+3$ is negative as well.
Indeed the three coefficients in order equal $-2^{k+1}a_{k+1}$ times
$$
1,\qquad 2u_1-1,\qquad 1-4u_1(1-u_2),\qquad
u_1=(k+1-p)/(k+2),\quad u_2=(k+2-p)/(k+3).
$$
All factors are positive for $k\ge6$.
These expressions follow by extracting coefficients just beyond degree $k$ in the expansion in property 1.
The negative-edge ghost vanishes.
Hence $S_t^+\le1$ on the deck and $-S_t^+$ is superharmonic on all layers needed here.
At the first parity point $x\ge\alpha\sqrt t-3/2$, the shifted score $x+2$ lies between $\alpha\sqrt{t-2}+1/2$ and $\alpha\sqrt{t-2}+3$ for all sufficiently large $t$.
The strengthened local estimate gives $R_{t-2}^{(p)}(x+2)<0$ there.
Its monotonicity and the two physical fringe signs yield $S_t^+(x)\le0$ for every higher score.
At $x\le-1$, $M_t-x\ge1$.
For $0\le x\le3$, $M_t-x\to\infty$.
It remains to check $x\ge4$ with $S_t^+(x)>0$.
Set $s=\sqrt{t+1}$, $d=\alpha s-x$, $y=(x-1)/s$, $h=\alpha-y=(d+1)/s$; the preceding sign check forces $d\ge3/2$.
As in Appendix 2.10, $M\ge Q$ here and $Q_t(x)-x\ge s g(y)+g'(y)$ for $g=f-\mathrm{id}$.
Since $f''$ is increasing and $g'(\alpha)=g(\alpha)=0$,
$$
g(y)=\int_y^\alpha(v-y)f''(v)dv\ge\tfrac h2[-g'(y)],\qquad
-g'(y)\ge h f''(0).
$$
Thus $M_t(x)-x\ge f''(0)(d^2-1)/(2s)\ge c d^2/s$ for a fixed $c>0$.
The shifted argument $y'=(x+2)/\sqrt{t-2}$ ranges in a fixed compact set and $|y'-\alpha|\le C(d+1)/s$.
The strengthened profile and $r(\alpha)=0$ give $(S_t^+(x))_+\le C't^{-p/2}(d+1)/s$.
For large $t$ this is less than $M_t(x)-x$, uniformly for $d\ge3/2$.
On the finite interval back to the original 3,600-card cutoff take a sufficiently small positive multiplier as before.
Now $M-\lambda S^+$ is a supermartingale dominating stopping, and $S^+_{2n}(0)\sim r(0)(2n)^{-p/2}/4$.
This proves the matching lower bound on the gap.
Neither comparison fixes the relation between its two constants.
The existence and value of $\lim n^{p_*/2}\Delta_n$ and the stronger remainder $o(n^{-1/2})$ are separate questions.
##### Replication and related results
Independent 50-digit evaluations of the parabolic-cylinder function and the Fourier integral give $p_*=0.46233337346897183829834024930715\ldots$.
A 4,000-panel midpoint calculation gives $0.4623386388\ldots$; the integrand behaves as $u^p$ at the origin and its derivative there is singular.
The difference matters when fitting an amplitude across several decades.
For the conventional differential equation and initial values see [NIST n.d.](https://dlmf.nist.gov/12.2 "Parabolic cylinder functions: differential equations").
The table shows $n^{p_*/2}(Q_{2n}(0)-V_n)$.
Each price interval was independently regenerated using the release's integer `heat` solver with a $10^{-12}$ truncation budget and cross-checked against the separate Catalan solver.
The transformation uses the full central-binomial ratio; only evaluation of the special-function constants uses high-precision numerical arithmetic.
Table bounds are rounded outward to the displayed decimals.
| Pairs $n$ | Lower | Upper |
|---:|---:|---:|
| 100 | 0.1038459674 | 0.1038459675 |
| 1,000 | 0.1029383065 | 0.1029383067 |
| 10,000 | 0.1026865688 | 0.1026865689 |
| 100,000 | 0.1026180714 | 0.1026180720 |
| 1,000,000 | 0.1025982872 | 0.1025983087 |
| 5,000,000 | 0.1025932503 | 0.1025935742 |
| 10,000,000 | 0.1025915353 | 0.1025925909 |
The scaled sequence changes slowly and a limiting amplitude near $0.1026$ is plausible.
No value in the table is a limit estimate with a certified truncation error in $n$.
For example, fitting the 1M and 5M midpoints with an assumed additional $n^{-1/2}$ term in the scaled sequence gives an extrapolated amplitude near $0.1025895$; that extrapolation is model-dependent.
Stirling gives the Wallis correction $K/(8\sqrt n)$ for $Q$ itself.
To establish the proposed three-term formula one would additionally have to show $\Delta_n-Cn^{-p_*/2}=o(n^{-1/2})$, which is substantially stronger than convergence of the scaled quantity.
Using the trial amplitude $0.102595$ and the corrected exponent predicts $52.1922173471$ at 10,000 pairs, about $1.09\cdot10^{-5}$ above the checked value.
Gwern's last regression used the 22,974 reported nonzero values together with 100,000 and 133,787,000 pairs.
The large final observation has high leverage.
The published data reproduce intercept $-0.01462286175$ and slope $0.52204803791$.
At the identical design points the three-term formula with amplitude $0.102595$ gives $-0.01374880836$ and $0.52205258555$.
The spectral correction accounts for the sign and approximate size of the intercept; this regression does not identify an exponent or an amplitude.
[Gwern et al. 2022](https://gwern.net/problem-14#approximating "Problem 14 Dynamic Programming Solutions").
For a one-sided, prescribed square-root barrier the analogous exponent is a first-passage theorem.
Uchiyama treats Brownian motion, and Denisov, Sakhanenko, Terveer and Wachtel give the exact random-walk survival tail; their lower-barrier convention uses $c=-\alpha$ after reflection.
Breiman's classical paper treats exit through **two** symmetric barriers in its main asymptotic theorem.
These results motivate the eigenvalue; the comparison above supplies the separate link to the optimal urn price.
Simons's numerical asymptotics concern the urn's stopping boundary, a different quantity from its fair-price deficit.
[Uchiyama 1980](https://doi.org/10.1007/BF00535355 "Brownian first exit from and sojourn over one sided moving boundary and application") · [Denisov et al. 2025](https://arxiv.org/abs/2501.04554 "Random walks with square-root boundaries: the case of exact boundaries") · [Breiman 1967](https://projecteuclid.org/ebooks/berkeley-symposium-on-mathematical-statistics-and-probability/Proceedings-of-the-Fifth-Berkeley-Symposium-on-Mathematical-Statistics-and/chapter/First-exit-times-from-a-square-root-boundary/bsmsp/1200513456 "First exit times from a square root boundary") · [Simons 1987](https://doi.org/10.1016/0167-7152(87)90025-3 "Easily determining which urns are ‘favorable’").
The companion `review/spectral_check.py` checks the roots by two methods, verifies representative fractional coefficients by exact rational convolution, and prints the scaled endpoint calculations.
Use `--heat /path/to/heat` to regenerate all seven Bellman certificates or `--observations bottomup-values0to22974.txt` to reproduce the observed and fitted regression coefficients.
### A sharpened prefix converse and the cost of coding a peak
The ballot–Kraft lower bound can be evaluated to constant order. The entropy of the peak and its one-shot Huffman length have distinct constant terms. For the optimum over all online decoder policies the resulting rigorous bounds, in bits, are
$$
-1.026321953\le\liminf_n (L_n^*-\tfrac12\log_2 n)
\le\limsup_n (L_n^*-\tfrac12\log_2 n)\le0.945139462.
$$
Here $n$ counts pairs. The improvement over the published lower constant is 1.242121153 bits. No independence between the peak and its location is used.
##### Lower bound and the two logarithms
Let $H$ be the maximum of the balanced walk, $J$ its last maximum time, and $b_*=(2n-J+H)/2$ the number of blacks remaining then. Every successful decoder stops at a maximum with at least $b_*$ blacks left. The existing ballot–Kraft inequality gives $E\ell\ge E\log_2(b_*+1)-E\log_2(H+1)$.
The bridge invariance principle and the continuity of last-argmax at a continuous path with unique maximum give $J/(2n)\Rightarrow U$, uniform on $[0,1]$. Uniformity also follows from cyclic invariance of the Brownian bridge and uniqueness of its maximum. Reflection gives $H/\sqrt n\Rightarrow Y$ with $\Pr(Y>y)=e^{-y^2}$, so $(b_*+1)/n\Rightarrow 1-U$. [Vervaat 1979](https://doi.org/10.1214/aop/1176995155 "A relation between Brownian bridge and Brownian excursion")
Natural logarithms suffice for checking integrability. At every deterministic vertex, including the last one, the probability of being a global maximum is $1/(n+1)$ by cyclic rotation and the Catalan count. Since $2n-J+2\le2(b_*+1)$, a union bound over the last vertices gives $\Pr((b_*+1)/n\le a)\le2a$ for $a\in(0,1)$. This bounds the negative log tail by $2e^{-u}$; its positive part is bounded. For $R_n(k)=\Pr(H\ge k)$,
$$
R_n(k)=\prod_{i=0}^{k-1}\left(1-\frac{2i+1}{n+i+1}\right),
\qquad 1-R_n(k)\le k^2/n.
$$
Thus $\Pr((H+1)/\sqrt n\le a)\le a^2$, bounding the negative log tail by $e^{-2u}$. The exact formula for $EH$, or the reflection tail $R_n(k)\le e^{-k^2/(2n)}$, uniformly controls the positive log tail. Both logs converge in mean under the usual representation coupling, and their expectations converge without coupling. Since $E\ln(1-U)=-1$ and $E\ln Y=-\gamma/2$, the lower constant is $(\gamma/2-1)/\ln2=-1.02632195225$.
##### Entropy, coding lengths, and the one-shot correction
The peak mass is $p_h=R_n(h)(2h+1)/(n+h+1)$. The tails satisfy $\Pr(-\ln R_n(H)\ge u)\le e^{-u}$ by monotonicity of $R_n$. Local convergence $R_n(\lfloor y\sqrt n\rfloor)\to e^{-y^2}$ is uniform on compact $y$-intervals. Consequently $E[-\ln R_n(H)]\to E Y^2=1$. Also $E\ln(1+(H+1)/n)\to0$, and replacing $H+1$ by $H+1/2$ inside its logarithm costs $o(1)$ by bounded convergence in probability. Taking logs of the displayed mass yields
$$
H_2(H)=\tfrac12\log_2 n+h_*+o(1),\qquad
h_*=(1+\gamma/2)/\ln2-1=0.859068129527.
$$
A constructive one-shot code achieves at most $H_2(H)+\delta+p_{\max}$, with $\delta=1-\log_2(\ln2)-1/\ln2=0.086071332056$. Write $-\log_2 p_i=k_i+s_i$, with $0\le s_i<1$. Start each length at $k_i+1$. Fractionally shortening it to $k_i$ by the fraction $u_i=2^{1-s_i}-1$ exactly exhausts Kraft's budget in aggregate; the per-symbol mean redundancy is $2-s_i-2^{1-s_i}\le\delta$. Instead maximize saved mean length under the same Kraft budget by greedy fractional knapsack. Keep only whole shortenings, losing at most the single fractional item's probability. Kraft's theorem supplies the desired binary prefix code. Here $p_{\max}\le3/\sqrt n$ by the reflection bound. This yields the asserted upper constant for arbitrary advising policies. The general redundancy bound is classical. [Gallager 1978](https://doi.org/10.1109/TIT.1978.1055959 "Variations on a theme by Huffman")
The distinction persists at constant order. For any code set $q_i=2^{-\ell_i}$ and $\phi(v)=v-1-\ln v$. Kraft gives $(E\ell-H_2)\ln2\ge\sum_i p_i\phi(q_i/p_i)$. Whenever $s_i\in[1/4,3/4]$, $\phi(q_i/p_i)\ge\phi(2^{-1/4})>0$. On $1\le y\le2$, $f(y)=2ye^{-y^2}$ is decreasing and $q(y)=-\log_2 f(y)$ traverses more than three unit periods. Its derivative is at most $7/(2\ln2)$, and $f\ge4e^{-4}$. For any phase shift at least 1.5 units of this interval of q-values have fractional part in $[1/4,3/4]$. The local limit $\sqrt n\,p_h\to f(h/\sqrt n)$ is uniform on this compact interval. Passing to convergent subsequences of the phase $\{\tfrac12\log_2 n\}$ gives
$$
\liminf_n(L_{\rm peak,Huff}-H_2(H))\ge (12/7)e^{-4}\phi(2^{-1/4})>0.0004453\text{ bits}.
$$
Thus the entropy constant does not give even a valid asymptotic upper constant for coding the exact peak by itself. A dealer with arbitrary online decoders may of course do better than coding the peak.
##### Exact subsequential expression for direct peak coding
Along $\{\frac12\log_2 n\}\to\theta$, put $T=\theta-\log_2 f(Y)$. Let $a\in(0,1)$ solve $E[2^{\{T+a\}-a}]=1$. The left side decreases continuously and strictly from above one to below one: the fractional phase has no atoms and meets every open arc with positive probability. For $I_h=-\log_2 p_h$, the trial lengths $\lfloor I_h+a\rfloor$ have Kraft sum $E2^{\{I_H+a\}-a}$, converging to the displayed quantity by the compact local limit, tightness and absence of phase atoms. Increasing $a$ by an arbitrarily small positive amount therefore gives a valid asymptotic upper bound. Conversely, for any integer length $l$, minimizing $p_h l+2^a2^{-l}$ gives $l=\lfloor I_h+a\rfloor$, with harmless ties. Summing this pointwise lower bound and using Kraft proves
$$
L_{\rm peak,Huff}-H_2(H)\longrightarrow a-E\{T+a\}.
$$
In numerical evaluations the excess at phases $0,1/4,1/2,3/4$ is respectively 0.03709, 0.04353, 0.02333, 0.02106 bits. Direct Huffman merges with exact integer reflection weights give 0.02334 bits at $n=8192$, whose phase is 1/2. For 52 cards, coding the literal peak costs 3.270627252 bits; the earlier 3.116571426 figure already merges zero-peak decks into an existing instruction.
### The optimal integer frontier and zero payouts
Let $t$ be cards remaining, $x\equiv t\pmod2$ the score, $m=(t+x)/2$, and
$U(t,x)=V(t,x)-x$ the optimal expected additional payout.
Write $b_t=\min\{x:U(t,x)=0\}$, using stop on ties.
The balanced initial state is $(N,0)$, with $N=2n$.
Put $s=\sqrt{t+1}$, let $B_t$ be the nearest parity-compatible integer to $\alpha s$, and let $p\in(0,1)$ satisfy $D_p(-\alpha)=0$.
Write $\mu=p/2=0.231166686734485919\ldots$.
**Results.** The integer frontier satisfies $b_t=\alpha\sqrt t+O(1)$.
Except on a set of layers of natural density zero, it is the first feasible integer $x$ satisfying $x+1/2\ge\alpha\sqrt t$.
In fact disagreements can accumulate only when $\operatorname{dist}(\alpha\sqrt t,\mathbb Z+1/2)\to0$.
The probability that optimal stop-on-ties play pays zero on a balanced deck is $\Theta(N^{-\mu})$.
These two-sided bounds leave the limiting amplitude undetermined.
##### Inputs from the price comparison
Let $p_t(x)=2^{-t}\binom t m$ and $Q_t(x)=2(1-\alpha^2)F_t(x)/p_t(x)$, where $F_t$ is the midpoint CDF of the simple symmetric walk.
The companion proof of the price gap supplies the following facts.
* The majorant $M$ dominates $V$ on all large layers. Its correction is
$$
M-Q=.55\frac{p_t(x-4)-p_t(x-2)}{p_t(x)}
+.14\frac{p_t(x+2)+p_t(x-2)-2p_t(x)}{p_t(x)}.
$$
* On $x\le B_t$, the payoff of a single policy dominates $Q_t(x)-x/t-L S_t^-(x)$ for all sufficiently large $t$, where $L$ is fixed,
$$
C_{t,m}=[z^m](1-z)^p(1+z)^{t-p},\qquad
R_t(x)=C_{t,m}/\binom t m,\qquad S_t^-(x)=C_{t+2,m}/\binom t m .
$$
The same stopped-martingale proof works from **each** such initial state. Its exercise boundary moves by one and its fixed terminal comparison covers every surviving state. At fixed displacement $x=\alpha\sqrt t+O(1)$, $S_t^-(x)=O(t^{-\mu-1/2})$.
* $Q_t(B_t)-B_t\le B_t/t$ for all large $t$.
* The $R_t$ decrease in $x$, and on compact ranges
$$
t^\mu R_t(x)=r(x/\sqrt t)+O(t^{-1}),\qquad
r(y)=e^{y^2/4}D_p(-y),\quad r(0)>0,\quad r(\alpha)=0,\quad r'(\alpha)<0 .
$$
Here and below fixed real offsets can be used on any subsequence respecting integer parity.
With $u=x-\alpha s$ bounded, the contact expansion is
$$
s(Q_t(x)-x)=\alpha(u^2-c_0)+o(1),\qquad c_0=\tfrac13-\tfrac16\alpha^2 .
\tag{1}
$$
The remainder tends uniformly to zero for $u$ in each fixed compact range.
For completeness put $y=(x-1)/s$, $f(y)=(1-\alpha^2)\int_0^\infty e^{yv-v^2/2}\,dv$, and $g=f-\mathrm{id}$.
The binomial midpoint integral is
$$
Q_t(x)-x=sg(y)+g'(y)+(1-\alpha^2)(s+y)
\int_0^\infty e^{yv}\{\operatorname{sech}^{s^2}(v/s)-e^{-v^2/2}\}\,dv .
$$
Since $f'=1-\alpha^2+yf$, $f(\alpha)=\alpha,\ f'(\alpha)=1,\ f''(\alpha)=2\alpha,\ f''''(\alpha)=8\alpha+2\alpha^3$.
After multiplication by $s$, the first two terms converge to $\alpha(u^2-1)$ up to $o(1)$.
The last contributes $f''''(\alpha)/12+o(1)$: for $v\le s$,
$$
0\le s^2\{\operatorname{sech}^{s^2}(v/s)-e^{-v^2/2}\}\le (v^4/12)e^{-5v^2/12}.
$$
This follows from $0\le v^2/2-s^2\log\cosh(v/s)\le v^4/(12s^2)$.
For $v\ge s$, $\log\cosh(v/s)\ge(v/s)/3$, so the scaled tail is exponentially small.
Pointwise expansion and dominated convergence give (1).
Likewise $p_t(x-2)/p_t(x)=(t+x)/(t-x+2)$.
Expanding the four adjacent ratios in $M-Q$ gives
$$
s(M_t(x)-Q_t(x))=1.1\alpha+o(1). \tag{2}
$$
##### A bounded strip for the frontier
$U$ decreases in $x$ at fixed $t$.
Indeed adding a minus ball weakly reduces the urn's future value and deleting a plus ball also reduces it.
These same monotonicities give $b_{t+1}\le b_t+1$ by adding a minus ball to a stopping state, and $b_{t+1}\ge b_t-1$ by adding a plus ball to the strict continuation state $b_t-2$.
Thus $b_{t+1}-b_t=\pm1$ on every layer where both states are physical, in particular on large layers. The same one-step property applies on the small layers directly, using $U(t,-t)>0,\ U(t,t)=0$ for $t>0$.
[Boyce 1973](https://doi.org/10.1016/0012-365X(73)90123-4 "On a simple optimal stopping problem").
At $x=B_t-4$, (1) has $u\le-3$. The attainable minorant gives
$sU(t,x)\ge\alpha(9-c_0)-\alpha-o(1)>0$, so $b_t\ge B_t-2$.
At $B_t$, equations (1)–(2) give $sU(t,B_t)\le(1-c_0+1.1)\alpha+o(1)<2\alpha$.
By monotonicity this also bounds $U(t,x)$ for every $x\ge B_t$.
Start at $B_t+2$. Follow the optimal rule for at most two draws, writing $\sigma$ for the number drawn and $X_i$ for the score after $i$ draws.
The Bellman identity gives
$$
U(t,B_t+2)=\mathbb E[U(t-\sigma,X_\sigma)]-
\mathbb E\sum_{i<\sigma}X_i/(t-i).
$$
If $\sigma<2$, the terminal excess is zero.
If $\sigma=2$, then $X_2\ge B_t\ge B_{t-2}$, since the same parity grid rounds a nondecreasing real threshold.
Consequently its terminal excess is at most $((2.1-c_0)\alpha+o(1))/s$, whereas its two realized drift costs sum to $(2\alpha+o(1))/s$, uniformly over paths.
Any other path taking at least one draw incurs a positive drift cost.
As $2.1-c_0<2$, strict continuation would give negative $U$. Thus
$$
B_t-2\le b_t\le B_t+2 \tag{3}
$$
for all sufficiently large $t$.
This proof gives an eventual constant and no explicit onset.
##### The local limit determines the half-card shift
Along any sequence $t\to\infty$, put $\ell_t=\lfloor\alpha\sqrt{t+1}\rfloor$.
Pass to a subsequence so that $\alpha\sqrt{t+1}-\ell_t\to\phi\in[0,1]$ and $t-\ell_t\pmod2$ is constant.
For each fixed $i\ge0$ and compatible integer $j$, the numbers
$$
\sqrt{t+1}\,U(t-i,\ell_t+j)/\alpha
$$
are bounded by (1)–(2). Take simultaneous subsequential limits $H_i(j)$ by countable diagonal extraction.
The continuation probabilities tend to $1/2$ and the scaled drift tends to one, so
$$
H_i(j)=\max\left(0,\frac{H_{i+1}(j-1)+H_{i+1}(j+1)}2-1\right).
\tag{4}
$$
At fixed $i$, $\alpha\sqrt{t-i+1}-\alpha\sqrt{t+1}\to0$.
By (3), $H_i(j)=0$ for $j\ge6$.
For $j\le-3$, the attainable minorant applies. Equations (1)–(2) imply
$$
-c_0-1\ \le\ H_i(j)-(j-\phi)^2\ \le\ -c_0+1.1. \tag{5}
$$
The same constants work for every $i,j$ after the subsequential limit. On the finitely many intermediate $j$'s (1)–(2) likewise bound $H_i(j)$ independently of $i$.
Let $k$ be a nearest integer to $\phi$ and put
$$
G(j)=\mathbf1_{j0$, the continuation surplus at $j=k$ is strictly negative, and it equals $-1$ farther to the right.
The actual continuation surpluses converge along the same subsequence by (4)'s prelimit identity.
Thus off any fixed neighborhood of half-integral phases, the exact integer rule agrees eventually with the first parity-compatible $x\ge\alpha\sqrt{t}-1/2$.
Replacing $\sqrt{t+1}$ by $\sqrt t$ changes the vanishing-error band by $O(t^{-1/2})$.
For completeness each parity subsequence $\alpha\sqrt{2j+e}$ is equidistributed modulo 2.
For a fixed interval $[a,b)\subset[0,2)$, the interval $2h+[a,b)$ contributes
$((2h+b)^2-(2h+a)^2)/(2\alpha^2)+O(1)$ indices $j$.
Summing full periods up to $j\le J$ gives $(b-a)J/2+O(\sqrt J)$, including the final partial period.
Hence phases within $\epsilon$ of a half-integer have upper density $O(\epsilon)$ on either parity.
The half-shift rule is exact on a density-one set.
On a fixed parity's uniform period of length two, the unshifted parity ceiling $x\ge\alpha\sqrt t$ differs from the half-shift ceiling on an interval of length $1/2$; thus the *unshifted ceiling* is exact on a set of density $3/4$.
This verifies both lattice-density predictions summarized by [Lai, Yao & Aitsahlia 2007](https://doi.org/10.1239/aap/1189518637 "Corrected random walk approximations to free boundary problems in optimal stopping"), p. 769, from [Simons 1987](https://doi.org/10.1016/0167-7152(87)90025-3 "Easily determining which urns are ‘favorable’").
The density statements concern integer compositions. The continuous threshold in Lai et al., p. 769, interpolates using one ball with a deterministic fractional payoff.
##### Zero-payoff survival
At every nonempty layer $x=0$ is strictly continuing: from a balanced positive-size urn, cash the first up-step if it occurs on draw one, otherwise retain the option of the terminal zero.
At $x<0$ the guaranteed terminal zero exceeds immediate cash. Thus zero payoff under stop on ties is precisely survival past every positive-time stopping set.
Let $P(t,x)$ be its probability from the given state. On continuing states it is the bridge average of its two children; it is zero on stopping states for $t>0$, and $P(0,0)=1$.
Write $K=8$ and consider
$$
S^u_t(x)=C_{t+K,m}/\binom t m,\qquad S^l_t(x)=C_{t-K,m}/\binom t m .
$$
Both solve the bridge recursion below the stopping frontier, including its physical left edge since negative-index coefficients vanish. The physical right edge is never used in continuation on the large layers.
One-step motion of $b$ means every first hit is at equality.
The arguments of $R$ at $b_t$ are $b_t-K$ and $b_t+K$, respectively.
By (3) they are uniformly strictly to the left and right of the corresponding roots $\alpha\sqrt{t\pm K}$ by a fixed number of lattice units.
The compact profile with $O(t^{-1})$ scaled error and $r'(\alpha)<0$ gives $S^u_t(b_t)>0>S^l_t(b_t)$ eventually.
Monotonicity of $R_{t+K}$ gives positivity of $S^u$ below the boundary as well.
On a single large even layer $T$, $P(T,x)>0$ at all $x0$ give $aS^l_T\le P(T,\cdot)\le bS^u_T$ on them.
At first hits, $P=0$ lies between these same comparisons.
Optional stopping at the boundary or $T$, whichever comes first, yields $aS^l_N(0)\le P(N,0)\le bS^u_N(0)$.
The two modes at zero are asymptotic to $2^{-K}r(0)N^{-\mu}$ and $2^K r(0)N^{-\mu}$, respectively.
This proves the claimed sharp order for the optimal policy.
### The continuous boundary with a fractional-payoff card
Let $\beta(t)$ be the continuous threshold defined by Lai, Yao and Aitsahlia. For $w\in(-t,t]$ take the integer $k$ of parity $t$ such that $k-20$ large enough that $\widetilde Q_t(w)-w\le Kw/t$ at first exercise; $s w/t\ge\alpha$ there. For $U_t(x)=C_{t+8,(t+x)/2}/\binom{t}{(t+x)/2}$ the shifted critical profile is evaluated at $x-8$. It is strictly positive at the largest endpoint in the strip for all large $t$, hence positive at all smaller physical scores by monotonicity of the normalized profile. The fractional interpolation $\widetilde U$ is positive throughout the needed region. It has a positive minimum on the finite cutoff row by taking the minimum over its finitely many physical endpoints. Choose $L$ so that $\widetilde Q-Kw/T-L\widetilde U\le0$ on that row. Optional stopping now gives the pointwise bound
$$
h_F(t,w)\ge \widetilde Q_t(w)-w-Kw/t-L\widetilde U_t(w)
\quad(w<\alpha\sqrt{t+1},\ t\ge T).
$$
All continuations stay away from the impossible upper edge, including both adjacent ordinary endpoints. The negative physical edge retains equality. The starting offsets needed below are on compact sets around the boundary.
**The limiting decision.** Fix a real offset $z$ and any sequence of horizons $t\to\infty$, with $w=\alpha\sqrt{t+1}+z$. Keep the distinguished card undrawn and look after $i$ ordinary draws at physical balances $w+j$ ($i+j$ even). Scale the surplus by $\sqrt{t+1}/\alpha$. On each fixed offset the upper comparison bounds these quantities uniformly, and they are nonnegative. Extract a diagonal subsequence with limits $H_i(j)$ for every fixed $i,j$ of the appropriate parity. The immediate expected gain on a draw is exactly $-(w+j)/(t-i)$. The ordinary probabilities tend to $1/2$, while the distinguished card has probability $1/(t-i)$. On its revelation the remaining ordinary surplus is $O(1/\sqrt t)$ at its bounded offset by the ordinary upper comparison, so its term in the scaled recurrence vanishes. Consequently
$$
H_i(j)=\max\{0,[H_{i+1}(j-1)+H_{i+1}(j+1)]/2-1\}.
$$
The same conclusion holds on endpoint subsequences by retaining the harmless label.
For all sufficiently positive $j$, both ordinary endpoints stop, hence $H_i(j)=0$. For all sufficiently negative $j$, the bounds just proved show that $H_i(j)-(z+j)^2$ is bounded by absolute constants independent of $i,j$ (for fixed $z$). Indeed the fixed-offset expansion of $s(Q-x)/\alpha$ has quadratic term $(x-\alpha s)^2$ and a constant offset. Interpolating the quadratic gives $(w-\alpha s)^2+4u(1-u)$, with a bounded extra term uniformly in $u$. The upper-majorant correction and tilt are bounded in scaled units. The translated critical kernel contributes zero in the limit at every fixed offset, by its simple zero and its $O(1/t)$ local profile error. Changes in the center from any *fixed* $i$ vanish in the limit. These are bounds on the limiting array; no estimate at offsets growing with $t$ is required.
Let $k_0$ be the smaller integer in a nearest-integer tie, and otherwise the unique integer nearest to $-z$ and set
$$
G(j)=\big((z+j)^2-(z+k_0)^2\big)\mathbf1_{j-1/2$: below the threshold $G(0)>0$, at the first exercise point the signed margin is $-1/2-(z+k_0)$, and above it the margin is $-1$. At an ambiguous nearest integer the only neutral position has $z+j=-1/2$. Thus for each $\epsilon>0$ the fractional urn strictly continues at offset $-1/2-\epsilon$ and strictly stops at $-1/2+\epsilon$ for all sufficiently large $t$. Monotonicity of its surplus places $\beta(t)$ between these two points. Finally $\sqrt{t+1}-\sqrt t=o(1)$.
### A quantitative error bound for the half-card correction
Let $\beta(t)$ have Lai, Yao and Aitsahlia's fractional-payoff definition. The preceding arguments imply
$$
\beta(t)=\alpha\sqrt t-\tfrac12+O(t^{-1/6}).
$$
The same estimate confines the integer half-shift rule's possible errors to a band of width $O(t^{-1/6})$ about half-integer phases. Constants and onset are nonexplicit. The argument uses the mathematically proved critical harmonic comparison; it is separate from the Lean replay.
Write $S=\sqrt{t+1}$, $w=\alpha S+z$, $|z|\le2$, $J=\lfloor t^{1/6}\rfloor$, $L=J^2$. For $i\le L$ and $s=\sqrt{t-i+1}$, consider the fractional state obtained after $i$ ordinary draws with balance $w+j$, where $-J\le j\le A$. Here $A=12$ is an upper absorbing level: both ordinary endpoint urns strictly stop or are indifferent there by (3) of the integer proof, so the fractional surplus is zero. The two endpoint states differ from $w+j$ by at most two. Their weights interpolate the endpoint scores to $w+j$. The distinguished card has probability $1/(t-i)$. Write $H_i(j)=S\,U_F(t-i,w+j)/\alpha$ for the fractional surplus and use analogous scaling for ordinary states.
Let $k$ be nearest to $-z$ and
$$
G(j)=\mathbf1_{j1/6$ here. The verified `GamePositivity.coefficient_positive` gives positive discrete coefficients at index $2/5$ up to $(169/200)\sqrt t$. Taking scaled limits at that endpoint gives $r_{2/5}(169/200)\ge0$; strict decrease in the spatial argument gives $r_{2/5}(\alpha)>0$, hence $\mu>1/5$ by the unique crossing in the spectral proof. The scaled tilt is $O(1)$. For $j\le-6$ the fractional minorant is available at $w+j<\alpha s$. The lower and upper endpoint comparisons thus give
$$
|H_i(j)-(z+j)^2|\le C \qquad(-J\le j\le-6).
$$
In taking the endpoint average the linear term in $e$ cancels, and its second moment is at most one. On the other finitely many sites use $U_F\ge0$ and the upper comparison (R1). We obtain
$$
|H_i(j)-G(j)|\le C\quad (i\le L,\ -J\le j\le A).
\tag{R2}
$$
At $j=A$ the difference equals zero. If the fractional card is revealed on a draw inside the box, the resulting ordinary scaled surplus is $O(J^2)$ by the same upper bound (enlarging the two endpoint margins by a constant if necessary).
**One-step error.** At each state prior to revealing the distinguished card, let $a_+,a_-$ be the probabilities of drawing ordinary $+1,-1$ cards, let $\eta=1/(t-i)$, and put $e_0$ for the bounded distinguished payoff. We have $a_++a_-=1-\eta$, $a_+-a_-=-(w+j)/(t-i)-\eta e_0=O(t^{-1/2})$. The scaled expected drift satisfies
$$
\left|(S/\alpha)(w+j)/(t-i)-1\right|=O(J/S+L/t).
$$
Thus replacing the stationary signed expression $(G(j-1)+G(j+1))/2-1$ by its actual Bellman expression with children $G(j\pm1)$ and the *actual* ordinary surplus on special-card revelation makes an error of at most
$$
e=C(J/S+L/t+J^2/t).
$$
The probability-asymmetry term multiplies a difference $O(J)$, while the missing ordinary mass and the entire revealed-card term cost $O(J^2/t)$. The positive part is 1-Lipschitz. Consequently $|H_i(j)-G(j)|\le e+a_+|H_{i+1}(j+1)-G(j+1)|+a_-|H_{i+1}(j-1)-G(j-1)|$. The identical inequality applies to the difference of the two *signed* draw surpluses at the first step, without taking positive parts there.
**Exit estimate.** Iterate up to $i=L$ or first exit to $-J,A$; revelation has already been paid for in $e$. Terminal or lower-exit errors are bounded by (R2) and the top error is zero. Each still-unrevealed path of length $d\le L$ has probability at most $2^{-d}(1+C/S)^d\le 2\cdot 2^{-d}$ for all sufficiently large $t$; the bound applies pathwise on the stopped tree. From $j=0$ the symmetric probability of hitting $-J$ before $A$ is $A/(J+A)$, and the reflection principle gives $\Pr_0(\tau_A>L)\le C A/\sqrt L$. The accumulation of the per-step error is at most twice $e$ times the expected exit time of the symmetric walk from $(-J,A)$ started at zero. The expectation equals $AJ$, by solving the elementary second-difference equation (or optional stopping of $S_m^2-m$). The bound applies to the sum of unabsorbed weights at each depth, with the same likelihood ratio as above. Therefore the scaled signed draw surplus at $w$ differs from its stationary value by at most
$$
C\{Je+1/J+1/\sqrt L\}=O(t^{-1/6}).
$$
For $z> -1/2$ near $-1/2$ the stationary signed margin at zero is $-|z+1/2|$, and for $z< -1/2$ it is $2|z+1/2|$. Test $z=-1/2\pm C' t^{-1/6}$ with $C'$ sufficiently large. The exact fractional actions are then strictly stop and strictly continue, respectively, in the appropriate order. Monotonicity in $w$ gives the theorem, since $\sqrt{t+1}-\sqrt t=O(t^{-1/2})$.
For the integer rounding frequency an interval of width $c\,t^{-1/6}$ near a half-integer yields at most $O(X^{5/6}+\sqrt X)$ exceptional layers through $X$. Apply the squared-block count on each dyadic interval $Y\le t<2Y$, where its length is $O(Y^{-1/6})$, and sum. Thus the number of possible mistakes of the half-shift rule over all remaining deck sizes through $X$ is $O(X^{5/6})$.
### Survival through a specified remaining layer
Fix the notation and the proven frontier bound $|b_t-\alpha\sqrt t|\le C_0$ of the integer proof.
Write $P_{N,T}$ for the probability of strictly continuing at every layer down to **and including** $T$, from a balanced deck of $N$ cards.
There are positive constants $a,b,T_0$ such that, simultaneously for all integers $T_0\le T\le N$, $N$ even,
$$
a(T/N)^\mu\le P_{N,T}\le b(T/N)^\mu .
$$
The constants depend on the game, not $T,N$. They do not identify a limiting multiplier.
Here is a reusable notation for translated exact solutions of the bridge equation.
For fixed integers $h,k$ of the same parity define
$$
Z_t^{h,k}(x)=p_{t+h}(x+k)R_{t+h}(x+k)/p_t(x)
$$
whenever the numerator is physical; on other lattice points use the signed heat numerator $2^{-t-h}C_{t+h,(t+h+x+k)/2}$, which vanishes at negative indices.
The function is harmonic inside the physical region where both child transitions are allowed.
At the left physical edge with $h+k\le0$, its omitted child has a negative coefficient index, so harmonicity also holds there. The three translations below all have $h+k\le0$.
Only continuation and first-hit states matter. Their right index remains physical for all sufficiently large $T$ in the translations below, because $x\le\alpha\sqrt t+C_0$ and $t+h\ge t/2$.
**Upper bound.** Fix an even integer $K>C_0+3$.
Take $d$ to be an even integer with $\sqrt T\le d\le\sqrt T+2$.
Use $A_t=Z_t^{K,-K}+Z_t^{d,-d}$.
Both summands are strictly positive on every continuation state and first exit for $t\ge T$; at the fixed translation this follows by the sign of $r'$ at the root and the uniform $O(t^{-1})$ scaled profile error.
For the growing translation $d$ the shifted score is farther below the root, and monotonicity in the score reduces to a fixed displacement cutoff in the $(t+d)$ layer.
At $t=T$, $x\le0$, the first summand is at least $cT^{-\mu}$. Its mass ratio is $2^{-K}\binom{T+K}{m}/\binom Tm\ge2^{-K}$; use monotonicity of $R$ and its positive central limit.
For $0\le x0$.
It remains to bound $T^\mu (L_T)_+$ uniformly on the cutoff. Put $s=T-D$.
On the negative half of the lattice,
$$
(R_s(y))_+\le C s^{-\mu}(1+|y|^p/s^{p/2}) .
\tag{1}
$$
Indeed write $(1-u)^p=1-\sum_{j\ge1}a_j u^j$, $a_j>0,\ a_j=O(j^{-1-p})$.
For $l=(s+y)/2\le s/2$, the exact binomial-factorial formula implies
$$
R_s(y)\le (1-2l/s)^p
+\sum_{j\ge1} a_j (2l/s)^j\min(1,j(j-1)/(2l)).
$$
When $j\le l$, this follows by bounding the finite-product loss
$1-(l)_j/l^j\le\sum_{il$ use the trivial bound one. Treat $l=0$ separately.
For $l\ge s/4$, the difference sum split at $\sqrt s$ is $O(s^{-p/2})$; for $l
### Matching bounds on true policy regret
Let $N=2n$, and let $D_\pi(t,x)=V(t,x)-V_\pi(t,x)$ be the loss against the finite game's own optimal price at state $(t,x)$. Write $B_t$ for the first exercise score of the specified rule on the compatible parity lattice. Each of the original hybrid, the pure half-dollar rule and the 79/half-dollar hybrid has the following asymptotic behavior, in dollars:
$$
D_\pi(N,0)=\Theta(N^{-\mu}),\qquad
\mu=0.2311666867344859\ldots .
$$
This is a written two-sided theorem for these three policies, with unspecified positive constants. In particular the improved hybrid's very small finite losses can coexist with the same decay exponent as the original hybrid. The unchanged 79-rule has a different leading slope and lies outside the theorem.
**Local accounting.** At a state let $P$ denote one step of the bridge and $a=x$ the cash payoff. When the policy stops, its loss is $(PV-a)_+$; when it draws its loss is $(a-PV)_+ + P D_\pi$. This identity underlies the independent floating-point sweep. It also supplies a sign-preserving lower bound: on any draw, $D_\pi\ge P D_\pi$. The module `RegretAccounting.lean` proves the identity in aggregate integer units on the actual game tree, including physical edges. A mistake at a descendant contributes only along paths where the player continues to that descendant.
**Preliminaries.** The critical heat numerator is
$$C_{t,m}=[z^m](1-z)^{2\mu}(1+z)^{t-2\mu},\qquad m=(t+x)/2.$$
Its normalized profile $R_t(x)=C_{t,m}/\binom tm$ decreases with $x$. At $y=x/\sqrt t$ in a fixed compact interval it satisfies $t^\mu R_t(x)=r(y)+O(t^{-1})$, where $r(0)>0$, $r(\alpha)=0$ and $r'(\alpha)<0$. The critical-exponent proof establishes these estimates. All three exercise boundaries move by one on each sufficiently large layer, are positive and satisfy $|B_t-\alpha\sqrt t|<2$ eventually. These facts hold for the specified dyadic implementation, despite its allowed downward displacement. A trajectory starting below its boundary first hits it at equality. Each rule draws whenever $t>0$ and $x\le0$.
**Upper bound.** Let $U_t(x)=C_{t+4,m}/\binom tm$. Its sign at $B_t$ is that of $R_{t+4}(B_t-4)$, strictly positive for all sufficiently large $t$ by the local profile estimate. Monotonicity of that unshifted profile gives strict positivity at every $x\le B_t$, including the extreme negative score. The translated numerator obeys Pascal's rule, so $U$ is harmonic on every continuing state. The published exercise-contact bounds give $Q_t(B_t)-B_t\le k B_t/t$, with $k=1$ for the original hybrid and $17/8$ for the half-card boundary. On one fixed large row $T$, choose $L>0$ so $Q_T(x)-kx/T-LU_T(x)\le V_\pi(T,x)$ at all surviving scores; this is possible by finite strict positivity. At exercise the same comparison is bounded by cash. Optional stopping from $(N,0)$, and the separately established $V(N,0)\le Q_N(0)$, give
$$0\le D_\pi(N,0)\le L U_N(0)=O(N^{-\mu}).$$
Indeed $\binom{N+4}{n}/\binom Nn\to16$ and its profile is evaluated at score $-4$.
**Lower bound.** Fix $b$ so that starting from $(2b,0)$ brings strictly positive expected loss. One may take $b=55$ for the pure half-card rule and $b=8243$ for either hybrid, since all decisions on the latter starting deck use the 79-rule. Put $a=2b+4$. For $t>a$, use the translated caloric function
$$ W_t(x)=C_{t-a,m-b}/\binom tm.$$
Coefficients of negative index are zero. The shifted profile now has score $x+4$, so $W_t(B_t)<0$ for all sufficiently large $t$, again by the local estimate and the simple zero of $r$. On a fixed sufficiently large cutoff row $T$, every $x0$. At $m0$ such that $D_\pi(T,x)\ge cW_T(x)$ on the entire required row, including the negative edge. Above the cutoff the same inequality follows by backward induction: on a draw use $D_\pi\ge P D_\pi$ and harmonicity, and on the first hit use $D_\pi\ge0>cW_t(B_t)$. The coefficient of negative index at the impossible left child is zero, and the policy never draws at the extreme positive edge. At the start
$$
W_N(0)\sim 2^{-a}r(0)N^{-\mu}
$$
because $\binom{N-a}{n-b}/\binom Nn\to2^{-a}$ while $x+4=4$. This proves the positive lower bound.
The same proof gives $\Pr_\pi(\text{zero payoff})=\Theta(N^{-\mu})$ for these three rules. The probability equals zero when positive cash is taken and is harmonic on draws, including programs which default to zero at exhaustion. For the upper bound use $LU$ alone. For the lower bound take $b=1$, since the black-first order of the two-card deck finishes at zero. The final probability and the realized loss are different quantities even though both inherit the spectral power. Neither argument supplies their amplitudes.
### Finite regret extrema, dominance and error accounting
##### Peak regret and the first strict improvement
Among all balanced decks through **8,388,608 total cards**, the original hybrid’s unique worst starting deck contains **326,148 cards**, with regret **$0.00026340776136228**. The runner-up is at 326,150. For 79 through 65,536 remaining cards followed by the half-card boundary, the unique worst deck contains **78,622 cards**, with regret **$0.0000000496869737541**. The runner-up is at 78,624. The two peaks differ by a factor of **5,301.34**. Fable’s maximizing deck sizes are correct over its entire scanned range. The infinite-horizon maximum is not established. The half-card rule alone retains its exact 220-card maximum and its first strictly suboptimal decision is to stop with 47 reds and 55 blacks left, on a deck of at least 110 cards.
The 79 rule strictly beats the old hybrid earlier than the apparent equalities in the long-double output suggest. Through **2,097,152 cards**, exact equality after the switch holds on **255** even decks, 65,538 through 66,046. Pure 79 wins on all **1,015,553** remaining sizes, beginning at **66,048**. From that first starting deck the difference in unconditional expected value already exceeds $5.33×10⁻⁷⁰. This explains how a floating-point comparison of regrets around $4×10⁻⁸ can report equality.
The upper-time branch of the old hybrid accepts every positive score accepted by 79 on the certified interval. A lower Bellman sweep evaluates the *actual 79 policy*, forcing zero at a far-negative wall. Its conditional expected payoff exceeds cash at each of the 452,375 states to 2,097,152 where the old hybrid cashes but 79 continues. Extending through 8,388,608 cards verifies all 1,582,976 differing exercise states, with the same smallest validated margin, above $0.00003065. Thus strict dominance extends to *every* even starting deck from 66,048 through 8,388,608. Backward induction therefore orders the two policies at every feasible state. At t=65,833, x=215 the old hybrid cashes, while the 79 policy realizes at least 215+44860115464/2⁵⁰ dollars in conditional expectation (the computed value is a lower bound). This is the first disagreement in t. No possible disagreement requires fewer than 66,048 initial cards: at all later layers the old stopping score is at least 215. The 215-red starting prefix first reaches this state on the 66,048-card deck, with probability binom(33024,215)/binom(66048,215). On larger balanced decks a suitable number of initial black–red pairs returns play to zero on a 66,048-card remainder. The witness now has positive probability on every larger deck in the dominance sweep.
At precisely 66,048 cards the all-red prefix is the only source of a payoff difference. Before 65,833 remaining cards have been reached, at most 214 points can have been won; below that layer there are no disagreements. In units of $2^{-46}$ dollars the directed conditional gain at $(65833,215)$ is between 2,803,757,111 and 2,803,757,336. The checker bounds every continuation by two integer weighted means rounded outwards and uses $[0,t]$ dollars on the artificial negative wall. The positive edge is in the exercise region. Multiplication by the exact probability of 215 initial reds gives **$5.335\times10^{-70}<\Delta<5.336\times10^{-70}$ dollars**.
The first threshold crossing after the switch and a nearly 5,000-fold value ratio at 131,070 describe distinct phenomena. At 65,538 the old hybrid's regret remains about $4.1394×10⁻⁸. At 8,388,608 cards our independent interval puts the 79 rule’s regret between 79.14% and 79.45% of its limiting leading term. Extrapolating the 79 rule's eventual loss 2.43148×10⁻⁹√n to a threshold of one cent gives roughly 1.69×10¹³ pairs. This is an extrapolation of the leading term, not a certified first crossing. The approximately 10⁹-card crossover between two policies is also an extrapolation.
##### Where the bound goes
Let E be the fixed policy's payoff, V the true optimum, Q the proxy upper bound, and C=λR the explicit comparison gap. The published proof establishes E≥Q−C and V≤Q, so **V−E≤Q−E≤C**. Thus the certificate genuinely bounds regret. Fable correctly identifies a large avoidable gap in the chosen comparison.
| Starting cards | Policy | Q−V | V−E | E−(Q−C) | C |
|---:|---|---:|---:|---:|---:|
| 482,620 | Original hybrid | 0.005846655 | 0.000258477 | 0.003699061 | 0.009804192 |
| 1,048,578 | Pure half-card | 0.004886301 | 0.000001684 | 0.002759230 | 0.007647215 |
| 1,048,578 | 79 then half-card | 0.004886301 | 0.000000018 | 0.002759006 | 0.007645326 |
All entries are dollars, with directed intervals in decomposition.txt. At 482,620 cards, Q−V accounts for **59.63423%** of the actual analytic cap. At the revised first deck outside the finite sweep, it accounts for **63.8965%** and **63.9123%**, respectively. The last component includes any looseness in the certified multiplier λ. A sharper central-product evaluation at the first uncovered deck tightens the formerly rounded global upper bounds to $0.0076472151 for pure half-card and $0.0076453259 for 79 then half-card. The product decreases thereafter and the finite prefix costs less.
Rebuilding the independent C source through 482,620 reproduced its last row and all reported maximum indices within this range. The program propagates a separate regret, so it avoids subtracting nearly equal prices at each root. At a policy stop its local cost is max(cash, optimal continuation) minus cash; at a draw it adds the local continuation shortfall to the two policy-child regrets. The identity is correct. Its negative wall and long-double arithmetic make the output numerical. A wall at −7√t has simple-walk Gaussian exponent −49/2 when t is a remaining-time segment much shorter than the full horizon; the comment “weight ~e^-98” is not a uniform reflection bound. At 482,620, for instance, Fable gives V=256.436494107779, slightly below our certified lower value 256.436494107855. The discrepancy does not affect the reported decomposition to six decimals. The proposed asymptotic rate of the proxy gap is a separate claim and is not needed by this arithmetic.
##### Reproducing the certificates
Use a GNU C implementation with unsigned 128-bit integers and Python 3. Retain assertions. peaks.c uses units S=2⁹², exact fixed-point floors and an independent score band. The guaranteed loss from the artificial negative wall of magnitude w is at most n exp(−w²/(n+1/2)) for an initial 2n-card deck; it is zero if the wall is unreachable. This follows by dividing the reflected bridge count binom(2n,n+w) by binom(2n,n), and bounding the corresponding product via (1−z)/(1+z)≤exp(−2z). The wall cost is less than one fixed-point unit on the fine sweep. The positive wall H always satisfies 2H²≥5t and every fixed rule stops there, so that wall is exact. For the optimum, the quadratic obstacle argument from fast.c gives stopping when x≥√(5t/2). In brief, for a²=5/2 the function (x²+a²t)/(2a√t) below a√t, patched to cash above it, majorizes all continuation values. Below contact this follows from E[x′²]=(1−2/t)x²+1 and a²≥1+√(t/(t−1)) for t≥2. At and above contact the lower child overshoots the quadratic tangency by at most one, costing at most 1/(2a√(t−1))≤x/t against the score's mean drift. The t=1 case is immediate.
At denominator d=2t, put s=floor(log₂(d−1)) and m=floor(2^(64+s)/d). For the weighted numerator v, the code computes q=floor(vm/2^(64+s)) using two 64-bit limbs. Since d≤2^(s+1) and v/d≤2¹⁰², this approximation is downward and its error below v/d is at most 2³⁹+1. The residual v−qd therefore fits in an unsigned 64-bit word. A second reciprocal multiplication of that residual and one integer correction give its exact quotient. A separate regression compares 100,000 averages to direct 128-bit integer division. Maxima and expectation are nonexpansive, so the lower fixed-point optimum and fixed-rule payoffs have errors ≤t/S on the clipped game. Their regret difference therefore has error ≤(t+1)/S on the full starting deck.
The earlier 52-bit default and extended sweeps screen the entire range: filter.py finds 1,113 old-hybrid candidates (325,040…327,264) and 2,092 mixed candidates (76,666…80,848). The 92-bit calculation runs from zero through the upper end of each range. Its witness lower bounds exceed every competitor upper bound there. For each rule the coarse screening excludes every larger deck through 1,048,576.
values.c uses the same walls argument and a one-step reciprocal approximation in units 2⁻⁵¹. Each continuation rounds down by less than three units and its starting price is enclosed to (3N+1) units. decompose.py encloses Q=(1−α²)4ⁿ/binom(2n,n) with the certified α bracket. Both its central binomial inverse and the R product iterate exact integer outward upper and lower bounds in units 2⁻¹⁰⁰. All reported component intervals are rounded outwards.
~~~bash
set -e
cc -O3 -march=native -std=gnu11 peaks.c -o /tmp/peaks
/tmp/peaks
cc -O3 -march=native -std=gnu11 check_mean.c -o /tmp/check-mean
/tmp/check-mean
cc -O3 -march=native -std=gnu11 values.c -o /tmp/values
/tmp/values > /tmp/fable-values
python3 decompose.py /tmp/fable-values
cc -O3 -march=native -std=gnu11 -DHORIZON=8388608 dominance.c -o /tmp/dominance
/tmp/dominance
python3 first_error.py
c++ -O3 -std=c++17 rare_opening.cpp -o /tmp/p14-rare-opening
/tmp/p14-rare-opening | python3 rare_opening.py
~~~
Run filter.py with the two row files generated by the preceding report’s review/rule/certify.c, default compilation first and -DEXTEND second. peaks.c took 13.2 seconds on an AMD EPYC 9V74 core; the 1,048,578-layer five-value sweep took 61.2 seconds.
##### The remaining 3,670,016 tail roots
The independent heat sweep covers every even starting size from 1,048,578 through 8,388,608. Its respective maximum upper endpoints on this tail are $0.000233022913154 for the old hybrid, $0.000000018926325 for 79 followed by half-card, and $0.000001684270508 for half-card alone. All lie below the independently established finite maxima, and for both hybrid policies below their runners-up.
For a value function V(t,x), multiplying by the fair-walk mass p_t(x) changes continuation into the ordinary half-sum of the two children's weighted values. The heat DP uses 2⁻⁶² units and downward integer averages. All weighted values stay below one: x·p_t(x)≤1 by binomial symmetry and unimodality, since x+1 parity-compatible masses on [−x,x] are at least p_t(x), and the half-sum preserves the bound. Each fixed policy has a single stopping boundary changing by one each time. Its stopping mass is followed by p_t(y)=t·p_(t−1)(x)/(t±y), with the sign determined by the step direction and outward-rounded endpoints in 2⁻⁹⁵ units. The unrestricted optimal computation uses the same quadratic frontier and binomial-mass reset every 128 layers as the original heat.c. It checks directly that the downward exercise approximation loses at most 1,000,000 weighted units on every layer. Thus each exact clipped root lies between its printed lower value and that value plus t+1,000,000 weighted units. Exercise does not accumulate this allowance at every draw because once a path exercises, its recursion ends.
The lower wall has magnitude 14,200 on the entire sweep, and n exp(−14200²/(n+1/2)) ≤ n·2⁻⁶⁵ < 200·10⁻¹⁵ dollars. This is checked with integer arithmetic. The positive frontier is either an optimal stopping state or the fixed policy's prescribed exercise boundary. At each even time the joiner bounds the difference of the two lower weighted values by ±(t+1,000,000) units, divides outwards by the central mass using independently calculated interval endpoints, and includes the wall allowance. The resulting root intervals include the four directly reported Fable payoffs at every common sampled large deck. This implementation places no faith in the independent long-double solver’s truncation or hardware floating-point rounding.
~~~bash
set -e
cc -O3 -march=native -std=gnu11 heat_tail.c -o /tmp/heat-tail
cc -O3 -std=gnu11 heat_join.c -o /tmp/heat-join
for k in 0 1 2 3 4; do /tmp/heat-tail "$k" "/tmp/heat-$k.u64" & done
wait
/tmp/heat-join /tmp/heat-{0,1,2,3,4}.u64
~~~
The five sweeps ran on separate cores of the same EPYC host in 17.0 seconds wall time. The first four numbers after each sampled N in heat-joined.txt are the two pairs of lower/upper endpoints for the old hybrid and the mixed hybrid. The next four numbers are the corresponding endpoints for half-card and uninterrupted 79. All endpoints are in 10⁻¹⁵ dollars. The long fixed-policy dominance audit took 168 seconds on one core.
### All-size central and square-root price bounds
Let $n$ be the number of red cards and the number of black cards in the initial deck.
Let $V_n$ be the optimal expected dollar payoff, $\alpha$ the Brownian stopping threshold, and $K=(1-\alpha^2)\sqrt\pi$.
For every natural $n$, including $n=0$,
$$
K\sqrt n-0.137(2n+1)^{-1/5}\le V_n
\le (1-\alpha^2)\frac{4^n}{\binom{2n}{n}}
\le K\sqrt{n+\tfrac12}.
$$
The mathematical bounds now cover inputs below the original cutoff.
The machine-entry theorem keeps its original domain.
##### Independent finite check
The analytic lower estimate already applies at $n\ge32768$, and the central-binomial upper estimate at $n\ge1800$.
The C++17 checker closes both finite gaps by integer Bellman induction.
With $t$ cards remaining and score $x=b-r$, drawing has expected value $((t-x)V_{t-1}(x+1)+(t+x)V_{t-1}(x-1))/(2t)$.
The player can always take $\max(x,0)$ dollars by stopping or exhausting a balanced deck.
Only reachable integer scores of the correct parity are used.
The lower sweep restricts play to $-2048\le x\le256$.
It takes $\max(x,0)$ at a strip wall or physical edge, rounds continuation down to a multiple of $2^{-30}$, and maximizes against $\max(x,0)$ in the interior.
The upper sweep retains all reachable scores, rounds up at the same scale, and takes exact values at the physical edges.
Nonnegative transition weights and monotonicity of the maximum prove the bounds inductively.
All unscaled lower values are at most 256, and the two transition weights sum to $2t\le131068$, so a lower numerator fits in 56 bits.
For the upper sweep the values are bounded by 3598 by induction, since rounding up preserves an integral maximum on the working grid.
Here $2t\le7196$, so the upper numerator including rounding fits in 55 bits.
The final square and binomial comparisons use GMP integers.
At each finite lower root let $d$ be the least positive integer with $d^5\ge10^5(2n+1)$.
The checker tests $0.522038\sqrt n\le L_n+137/(100d)$ by squaring nonnegative sides.
Since $K<0.522038$ and $d\ge10(2n+1)^{1/5}$, the lower inequality follows.
At each finite upper root it checks $U_n\le0.522037\sqrt{n+1/2}$ and $U_n\le(58905/200000)\,4^n/\binom{2n}{n}$.
The archived coefficient brackets give $0.522037
### Neutral urns and the recurrence-rank experiment
Let r positive (red) and b negative (black) cards remain, and let x=b-r. All suffixes have weight C=binom(r+b,r). The integer stopping total is xC. The draw total is A(r-1,b)+A(r,b-1), omitting missing children, where A is the optimal final-balance total. This tests the two actions themselves, before taking their maximum. Exhaustion has no draw action and is excluded. On the one-color axes the selected action is strict.
The exact square through 8,192 cards of each color has 32,982,291 strict stops, 34,142,956 strict draws, and one equality. That equality is r=1, b=2. Both action totals are 3 over the three possible suffixes. The equal-action state is unchanged by adding a constant to all current and final scores.
The rectangle 0≤r≤8192, 0≤b≤8555 had 35,950,622 strict stops, 34,148,684 strict draws, and one equality. Its last column was verified to consist entirely of strict stops. In general, if the last column b=B>8192 consists entirely of strict stops, all later columns consist of strict stops too. Induct on b and then on r inside each column. When both possible child values are cash, the expected cash after one draw is x−x/(r+b)0. The same calculation applies with the appropriate single child on the red-empty axis. Hence the finite rectangle verifies the search for every black count when r≤8192. For r>8192, b≤8192, current cash x is negative while drawing until exhaustion guarantees zero. This extension establishes the finite red-count range without assuming a stopping-boundary formula. Boyce conjectured that this is the only neutral urn for arbitrary counts (1973, §5).
risk.py separately counts living prefixes in the 52-card deck. There are 12,871,862,985,715 surviving prefixes with three cards left at the tie. Each prefix has three equiprobable completions, RBB, BRB and BBR. Cashing now earns 1. Drawing and then following the strict optimal actions earns 2,1,0 after 1,2,3 extra draws. Thus the entire change in zero-payout probability and mean duration equals p/3 and 2p, respectively, where p=443857344335/5700213022392 is the tie visitation probability. The program independently recomputes the initial expected price and both complete outcome histograms for the two conventions.
rank.cpp works modulo 2147483647. For proposed recurrence order r and coefficient degree d it forms a square matrix of C=(r+1)(d+1) rows, indexed by n=0,…,C-1, and columns (j,k), j=0,…,r and k=0,…,d. An entry is n^k D_(n+j), with D_n the integral normalized diagonal as calculated by ties.cpp. A nonzero determinant modulo this prime proves full column rank over the rationals and reals, excluding recurrences of that order and degree valid on the sampled rows. The infinite non-P-recursiveness theorem has a separate proof.
|r|d|C|determinant modulo 2147483647|
|---:|---:|---:|---:|
|1|300|602|2107471273|
|2|200|603|32920820|
|3|150|604|887925844|
|5|100|606|1846400590|
|8|66|603|1039805697|
|12|46|611|1227701472|
|20|28|609|732207642|
Build and reproduce from this directory (C++17, GMP, Python 3).
~~~bash
set -e
c++ -std=c++17 -O3 ties.cpp -lgmpxx -lgmp -o ties
./ties 8192 --all-black-counts
./ties 640 --diagonal > D640.txt
c++ -std=c++17 -O3 rank.cpp -lgmpxx -lgmp -o rank
./rank < D640.txt
python3 risk.py
~~~
### Stronger preview and message calculations
Let $N=2n$ denote total cards and $H$ the maximum score on the deal. A signal with $i$ possible messages lets an oracle pick the best of $i$ ordinary stopping rules on each deal. Its value $V_i$ equals the optimal expected maximum of $i$ online nominations. One bit means two messages. The percentage is $100(V_i-V_1)/(EH-V_1)$. A rolling preview of the next $k$ cards is a different information source.
##### Pre-game labels
The supplied C program reproduced all F6 two- and three-label figures (fable.txt). For 52 cards the percentages are 43.20989% and 63.57269%. Three messages exceed half at 8,192 cards (50.23075%) and miss it at 16,384 (49.92094%). The independently bounded runs in finite.txt extend these figures. Richardson extrapolation assuming a leading correction proportional to $N^{-1/2}$ supports 33.2% and 49.2%. The actual limits and the proposed asymptotic necessity of a fourth label remain open. The separate Brownian two-label upper bound of 35% is consistent with these results. The archive already proves sufficiency of four messages in the limit via an explicit menu reaching at least 0.4997753 per square root of total cards, above the 0.4978967 target.
| Total cards | One bit, 2 messages | 3 messages |
|---:|---:|---:|
| 32,768 | 33.51263% | 49.70215% |
| 65,536 | 33.40802% | 49.54751% |
| 131,072 | 33.33408% | 49.43817% |
| Last-doubling extrapolation | 33.15559% | 49.17420% |
Entries are interval midpoints rounded for display. At 131,072 cards the rigorous intervals are [33.33406912, 33.33409813]% and [49.43815615, 49.43818235]%.
The extended implementation uses the supplied recurrence with a narrower absorbing score band $[-w,w]$, $w=\min(n,\lceil\sqrt{18n}\rceil)$, and hexadecimal output. For the clip error set $R(k)=\binom{2n}{n+k}/\binom{2n}{n}$. A positive-wall hit can lose at most $(H-w)^+$. At the negative wall the incumbent is retained, so losing a subsequent level $j>0$ requires ordered hits of $-w,+j$. Two successive reflections count these paths by $R(w+j)$. Thus the price increase from removing the walls lies between zero and $2\sum_{j\ge1}R(w+j)$, bounded using the ratio of consecutive binomial coefficients. This holds for each nomination budget. The prophet mean is exactly $(4^n/\binom{2n}{n}-1)/2$.
For the binary64 recurrence let $u=2^{-53}$. Children have exact value at most $n$. When their computed values differ by at most 1, rounding both probabilities, both products and the sum adds at most $8(n+1)u$ to the local absolute error. This uses $|\mathrm{RN}(z)-z|\le u\max(1,|z|)$, valid also for subnormals. A stochastic average and a maximum each preserve a uniform error bound. The same-row nomination alternative uses an already evaluated maximum with the current banked score, adding no second arithmetic step. Induction through $2n$ rows gives $16n(n+1)u<1$ for the cases here. The checker then bounds the shares using exact rational arithmetic and outward decimal rounding. This numerical certificate assumes IEEE binary64 nearest rounding and separate multiply and add.
##### Rolling preview
Let $v(d)$ be the maximum expected trailing-window peak at a Brownian-bridge stopping time, with window length $d$ on a unit-duration bridge. The archive proves that the limiting required fraction $d_*$ exists and uniquely solves $v(d_*)=T$, where $T=(3/2-\alpha^2)\sqrt{\pi/2}/2=0.49789672\ldots$. The calculation below improves the strict upper bound from $1/20$ to **$1/30$**. Together with the archive's lower bound, $1/1280
(3/2-0.83992^2)\cdot1.25332/2=0.497902923093376>T.
$$
Thus 3⅓% of a large deck is more than enough in the limit. The archive's certified finite thresholds point near 2%, but do not determine two significant digits. Fitting the first total deck size at each change $k=12,\ldots,30$ gives $d=0.01963$ for $k=dN+c$ and $d=0.01787$ for $k=dN+a\sqrt N+c$. Restricting to $k=20,\ldots,30$ gives 0.01945 and 0.01715. Neither model comes with a finite-size remainder bound. The block policy is a rigorously priced restriction of the Brownian problem. Its threshold need not be optimal.
##### Reproduction
~~~sh
set -e
gcc -O3 -march=native -ffp-contract=off p14_three_messages.c -lm -o fable
./fable 26 1024 2048 4096 8192 16384
gcc -O3 -march=native -ffp-contract=off extended.c -lm -o extended
./extended 26 4096 8192 16384 32768 65536 > extended.hex
python3 check_extended.py < extended.hex
python3 block_atoms.py 32 > block_atoms_fine.txt
c++ -std=c++17 -O3 block_bound.cpp -o block
./block 30 32768 < block_atoms_fine.txt
python3 threshold_fit.py thresholds.csv
~~~
### Primary sources and historical attribution
**Boyce’s numerical rule.** Ann R. Martin computed the boundary with exact integer arithmetic. Boyce gives, for $2\le p\le100$ remaining plus balls and $m$ remaining minus balls, the following empirical characterization of strictly positive future value:
$$
m
V(m,p)$.
Writing $\beta(p)$ for the largest strictly favorable $m$, this yields $\beta(p+1)\ge\beta(p)+1$. The first zero-value urn under the stop-on-ties convention is $T(p)=\beta(p)+1$, hence $T(p+1)\ge T(p)+1$.
In §5 the sole nonempty neutral urn reported through $p=100$ is $(m,p)=(2,1)$, which corresponds to $(t,x)=(3,1)$. For that state both stopping and drawing once optimally return zero *incremental* value. Boyce explicitly presents uniqueness over all urns as a conjecture. For a standard deck, the finite result covers all reachable states, so the two actions at this single state account for the difference between the draw-on-ties and stop-on-ties payoff laws. Policies can of course differ on unreached histories, or randomize on the tie. [Boyce 1973, Theorem 3.8, p. 304](https://sites.math.rutgers.edu/~zeilberg/EM13/boyce1973.pdf#page=8 "On a simple optimal stopping problem") · [Boyce 1973, p. 309](https://sites.math.rutgers.edu/~zeilberg/EM13/boyce1973.pdf#page=13 "Neutral urns")
**Shepp’s original claim.** The Wharton file has 19 pages. Only its JSTOR cover is text-searchable with ordinary PDF extraction. Section 6(a,b) occupies printed pp. 999–1001, PDF pages 8–10. Shepp defines favorability by strictly positive future value. He gives the favorable boundary’s leading term in (6.1) and solves the continuous pinned-Wiener problem via a deterministic time change in (6.2)–(6.5). Equation (6.5) stops at $u+W^*(s)\ge\alpha\sqrt{b-s}$. In (6.6), $u=(m-p)/\sqrt{m+p}$ and the terminal bridge value is $-u$. He describes the discrete limiting step as formal. For the value limit (6.7), including $V(p,p)\sim(1-\alpha^2)\sqrt{\pi p}$, he explicitly says he did not supply the rigorous proof.
The paper even contains a sign error adjacent to this warning. The sentence under (6.7) puts $V(u,1)=u$ on $u\le\alpha$. Formula (1.4), the direction of the stopping boundary, and $V(0,1)>0$ give the correct stopping side $u\ge\alpha$.
[Shepp 1969, §6(a,b)](https://faculty.wharton.upenn.edu/wp-content/uploads/2012/04/Explicit-solutions-to-some-problems-of-optimal-stopping.pdf#page=8 "Explicit Solutions to Some Problems of Optimal Stopping") · [Shepp 1969, eq. 6.7](https://faculty.wharton.upenn.edu/wp-content/uploads/2012/04/Explicit-solutions-to-some-problems-of-optimal-stopping.pdf#page=10 "Discrete urn-value limit")
**What the half correction predicts.** Lai, Yao and Aitsahlia’s $n$ is the total number of remaining balls, equal to our $t$. Their integer negative remaining worth is $k=2m-n=x$, of the same parity as $n$. They define a real negative worth $w$ by replacing one ball’s payoff with a number in $[-1,1]$, then define $\beta(n)$ as the smallest $w$ at which the urn has zero value. Their integer first-stop level $\bar\beta(n)$ satisfies $\bar\beta(n)-2<\beta(n)\le\bar\beta(n)$. It is important to specify which boundary is being estimated. The real threshold in a fractional-payoff urn, the first admissible lattice boundary in an integer urn, and a boundary estimated by recording the first time a level changes need separate definitions.
Section 4 proposes $\beta(n)=\alpha\sqrt n-1/2+o(1)$ by formal application of Theorem 3.1 and tabulates numerical evidence in Table 1. The authors explicitly single out the unbounded derivative of the limiting square-root boundary at zero as the obstacle to proving it by their theorem. They attribute the earlier numerical conjecture to Gordon Simons, whose 1987 article studied this same urn and already proposed an empirical third-order rule. This credit predates both the new regressions and the 2007 paper. [Lai, Yao & Aitsahlia 2007, §4, pp. 768–770](https://www.cambridge.org/core/services/aop-cambridge-core/content/view/4D97D8DB08C5D96C95E3858128A21C07/S0001867800002032a.pdf#page=17 "Corrected random walk approximations to free boundary problems in optimal stopping") · [Simons 1987](https://doi.org/10.1016/0167-7152(87)90025-3 "Easily determining which urns are ‘favorable’")
### Simons's two conjectures
Let $B_t$ be the smallest admissible score at which the optimal incremental value vanishes with $t$ cards remaining. Thus $B_t\equiv t\pmod 2$. Tze Leung Lai, Yi-Ching Yao and Farid Aitsahlia attribute to Gordon Simons two numerical conjectures about this *integer* boundary. For $h\in\{0,1/2\}$ put
$$
C_N(h)=\frac{1}{N}\#\{1\le t\le N:B_t-2<\alpha\sqrt t-h\le B_t\}.
$$
The proposed limits are $C_N(0)\to3/4$ and $C_N(1/2)\to1$. The strict lower endpoint and inclusive upper endpoint matter: the event means rounding the proposed cutoff *up to the lattice of parity* $t$ gives precisely $B_t$. These are frequencies among deck sizes. They are different quantities from the probability of a suboptimal choice on a random deck path or the expected payoff lost to such a choice. Separately, the authors formally predict $\beta(t)=\alpha\sqrt t-1/2+o(1)$ for the real fractional-ball boundary. They observe that this expansion implies the density conjectures by equidistribution, and explicitly report that their general boundary theorem did not provide a rigorous proof for this urn. [Lai, Yao & Aitsahlia 2007, p. 769](https://www.cambridge.org/core/services/aop-cambridge-core/content/view/4D97D8DB08C5D96C95E3858128A21C07/S0001867800002032a.pdf#page=17 "Corrected random walk approximations to free boundary problems in optimal stopping")
Simons's own 1987 publisher abstract describes an empirical third-order approximation. It omits the third term's power, coefficient and sign. The institutional catalogue searches, publisher preview, bibliographic indexes and citing materials available for this audit did not produce the full six pages or a transcription of that term. The original abstract supports credit for an earlier empirical third-order proposal. The proposed positive quarter-power term in the new fit cannot be identified with Simons's term on that evidence. [Simons 1987](https://doi.org/10.1016/0167-7152(87)90025-3 "Easily determining which urns are ‘favorable’")
The original 1969 source cited by Simons, Boyce and Lai et al. is Shepp's *Annals of Mathematical Statistics* paper, pp. 993–1010. Shepp states the first-order discrete frontier limit in (6.1), solves the corresponding continuous stopping problem in (6.2)–(6.5) and presents the passage from the discrete game as formal on p. 1001. The paper expressly disclaims a proof of the more general *value* convergence (6.7). Boyce restates the first-order frontier result in his equation (1). Neither that historical attribution nor the bridge solution provides a proof of the half-unit correction. [Shepp 1969, pp. 1000–1001](https://faculty.wharton.upenn.edu/wp-content/uploads/2012/04/Explicit-solutions-to-some-problems-of-optimal-stopping.pdf#page=9 "Explicit Solutions to Some Problems of Optimal Stopping") · [Boyce 1973, p. 298](https://sites.math.rutgers.edu/~zeilberg/EM13/boyce1973.pdf#page=2 "On a simple optimal stopping problem")
## 9. Verification record
**Independent checks and new results.** An independent December 2026 review proposed the half-card shift, the one-sided spectral root, and the limiting ballot–Kraft constant. It identified both distribution failures and several defects in the original numerical analysis. The critical-exponent comparisons, all-size half-card certificates, coding-length analysis and formal compositions in this edition were developed and checked separately. The external reproduction recovered all 306 files of the first edition and ran the ordinary solvers, advice programs, compact executable and integer core of the kernel module. Its inspection of the 108 original Lean sources was static. The release verification below used the pinned Lean compiler; its guest-device experiment is separately identified. The new full-history modules were replayed against those sources with Lean 4.19.0 and matching mathlib. The analytic spectral and coding arguments are written proofs. The policy certificates use directed integers. High-precision special-function evaluations and estimates of the limiting amplitude are numerical.
A second independent calculation used a wider negative cutoff for optimal zero-payoff probabilities. Exact integers on small decks and directed intervals for large finite-deck regret give stronger checks where available. The two accompanying C programs, selected CSV rows and original plot from Fable's audit appear in the embedded source under `review/fable/independent/`. That audit covered the 306-file first edition. It statically inspected the Lean sources, replayed seven of its certificate programs, and left timing measurements and machine code untested. There are four operative `native_decide` invocations in that edition. Plain text matches also count mentions in comments. The expanded all-size price proof adds one invocation and reports its native-reduction dependency explicitly.
The price-gap exponent, two-sided actual regret, optimal survival, boundary-density and continuous half-dollar results have written mathematical proofs. The integer Bellman regret identity and the all-size price inequalities have independently replayed Lean theorems. The parabolic-cylinder asymptotics and the non-P-recursiveness argument still require ordinary mathematical review.
The clean Lean 4.19.0 replay built all 70 project modules in the dependency graph of the new and revised results from source in 125.93 seconds, starting with zero project object files and a built mathlib v4.19.0. The three regret-accounting theorems use only `propext` and `Quot.sound`. The two all-deck price theorems also use `Classical.choice` and `Lean.ofReduceBool`. The complete transcript is `review/fable/check-lean.log`. This counts the new dependency closure; the full edition includes further formal modules covering the other problems and implementations.
The original executable test could see only the process stack while Linux was still loading the image. Four workers reproduced this with their first failures on attempts 18, 11, 55 and 48. The new test fills stdout before launch, waits for the executable’s diagnostic on a separate pipe, then reads its mappings while its stdout write is blocked. Across the two images, 2,000 checks passed. The output and exit-status suites passed using the seccomp backend. This host restricted ptrace, so those repetitions give no fresh strace trace.
The first public text mirror reproduced the raw Markdown exactly after GNU `fold -s -w 80`, including its extra 20,717 bytes. Hard wrapping split both source lines and the original extractor. Section 12 stores an independent 64-column representation of the entire project; Section 10 gives its short bootstrap. An extraction test checks all members and modes before and after the mirror’s actual transformation and after CRLF conversion. A deliberate payload mutation must fail archive verification.
Fresh replay used Linux x86-64, GCC/G++ 14.2.0, GMP 6.3.0, Python 3.12.16 and stock Lean 4.19.0. Twelve independent suites completed successfully in clean build directories. A separate pinned mathlib replay also checked the full 55-module project graph through `asmproof.GameMachinePrice`. It built 32 modules in the mathlib-enabled pass and reused 23 modules already built in the stock-Lean pass. The two native finite cutoff checks were included. The axiom reports for `P14Entry.game_bounds`, `machine_encloses_game` and `printed_game` were identical: `propext`, `Classical.choice`, `Lean.ofReduceBool` and `Quot.sound`. As an independent end-to-end check, the released scalar executable was run on the three record inputs; generated Lean proofs linked each actual printed microdollar record to the real game. The audited declarations are in `asmproof/RecordReplay.lean`, with the three stdout records in `verification/record-prices.txt`. Four rebuilt images matched their released counterparts byte for byte. The historical performance tables and kernel-guest timings retain their original measurement conditions.
| Suite | Checks reproduced |
|---|---|
| Ordinary solver | The full top-level make check completed. It compiled the six standard solvers, additional frontier and comparison programs, and eight Lean modules following the core game. Checks included 485 numerical intervals, 1,307 intermediate layer enclosures, 10,004 survival weights, 527 packed-table checks, 375 weighted-heat cases, 176 Catalan intervals, the exact and asymptotically fast solver comparison, and the independent fifth-root calibration. |
| Actual answers | The exact solver returned 41984711742427/15997372030584 for 26 pairs. The price program returned 6038.22, 11673.12 and 522037.68 for 133787000, 500000000 and 1000000000000 pairs, with microdollar endpoints agreeing with the releases. |
| Machine code | Targets check-asm, check-batch, check-inverse-image, check-minelf and proof-minelf-headers passed. All 14,893 threshold words, 440 linked inverse-path bytes, parser/CLI cases, 90,786 compact-solver cases, and three actual ELF headers checked. The rebuilt price-asm, price-flat, price-minelf and price_batch binaries matched their four archived counterparts byte for byte. The stock Lean proof-asm and proof-minelf targets both completed; the compact proof checked eight actual printed records. Both image layouts and output/exit paths also passed the Linux runtime checks under a seccomp syscall allow-list. |
| Module arithmetic | The kmod test-integer target found exact agreement on 242,201 inputs. The compiled freestanding object had no undefined symbols and contained no floating-point or vector instruction. |
| Playing and advice | The bounded quadratic rule and its eight-byte action routine passed native and standard-library Lean checks. A separately compiled directed-integer verifier located the four offending states and the first loss at 8,243 pairs, reproduced the denominator-79 frontier, and agreed with an exact rational oracle on five decks. A fresh sweep through all 65,535 pair counts reproduced the uniform regret cap 34673417/281474976710656 dollars. |
| Small-deck signals | Python checked all 1,378 fixed singleton/pair announcements, the optimal fair 52-card bit, and all capped-peak budgets on decks through 40 pairs. Exhaustive C++ enumerated 524,288 binary partitions of the six-card deck up to relabeling. The full-history one-bit stock Lean certificate checked its exact aggregate, price and premium. |
| Preview | The rolling-window suite matched 48 exact fractions and 120 raw-history band calculations. The stock-Lean voucher certificate checked all 22 standard-deck table values, full strategy attainability, and saturation at exactly 21 vouchers; its reported axioms were propext and Quot.sound. The voucher software tests passed. The independent 20-block Brownian window lower check, including direct quadrature spot checks, returned 2053/4096. |
| Final follow-ups | Both stock Lean files, the quartic certificate, the directed integral certificate giving 0.4592, a byte-for-byte regeneration of all 17 three-message results through 16,384 pairs followed by the independent checker, the 8,192-pair four-message lower construction, and the variable-length prefix-code checker passed. The last reproduced 2.913090992940 and 3.052301273338 expected bits as the lower and upper endpoints, and 3.116571425843 bits for peak-only coding. |
For the new guarantee, the full finite integer sweep, policy-specific cutoff, exact product threshold, 64-bit coefficient and no-wrap lemmas, independent rational small-deck tests, and arbitrary-precision decision tests were also run. There were 266,478 successful native comparisons against an independent integer predicate. The 64-bit tests include near-boundary cases and the largest remaining count. These sampled native calls supplement an all-layer match of the squared coefficient through 482,618 cards. Lean separately proves the cutoff-transport principle and the scalar threshold for the more conservative multiplier 1/5. For the policy-specific multiplier, `CentPolicyCap.first_subcent` proves the exact 218,593-pair transition, `large_cap` proves the tighter endpoint from 241,310 pairs onward, and `small_cap` puts the finite-sweep numerator under the same cap. The first two scalar lemmas share a native integer computation. The Python product calculation independently checks them. `CentQuick.lean` also verifies the more conservative 1/5-multiplier threshold with a kernel-only 1,000-factor check.
The 700-pair rolling-preview classification is supplied as per-deck numerical evidence, with a smaller independent replay of the recurrence. Loading the kernel in a guest, retiming thousands of programs, and stress-testing every unbounded mathematical premise have distinct verification procedures. The actual kernel-module test was performed in the documented guest. The native device latency remains unmeasured.
## 10. Extracting and running the project
The following commands need Python 3 and a POSIX shell. Set `report` to the filename of this document, including when it has a `.txt` extension. The first invocation verifies the archive in memory. The second writes a new directory. Neither executes the embedded project. The digest detects accidental corruption and carries no signature.
```sh
set -e
report=problem-14-stopping-game-complete.md
tr -d '\r' < "$report" |
awk '/^$/{exit} p; /^$/{p=1}' \
> unpack.py
python3 unpack.py "$report"
python3 unpack.py "$report" problem14-review
cd problem14-review
```
The printable archive uses 64 ASCII characters per payload line. All lines of the bootstrap fit in 72 columns. The human-readable code listings can wrap in a text mirror. The bytes compiled by the procedure below come from the independent encoded copy.
```python
"""Extract the Problem 14 source edition using Python 3."""
import base64
import hashlib
import io
import json
import sys
import zipfile
from pathlib import Path, PurePosixPath
def block(lines, name):
start = ""
end = ""
if lines.count(start) != 1 or lines.count(end) != 1:
raise ValueError("missing or repeated " + name)
return "".join(lines[lines.index(start) + 1:lines.index(end)])
def sha(data):
return hashlib.sha256(data).hexdigest()
def main():
if len(sys.argv) not in (2, 3):
sys.exit("usage: python3 unpack.py REPORT [NEW_DIRECTORY]")
lines = Path(sys.argv[1]).read_bytes().decode(
"utf8", errors="replace").splitlines()
data = base64.b64decode(block(lines, "P14ZIP"), validate=True)
if sha(data) != block(lines, "P14SHA"):
sys.exit("archive SHA-256 mismatch")
target = Path(sys.argv[2]) if len(sys.argv) == 3 else None
with zipfile.ZipFile(io.BytesIO(data)) as archive:
entries = json.loads(archive.read("MANIFEST.json"))
names = archive.namelist()
if sorted(names) != sorted([*entries, "MANIFEST.json"]):
raise ValueError("archive member list mismatch")
for name, info in entries.items():
path = PurePosixPath(name)
if path.is_absolute() or ".." in path.parts:
raise ValueError(name)
payload = archive.read(name)
if len(payload) != info["bytes"] or sha(payload) != info[
"sha256"] or info["mode"] not in (420, 493):
raise ValueError(name)
if target:
target.mkdir(parents=True, exist_ok=False)
for name, info in entries.items():
path = target / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(archive.read(name))
path.chmod(info["mode"])
(target / "MANIFEST.json").write_bytes(
archive.read("MANIFEST.json"))
print(f"Verified {len(entries)} files. Archive {sha(data)}")
if __name__ == "__main__":
main()
```
**Reproduce the original all-deck guarantee.** Run at the extracted root. The native player uses unsigned 128-bit multiplication with GCC or Clang. Enable the assertions when building certificate programs. The finite sweep emits one aggregate line by default and accepts an optional output file for all balanced roots. `play.py` also gives a human-readable action from a feasible remaining count and balance.
```sh
set -e
cc -O3 -std=gnu11 cent/analytic/cutoff79.c -o cutoff79
./cutoff79
python3 cent/analytic/cent_product.py
cc -O3 -std=gnu11 cent/fast/certify.c -o cent-certify
./cent-certify 482618
python3 cent/fast/test.py
python3 cent/native/check_play64.py
python3 cent/native/play.py
python3 cent/native/play.py 17 3
python3 cent/native/play.py 19 3
lean cent/native/Play64.lean
bash cent/formal/check.sh
```
**Reproduce the ordinary prices and selected information results.** The first command builds the GMP/CPU reference solvers, checks the stock Lean core and runs the main numerical regression suite. The rolling and scaled analytic tests have additional modes in the source listings.
```sh
set -e
make check
./exact 26
./price 133787000 500000000 1000000000000
python3 quote.py 1000000000000000000000000000000
bash further/formal/check-bit.sh
bash further/formal/check.sh
python3 followups/onebit_integral.py
python3 followups/check_three_messages.py < followups/three_messages.hex
python3 followups/four_messages.py 8192
python3 followups/variable_advice.py
```
**Reproduce machine proofs.** On x86-64 Linux with GNU binutils, `make proof-asm` and `make proof-minelf` check the stock-Lean and binary obligations. With a built mathlib v4.19.0 checkout including its pinned dependencies, run `make proof-asm-full MATHLIB=/absolute/path/to/mathlib4` and `make proof-minelf-full MATHLIB=/absolute/path/to/mathlib4` for the analytic game link. The packet includes the project’s Lean sources, plus application code, tests, sample data, and exact release images. The named build dependency is **Lean 4.19.0**. The package includes no third-party toolchain or mathlib checkout. On any computer with a suitable browser the extracted `Problem-14-Card-Table.html` plays six standard-deck information contracts offline.
The main text and mathematical appendices can be read independently of the listings. A reviewer with a limited context window can use `cent/` for the new theorem, the root-level Lean files and `asmproof/Game*` for ordinary value, `further/formal/` and `further/signals/` for advice, or `minelf/` for the systems claim. Preserve the complete file for extracting the project.
**Reproduce the half-card comparison and full-history theorems.** From the extracted project root, run the commands below. The optional row file lists every balanced starting size in integer units. The six new Lean modules use the compiled analytic graph and the mathlib path, as specified in `review/formal/README.md`. The numerical eigenvalue and phase checks list their additional Python dependencies in their respective source files.
```sh
set -e
cc -O3 -std=gnu11 review/rule/certify.c -o half-check
./half-check half-results.tsv
python3 review/rule/exact.py
python3 review/peak-limit.py
```
The next block checks the largest cutoff, the native and arbitrary-integer players, the eigenvalue, and the clean regression. Run in the extracted root. The full sweep writes a temporary text file of roots to permit the independent uniqueness check. The spectral check uses mpmath, and the optional phase computation above uses SciPy.
```sh
set -e
python3 review/rule/inspect.py < half-results.tsv
cc -O3 -std=gnu11 -DEXTEND review/rule/certify.c -o half-extend
./half-extend half-extended.tsv
python3 review/rule/inspect.py < half-extended.tsv
cc -O3 -std=gnu11 review/rule/cutoff.c -o half-cutoff
./half-cutoff 1048576 17 1 300000
./half-cutoff 1048576 17 2 300000
python3 review/rule/test_players.py
cc -O3 -std=gnu11 review/rule/half64.c -o half64
./half64 --hybrid 17 3
python3 review/spectral_check.py --observations review/observations.txt
python3 review/reproduce-regressions.py review/observations.txt
make check-minelf-runtime
```
To replay the additional Lean modules, set `MATHLIB` to the absolute path of a built mathlib v4.19.0 checkout, with its pinned dependencies. This uses Lake to resolve the search paths against that checkout. The ordinary analytic build produces the local compiled modules.
```sh
set -e
project=$(pwd)
make proof-asm-full MATHLIB="$MATHLIB"
mlpath=$(cd "$MATHLIB" && lake env python3 -c '
import os
from pathlib import Path
parts = os.environ["LEAN_PATH"].split(os.pathsep)
print(os.pathsep.join(str(Path(p).resolve()) for p in parts if p))')
P14_ANALYTIC_LEAN_PATH="$project/.asm-build:$mlpath" \
bash review/formal/check.sh "$project"
```
### Replaying the independent review and new certificates
From the extracted project root, the following examples replay the integer core of the review. The Lean runner uses the pinned Lean and mathlib environment described in the formal verification section. GCC or Clang and the GMP development headers are needed for the exact native checkers.
```sh
set -e
# Set MATHLIB to the local, built mathlib v4.19.0 checkout.
: "${MATHLIB:?supply the mathlib checkout path}"
export MATHLIB
bash review/fable/check-lean.sh
python3 review/fable/sources/replay_boyce.py
c++ -std=c++17 -O3 review/fable/advice/block_bound.cpp -o /tmp/p14-block
/tmp/p14-block 30 32768 < review/fable/advice/block_atoms_fine.txt
python3 review/fable/advice/check_extended.py < review/fable/advice/extended.hex
```
The finite-peak worksheet includes commands for its 92-bit and heat-kernel checks. It gives exact conventions for peak ties and the range of deck sizes checked. The information worksheet documents floating-point assumptions for the message calculations and the exact arithmetic used in the 30-block proof.
## 11. Readable source listings
All 117 Lean modules and the implementation sources are printed below. The complete 468-file project, including its data, proof worksheets and executable images, is in Section 12. The path above each listing is relative to the project root.
#### `review/article-edits/check_article_numbers.py`
~~~~python
"""Check the arithmetic behind the proposed corrections using Python 3."""
from fractions import Fraction
from functools import cache
from pathlib import Path
import re
import sys
@cache
def game(r, b, hybrid=False):
if not r:
return Fraction(b)
if not b:
return Fraction(0)
p = Fraction(1, 2) if hybrid else Fraction(r, r+b)
draw = p*game(r-1, b, hybrid)+(1-p)*game(r, b-1, hybrid)
return max(Fraction(b-r), draw)
source = Path(sys.argv[1]).read_text()
checked = 0
for line in source.splitlines():
row = re.match(r'>\s+\*\*(\d+)\*\*\s+(.*)', line)
if row is None:
continue
r, values = int(row[1]), row[2].split()
assert len(values)==27
for b, printed in zip(range(26, -1, -1), values):
expected = format(float(game(r,b)), '.4g')
assert Fraction(printed)==Fraction(expected), (r,b,printed,expected)
checked += 1
assert checked == 729
assert game(26,26,True)==Fraction(805867616040669,281474976710656)
print(f'Spreadsheet cells matching the four displayed significant digits: {checked}.')
print('Forced-edge, half-probability interior:', game(26,26,True), float(game(26,26,True)))
print('Original, 26 pairs:', game(26,26))
# For the mnemonic, either action is acceptable at an exact tie.
first_strict_error = None
ties = []
for r in range(33):
for b in range(33):
if r+b == 0:
continue
x, t = b-r, r+b
draw = ((r * game(r-1,b) if r else 0)
+ (b * game(r,b-1) if b else 0)) / t
stop = x > 0 and (x+2)**2 >= t+8
chosen = x if stop else draw
if max(r,b) <= 26 and draw == x:
ties.append((r,b))
if chosen < game(r,b):
candidate = (max(r,b),r,b)
if first_strict_error is None or candidate < first_strict_error:
first_strict_error = candidate
assert ties == [(1,2)]
assert first_strict_error == (32,26,32)
print('52-card mnemonic and unique tie checked; first strict error at 32 pairs.')
~~~~
#### `review/article-edits/check_listing_c.py`
~~~~python
from pathlib import Path
from fractions import Fraction
from math import isclose
from subprocess import run
import re,sys
# Usage: python3 check_listing_c.py ORIGINAL.md PATCHED.md
from tempfile import TemporaryDirectory
sandbox = TemporaryDirectory()
base = Path(sandbox.name)
pattern = r'^~~~\{([^}]+)\}\n(.*?)^~~~'
old = re.findall(pattern, Path(sys.argv[1]).read_text(), re.M | re.S)
new = re.findall(pattern, Path(sys.argv[2]).read_text(), re.M | re.S)
def build(i, src, changes=(), flags=(), fail=False):
p=base / f'listing{i}.c'; out=base / f'code{i}'
for before,after in changes:
assert src.count(before)==1, before
src=src.replace(before,after)
p.write_text(src)
result=run(['cc','-std=c11','-O2','-Wall','-Wextra',*flags,str(p),'-pthread','-lm','-o',str(out)],capture_output=True)
assert bool(result.returncode)==fail,(i,result.stderr)
return out, result.stderr
def output(exe,*args):
return run([str(exe),*args],text=True,capture_output=True,check=True,timeout=30).stdout
def value(n):
a=[[Fraction() for _ in range(n+1)] for _ in range(n+1)]
for r in range(n+1):
for b in range(n+1):
a[r][b]=r if b==0 else 0 if r==0 else max(0,(r*(a[r-1][b]+1)+b*(a[r][b-1]-1))/Fraction(r+b))
return float(a[n][n])
n=51
oo,_=build(6,old[6][1],[('i <= 100000',f'i <= {n}')])
oldrows=output(oo)
nn,_=build(6,new[6][1],[('const int blacks = 100000;',f'const int blacks = {n};')])
newrows=output(nn)
assert oldrows==newrows and len(newrows.splitlines())==n+1
print('rolling C: all 52 printed roots from 0 through 51 pairs byte-for-byte equal')
_,msg=build(11,old[11][1],fail=True)
assert b'count' in msg
print('old intermediate blocks: failed compilation on undeclared count')
for n in [1,2,10,26,40,80]:
for i in [9,10]:
c='int cards = 200000;' if i==9 else 'int cards = 100000;'
exe,_=build(i,new[i][1],[(c,f'int cards = {n};')])
val=float(output(exe).split()[-1])
assert abs(value(n)-val)<1e-6,(n,i,val)
for B in [1,2,5,13,20]:
if n%B: continue
for i in (11,12):
init=100000 if i==11 else 133787000
b=400 if i==11 else 1000
exe,_=build(i,new[i][1],[(f'#define NUM_CARDS {init}',f'#define NUM_CARDS {n}'),(f'#define BLOCK_SIZE {b}',f'#define BLOCK_SIZE {B}'),('#define NUM_THREADS 15','#define NUM_THREADS 4')])
val=float(output(exe).split('=')[1])
assert abs(value(n)-val)<5.1e-6,(n,B,i,val)
for i in (11,12):
init=100000 if i==11 else 133787000
b=400 if i==11 else 1000
_,msg=build(i,new[i][1],[(f'#define NUM_CARDS {init}','#define NUM_CARDS 26'),(f'#define BLOCK_SIZE {b}','#define BLOCK_SIZE 5')],fail=True)
assert b'BLOCK_SIZE must be positive' in msg
print('all corrected serial/parallel C smoke tests agree with rational Bellman roots; 26 pairs with block size 5 rejected')
~~~~
#### `review/article-edits/data-audit/article_roots.c`
~~~~c
/* Same row-major recurrence as the 2022 article. One run emits every diagonal. */
#include
#include
#include
#define AT(r, b) tab[((r)%2) * (blacks + 1) + (b)]
float calc(int reds, int blacks, int r, int b, float *tab) {
return !r ? 0 : !b ? r : fmax(0,
r*1.0/(r+b) * (AT(r-1, b) + 1) +
b*1.0/(r+b) * (AT(r, b-1) - 1));
}
int main(void) {
const int reds=22974, blacks=22974;
float *tab = malloc(sizeof(float)*2*(blacks+1));
if (!tab) return 1;
for (int r=0;r<=reds;r++) {
for (int b=0;b<=blacks;b++)
AT(r,b)=calc(reds,blacks,r,b,tab);
printf("%f\n",AT(r,r));
}
free(tab);
}
~~~~
#### `review/article-edits/data-audit/certify_rows.c`
~~~~c
/* Outward integer Bellman intervals for all balanced roots of even size 2n.
Default: the historical n=0..22974 grid. Define PAIRS and WALL to override. */
#include
#include
#include
#ifndef PAIRS
#define PAIRS 22974
#endif
#ifndef WALL
#define WALL 1024
#endif
typedef __uint128_t Wide;
typedef uint64_t Unit;
static const Unit scale = UINT64_C(1) << 46;
struct Interval { Unit lower, upper; };
static struct Interval row[2][2 * WALL + 1];
_Static_assert(2 * PAIRS < (UINT64_MAX >> 46), "price bounds must fit");
_Static_assert(WALL >= 2 && WALL <= 2 * PAIRS, "invalid wall");
int main(void) {
puts("0 0 0");
for (int t = 1; t <= 2 * PAIRS; ++t) {
unsigned den = 2 * t;
int radius = t < WALL ? t : WALL;
int parity = t % 2;
for (int x = -radius + (t + radius) % 2; x <= radius; x += 2) {
int i = x + WALL;
struct Interval v;
if (x == -t) v = (struct Interval){0, 0};
else if (x == t) v = (struct Interval){t * scale, t * scale};
else if (x <= 1 - WALL || x >= WALL - 1) {
v.lower = x > 0 ? x * scale : 0;
v.upper = t * scale;
} else {
struct Interval up = row[1 - parity][i + 1];
struct Interval down = row[1 - parity][i - 1];
v.lower = ((Wide)(t-x)*up.lower + (Wide)(t+x)*down.lower) / den;
v.upper = ((Wide)(t-x)*up.upper + (Wide)(t+x)*down.upper + den - 1) / den;
if (x > 0 && v.lower < x*scale) v.lower = x*scale;
if (x > 0 && v.upper < x*scale) v.upper = x*scale;
}
row[parity][i] = v;
}
if (!parity)
printf("%d %" PRIu64 " %" PRIu64 "\n",t/2,row[0][WALL].lower,row[0][WALL].upper);
}
}
~~~~
#### `review/article-edits/data-audit/check.py`
~~~~python
"""Audit the archived prices, candidate text reconstruction and two-parameter fits."""
from fractions import Fraction as F
from hashlib import sha256
from math import isqrt
from pathlib import Path
from sys import argv
def read_rows(path):
return [tuple(map(int, line.split())) for line in Path(path).read_text().splitlines()]
def show(bounds, digits):
"""Inclusive decimal bounds rounded outwards, including negative intercepts."""
q = 10**digits
def decimal(v):
s = "-" if v < 0 else ""
a, b = divmod(abs(v), q)
return f"{s}{a}.{b:0{digits}d}"
return "[" + decimal(bounds[0] * q // 1) + ", " + decimal(-((-bounds[1] * q) // 1)) + "]"
def fit(observations, scale):
"""Intercept + slope*sqrt(n). Root coordinates use rational enclosures."""
unit_x = 1 << 80
m = len(observations)
sxlo = sxhi = sylo = syhi = xylo = xyhi = sum_n = 0
for n, lo, hi in observations:
assert n > 0 and 0 < lo <= hi
arg = n * unit_x**2
xlo = isqrt(arg)
xhi = xlo + (xlo*xlo != arg)
sxlo += xlo
sxhi += xhi
sylo += lo
syhi += hi
xylo += xlo*lo
xyhi += xhi*hi
sum_n += n
vlo = m*sum_n*unit_x**2 - sxhi**2
vhi = m*sum_n*unit_x**2 - sxlo**2
clo = m*xylo - sxhi*syhi
chi = m*xyhi - sxlo*sylo
assert 0 < clo <= chi and 0 < vlo <= vhi
b = F(unit_x*clo, vhi*scale), F(unit_x*chi, vlo*scale)
a = ((F(sylo,scale)-b[1]*F(sxhi,unit_x))/m,
(F(syhi,scale)-b[0]*F(sxlo,unit_x))/m)
arg = 133787000*unit_x**2
z = isqrt(arg)
pred = a[0]+b[0]*F(z,unit_x), a[1]+b[1]*F(z+(z*z!=arg),unit_x)
return a, b, pred
def diff(a, b):
return a[0]-b[1], a[1]-b[0]
if len(argv) < 5:
raise SystemExit("check.py HISTORIC VERIFIED_ROWS POINT100K FLOAT_REPLAY [FLOAT_REPLAY ...]")
source = Path(argv[1]).read_bytes()
assert sha256(source).hexdigest() == "9d197ac8a5aa00003c21e6eb2f30908097181b3564b20dcfefa4d1250004f3c9"
lines = source.splitlines(keepends=True)
assert len(lines) == 22975 and lines[-1] == b"79.11\n"
values = [F(l.decode().strip()) for l in lines]
print("Historical raw data SHA-256:", sha256(source).hexdigest())
print("Six-decimal data rows:", sum(len(v.split(b".")[1].strip())==6 for v in lines))
print("All decreases in the posted price sequence:", [i for i in range(1,len(values)) if values[i]a or y < -a for x,y in errs)
high = sum(y>a or x < -a for x,y in errs)
assert low == high
print(f"Count with absolute error > {v} dollars:", low)
penny_disagreements = []
for (n,lo,hi),y in zip(rows, values):
true_lo, true_hi = ((F(z,scale)*100 + F(1,2)) // 1 for z in (lo,hi))
assert true_lo == true_hi
if (100*y + F(1,2)) // 1 != true_lo:
penny_disagreements.append(n)
print("Posted values disagree at nearest cent:",len(penny_disagreements),
"first/last n:",penny_disagreements[0],penny_disagreements[-1])
published = [(n,int(y*10**6),int(y*10**6)) for n,y in enumerate(values) if n]
assert all((v*10**6).denominator==1 for v in values)
p100k=(100000,165076000,165076000)
# Use a common denominator to separate the rounding at the single 100,000-pair row.
common=10**6 * scale
hist_sub=[(n,lo*scale,hi*scale) for n,lo,hi in published]
verified_extra=(extra[0],extra[1]*10**6,extra[2]*10**6)
fits=[
("Published positive rows plus reported 165.076",fit([*published,p100k],10**6)),
("Published positive rows plus certified 100,000-pair price",fit([*hist_sub,verified_extra],common)),
("Certified positive rows plus certified 100,000-pair price",fit([*rows[1:],extra],scale))
]
record=(F("6038.215406"),F("6038.218246"))
for label,(a,b,p) in fits:
print(label)
print(" intercept",show(a,10),"slope",show(b,12),"held-out prediction",show(p,8))
print(" prediction minus historical quoted 6038.22",show(diff(p,(F("6038.22"),)*2),8))
print(" prediction minus certified record",show(diff(p,record),8))
print("Change in prediction after replacing all response values:",show(diff(fits[2][1][2],fits[0][1][2]),8))
print("Change from replacing only the reported 100,000-pair response:",show(diff(fits[1][1][2],fits[0][1][2]),8))
~~~~
#### `review/fable/RegretAccounting.lean`
~~~lean
import Problem14
/-! Local action errors in aggregate payoff units for the ordinary game.
Dividing the total by the number of completed words gives dollar regret. -/
namespace Problem14.RegretAccounting
/-- The missed payoff at a reached decision, plus losses incurred after a draw.
Both actions are compared with their optimal continuations. A stop has no
subsequent cost. Each child already sums over all words completing its prefix. -/
def loss (R : Nat) (q : Rule) : Tree → Nat
| .empty => 0
| .leaf => 0
| .branch s l r =>
let cash := reward R s * (weight l + weight r)
let draw := bellman R l + bellman R r
if q s then draw - cash
else (cash - draw) + loss R q l + loss R q r
/-- The optimal total is exactly the payoff collected plus all reached
action errors; the equality holds on arbitrary subtrees. -/
theorem account (R : Nat) (q : Rule) (t : Tree) :
bellman R t = score R q t + loss R q t := by
induction t with
| empty => simp [score, paths, bellman, loss]
| leaf => simp [score, paths, firstPay, bellman, loss]
| branch s l r hl hr =>
rw [score_branch]
cases h : q s <;> simp only [loss, bellman, h, Bool.false_eq_true, if_false, if_true] <;> omega
theorem deck_regret (n : Nat) (q : Rule) :
bellman n (deck n n) - score n q (deck n n) = loss n q (deck n n) := by
have h := account n q (deck n n)
omega
/-- Any positive loss reached after a draw gives positive root loss. -/
theorem draw_inherits {R : Nat} {q : Rule} {s : State} {l r : Tree}
(draw : q s = false) (miss : 0 < loss R q l ∨ 0 < loss R q r) :
0 < loss R q (.branch s l r) := by
simp only [loss, draw, Bool.false_eq_true, if_false]
omega
#print axioms account
#print axioms deck_regret
end Problem14.RegretAccounting
~~~
#### `review/fable/advice/block_atoms.py`
~~~python
#!/usr/bin/env python3
"""Generate rigorous probability and conditional-mean lower bounds for block DP."""
from fractions import Fraction as F
from functools import cache
import sys
U = 2**32
Z = 2**20
# Certified with the Machin alternating series; 3.14159265358979 < pi < 3.14159265358980.
def atan_bounds(q):
s=sum(F((-1)**i,(2*i+1)*q**(2*i+1)) for i in range(16))
return s,s+F(1,33*q**33)
a,b=atan_bounds(5);c,d=atan_bounds(239)
pi0,pi1=16*a-4*d,16*b-4*c
c0,c1=F(3989422804014326,10**16),F(3989422804014328,10**16)
assert 2*pi1*c0*c0<1<2*pi0*c1*c1
@cache
def exp_bound(x):
# alternating Taylor at -x²/2: an odd truncation is global lower, even upper.
t=s=F(1)
for i in range(1,112):
t *= -x*x/(2*i)
s += t
return s, s-t
@cache
def gauss_area(x):
# Enclose integral_0^x exp(-z²/2) dz by its integrated Taylor polynomials.
if x<0:
a,b=gauss_area(-x)
return -b,-a
t=s=x
for i in range(1,112):
t *= -(x*x)*F(2*i-1,2*i*(2*i+1))
s += t
return s,s-t
def quant(a):return a.numerator//a.denominator
def make(kind,start,end,step):
bins=[]
for j in range(start,end):
a,b=F(j,step),F(j+1,step)
al,ah=exp_bound(a);bl,bh=exp_bound(b)
il,ih=gauss_area(a);jl,jh=gauss_area(b)
arealo,areahi=jl-ih,jh-il
if kind=='normal':
wl,wh=c0*arealo,c1*areahi
# Normal conditional mean=(exp(-a²/2)-exp(-b²/2))/area.
z=(al-bh)/(areahi if al>=bh else arealo)
else:
wl,wh=al-bh,ah-bl
numerator=a*al-b*bh+arealo
assert numerator>0
z=numerator/wh
assert wl>0 and a-F(1,100000)1 else 16
if step not in (16,32): raise ValueError('use 16 or 32 subdivisions per unit')
atoms=[make('normal',-5*step,5*step,step),make('rayleigh',0,6*step,step)]
for a in atoms:
print(len(a))
for p,m in a:print(p,m)
assert sum(p for p,_ in a)
#include
#include
#include
#include
#include
#include
using S=std::int64_t; using U=std::uint64_t;using Wide=unsigned __int128;
constexpr S Z=1<<20, R=1<<16;
struct Atom{S weight,mean;};
std::vector read_atoms() {
int n; if(std::scanf("%d",&n)!=1 || n<1 || n>8192) std::exit(2);
std::vector a(n); S sum=0;
for(auto& e:a) {
long long w,v; if(std::scanf("%lld%lld",&w,&v)!=2) std::exit(2);
e={w,v}; assert(w>=0 && std::abs(v)<=6*Z); sum+=w;
}
assert(sum <= (S{1}<<32));
return a;
}
S floor_div(S x,S d){return x/d-(x%d<0);}
S root(U v) {
U r=std::sqrt((long double)v);
while(r*r>v) --r;
while((r+1)*(r+1)<=v) ++r;
return r;
}
int main(int argc,char**argv){
if(argc!=3) return 2;
int m=std::atoi(argv[1]),unit=std::atoi(argv[2]);
if(m<2||m>64||unit<256||unit>32768)return 2;
auto normal=read_atoms(),ray=read_atoms();
int nE=ray.size(),wall=2*unit,limit=4*unit;
std::vector inc(nE),mass(nE+1);
for(int e=nE-1;e>=0;--e){
assert(ray[e].mean>=0);
inc[e]=((Wide)unit*unit*(U)ray[e].mean*(U)ray[e].mean)/((Wide)m*Z*Z);
mass[e]=mass[e+1]+ray[e].weight;
}
assert(std::is_sorted(inc.begin(),inc.end()));
std::vector sums((size_t)(limit+1)*(nE+1));
for(S d=0;d<=limit;++d){
U* su=&sums[d*(nE+1)];
for(int e=nE-1;e>=0;--e)
su[e]=su[e+1]+(U)ray[e].weight*((root(d*d+inc[e])-d)/2);
}
std::vector val(2*wall+1),next(val);
for(S j=1;j<=m;++j){
S sig=root((Wide)unit*unit*R*R*(j-1)/(j*m));
S denom=j*Z*R;
for(S x=-wall;x<=wall;++x){
Wide total=0;
for(auto a:normal){
S numerator=(j-1)*x*Z*R + j*a.mean*(sig+(a.mean<0));
S y=floor_div(numerator,denom),d=std::abs(x-y);
assert(d<=limit);
S cont = (y < -wall) ? 0 : val[std::min(y+wall,S(2*wall))];
S peak=std::max(x,y),cash=std::max(peak,cont),gap=cash-peak;
S e=std::lower_bound(inc.begin(),inc.end(),4*(gap+1)*(d+gap+1))-inc.begin();
U extra=sums[d*(nE+1)+e]-gap*mass[e];
U grouped=cash*mass[0]+extra;
if(x==-wall || x==0 || x==wall){
U direct=0;
for(int k=0;k>64);
assert(next[x+wall]>=0 && next[x+wall]<=8*unit);
}
val.swap(next);
}
printf("%d blocks: value >= %lld/%d = %.12f\n",m,(long long)val[wall],unit,(double)val[wall]/unit);
}
~~~
#### `review/fable/advice/check_extended.py`
~~~python
"""Certify the finite premium fractions and report successive Richardson estimates.
Reads n w V1 V2 V3 in hexadecimal binary64 from extended.c. Assumes strict
IEEE binary64 round-to-nearest and compiler floating-point contraction off.
"""
import sys
from math import ceil, comb, floor, sqrt
from fractions import Fraction as F
def pct(value, roundfn):
units=roundfn(value*10**10)
return f"{units//10**8}.{units%10**8:08d}"
def verify(line):
ns,ws,*data=line.split()
n=int(ns);w=int(ws);assert 1<=w<=n and len(data)==3
vals=list(map(lambda s:F(float.fromhex(s)),data))
z=comb(2*n,n)
prophet=(F(4**n,z)-1)/2
# Clipped value is at most the actual value. For the positive wall,
# only (H-w)_+ can be lost. At the negative wall, reaching a positive
# score j afterwards requires the ordered crossings -w,+j, with probability
# C(2n,n+w+j)/C(2n,n) by two reflections. Sum both tails geometrically.
clip=F(0) if w==n else 2*F(comb(2*n,n+w+1),z)/(1-F(n-w-1,n+w+2))
rnd=F(16*n*(n+1),2**53)
err=clip+rnd
vi=vals[0]
def share(v):
# (v-ordinary)/(prophet-ordinary) increases with v and decreases
# with ordinary on the price range [ordinary,prophet].
return ((v-rnd-(vi+err))/(prophet-(vi+err)),
(v+err-(vi-rnd))/(prophet-(vi-rnd)))
a,b=share(vals[1]); c,d=share(vals[2])
print(f'N={2*n:6d} V2share=[{pct(a,floor)}, {pct(b,ceil)}]% '
f'V3share=[{pct(c,floor)}, {pct(d,ceil)}]% '
f'FP+clip error={float(err):.3g} dollars')
return 2*n,float((a+b)/2),float((c+d)/2)
if __name__=='__main__':
rows=[verify(line) for line in sys.stdin if line.strip()]
for (n,a,b),(N,c,d) in zip(rows,rows[1:]):
if N==2*n:
extrap=lambda x,y:100*(y+(y-x)/(sqrt(2)-1))
print(f'assuming leading 1/sqrt(N), {n}->{N}: '
f'{extrap(a,c):.6f}%, {extrap(b,d):.6f}%')
~~~
#### `review/fable/advice/extended.c`
~~~c
// Build: gcc -O2 -o p14_three_messages p14_three_messages.c -lm Run: ./p14_three_messages 26 4096 8192 16384 (arguments are pairs)
// nom3.c -- value of the best 1, 2 and 3 pre-game messages (= best of k online nominations) on a deck of n pairs.
// U_k(t,x,h): t cards left, balance x, best banked nomination h, k nominations left. double precision.
#include
#include
#include
int main(int argc, char**argv){
for(int a=1; a n) w = n;
long X = 2*w + 1, Hn = w + 1;
double *U1 = calloc((size_t)X*Hn, sizeof(double)), *U2 = calloc((size_t)X*Hn, sizeof(double)), *U3 = calloc((size_t)X, sizeof(double));
#define IDX(x,h) ((size_t)((x)+w)*Hn + (h))
for(long h=0; h<=w; h++){ U1[IDX(0,h)] = (double)h; U2[IDX(0,h)] = (double)h; }
U3[w] = 0.0;
for(long t=1; t<=N; t++){
long lo = (-t > -w) ? -t : -w, hi = (t < w) ? t : w;
if(((lo % 2) + 2) % 2 != t % 2) lo++;
if(((hi % 2) + 2) % 2 != t % 2) hi--;
for(long x=lo; x<=hi; x+=2){
double pu = (double)(t-x)/(2.0*(double)t), pd = (double)(t+x)/(2.0*(double)t);
if(x == w && t > w){ for(long h=0; h<=w; h++){ U1[IDX(x,h)] = (double)w; U2[IDX(x,h)] = (double)w; } U3[x+w] = (double)w; continue; }
if(x == -w && t > w){ for(long h=0; h<=w; h++){ U1[IDX(x,h)] = (double)h; U2[IDX(x,h)] = (double)h; } U3[x+w] = 0.0; continue; }
double *u1p = (pu > 0) ? &U1[IDX(x+1,0)] : NULL, *u1m = (pd > 0) ? &U1[IDX(x-1,0)] : NULL;
double *u2p = (pu > 0) ? &U2[IDX(x+1,0)] : NULL, *u2m = (pd > 0) ? &U2[IDX(x-1,0)] : NULL;
double *o1 = &U1[IDX(x,0)], *o2 = &U2[IDX(x,0)];
for(long h=0; h<=w; h++){
double c1 = (u1p ? pu*u1p[h] : 0.0) + (u1m ? pd*u1m[h] : 0.0);
o1[h] = (x > h && (double)x > c1) ? (double)x : c1;
}
double nom1 = (x > 0) ? o1[x] : 0.0; // U_1(t,x,x): after banking x with one nomination left
for(long h=0; h<=w; h++){
double c2 = (u2p ? pu*u2p[h] : 0.0) + (u2m ? pd*u2m[h] : 0.0);
o2[h] = (x > h && nom1 > c2) ? nom1 : c2;
}
double c3 = ((pu > 0) ? pu*U3[x+1+w] : 0.0) + ((pd > 0) ? pd*U3[x-1+w] : 0.0);
double nom2 = (x > 0) ? o2[x] : 0.0;
U3[x+w] = (x > 0 && nom2 > c3) ? nom2 : c3;
}
}
printf("%ld %ld %a %a %a\n",n,w,U1[IDX(0,0)],U2[IDX(0,0)],U3[w]);
fflush(stdout); free(U1); free(U2); free(U3);
}
return 0;
}
~~~
#### `review/fable/advice/p14_three_messages.c`
~~~c
// Build: gcc -O2 -o p14_three_messages p14_three_messages.c -lm Run: ./p14_three_messages 26 4096 8192 16384 (arguments are pairs)
// nom3.c -- value of the best 1, 2 and 3 pre-game messages (= best of k online nominations) on a deck of n pairs.
// U_k(t,x,h): t cards left, balance x, best banked nomination h, k nominations left. double precision.
#include
#include
#include
int main(int argc, char**argv){
for(int a=1; a n) w = n;
long X = 2*w + 1, Hn = w + 1;
double *U1 = calloc((size_t)X*Hn, sizeof(double)), *U2 = calloc((size_t)X*Hn, sizeof(double)), *U3 = calloc((size_t)X, sizeof(double));
#define IDX(x,h) ((size_t)((x)+w)*Hn + (h))
for(long h=0; h<=w; h++){ U1[IDX(0,h)] = (double)h; U2[IDX(0,h)] = (double)h; }
U3[w] = 0.0;
for(long t=1; t<=N; t++){
long lo = (-t > -w) ? -t : -w, hi = (t < w) ? t : w;
if(((lo % 2) + 2) % 2 != t % 2) lo++;
if(((hi % 2) + 2) % 2 != t % 2) hi--;
for(long x=lo; x<=hi; x+=2){
double pu = (double)(t-x)/(2.0*(double)t), pd = (double)(t+x)/(2.0*(double)t);
if(x == w && t > w){ for(long h=0; h<=w; h++){ U1[IDX(x,h)] = (double)w; U2[IDX(x,h)] = (double)w; } U3[x+w] = (double)w; continue; }
if(x == -w && t > w){ for(long h=0; h<=w; h++){ U1[IDX(x,h)] = (double)h; U2[IDX(x,h)] = (double)h; } U3[x+w] = 0.0; continue; }
double *u1p = (pu > 0) ? &U1[IDX(x+1,0)] : NULL, *u1m = (pd > 0) ? &U1[IDX(x-1,0)] : NULL;
double *u2p = (pu > 0) ? &U2[IDX(x+1,0)] : NULL, *u2m = (pd > 0) ? &U2[IDX(x-1,0)] : NULL;
double *o1 = &U1[IDX(x,0)], *o2 = &U2[IDX(x,0)];
for(long h=0; h<=w; h++){
double c1 = (u1p ? pu*u1p[h] : 0.0) + (u1m ? pd*u1m[h] : 0.0);
o1[h] = (x > h && (double)x > c1) ? (double)x : c1;
}
double nom1 = (x > 0) ? o1[x] : 0.0; // U_1(t,x,x): after banking x with one nomination left
for(long h=0; h<=w; h++){
double c2 = (u2p ? pu*u2p[h] : 0.0) + (u2m ? pd*u2m[h] : 0.0);
o2[h] = (x > h && nom1 > c2) ? nom1 : c2;
}
double c3 = ((pu > 0) ? pu*U3[x+1+w] : 0.0) + ((pd > 0) ? pd*U3[x-1+w] : 0.0);
double nom2 = (x > 0) ? o2[x] : 0.0;
U3[x+w] = (x > 0 && nom2 > c3) ? nom2 : c3;
}
}
double r = 1.0; for(long i=1; i<=n; i++) r *= (double)(2*i)/(double)(2*i-1);
double V = U1[IDX(0,0)], P = (r - 1.0)/2.0;
printf("pairs=%ld band=%ld one=%.9f two=%.9f three=%.9f prophet=%.9f midpoint=%.9f frac2=%.5f%% frac3=%.5f%%\n", n, w, V, U2[IDX(0,0)], U3[w], P, (V+P)/2, 100*(U2[IDX(0,0)]-V)/(P-V), 100*(U3[w]-V)/(P-V));
fflush(stdout); free(U1); free(U2); free(U3);
}
return 0;
}
~~~
#### `review/fable/advice/threshold_fit.py`
~~~python
"""Fit finite preview threshold transitions from the archived certified CSV (stdlib)."""
import csv
from math import sqrt
import sys
def least_squares(rows):
size = len(rows[0]) - 1
mat = [[sum(row[i]*row[j] for row in rows) for j in range(size+1)]
for i in range(size)]
for i in range(size):
scale = mat[i][i]
mat[i] = [x/scale for x in mat[i]]
for j in range(size):
if i == j:
continue
scale = mat[j][i]
mat[j] = [a-scale*b for a, b in zip(mat[j], mat[i])]
return [row[-1] for row in mat]
with open(sys.argv[1], newline='') as f:
first = {}
for row in csv.DictReader(f):
first.setdefault(int(row['minimum_preview']), 2*int(row['pairs']))
for lower in (8,12,20):
obs = [(first[k],k) for k in range(lower,31)]
a = least_squares([[n,1,k] for n,k in obs])[0]
b = least_squares([[n,sqrt(n),1,k] for n,k in obs])[0]
print(f'k={lower}..30: k=dN+c yields d={a:.8f}; k=dN+h√N+c yields d={b:.8f}.')
~~~
#### `review/fable/check-lean.sh`
~~~bash
#!/usr/bin/env bash
set -euo pipefail
# From a clean extracted report with Lean 4.19.0 and mathlib v4.19.0:
# MATHLIB=/path/to/mathlib4 bash review/fable/check-lean.sh
# P14_MATHLIB_LEAN_PATH can supply the compiled mathlib/package paths directly.
# To reuse the 55 previously built original modules, set P14_ANALYTIC_LEAN_PATH
# to their compiled directory and mathlib paths, then pass --reuse-analytic.
# P14_LAYER_PLUGIN optionally accelerates the latter mode.
here=$(cd -- "$(dirname -- "$0")" && pwd)
project=$(cd -- "$here/../.." && pwd)
mode=${1:---clean}
case "$mode" in
--clean)
if [[ -n ${P14_MATHLIB_LEAN_PATH:-} ]]; then
deps=$P14_MATHLIB_LEAN_PATH
else
deps=$(cd -- "${MATHLIB:?set MATHLIB to a built mathlib v4.19.0 checkout}" &&
"${LAKE:-lake}" env python3 -c 'import os; print(os.pathsep.join(os.path.abspath(p) for p in os.environ["LEAN_PATH"].split(os.pathsep) if p))')
fi
;;
--reuse-analytic) deps=${P14_ANALYTIC_LEAN_PATH:?set P14_ANALYTIC_LEAN_PATH} ;;
*) echo "Usage: bash check-lean.sh [--clean|--reuse-analytic]" >&2; exit 2 ;;
esac
work=$(mktemp --directory)
trap 'rm --force --recursive -- "$work"' EXIT
export LEAN_PATH="$work:$deps"
python3 - "$project" "$work" "$mode" <<'PY'
import concurrent.futures as cf
import os, pathlib, re, shlex, subprocess, sys, threading
project, work = map(pathlib.Path, sys.argv[1:3])
reuse = sys.argv[3] == '--reuse-analytic'
lean = os.environ.get('LEAN', 'lean')
version = subprocess.check_output([lean, '--version'], text=True).strip()
print(version, flush=True)
if not re.search(r'version 4\.19\.0\b', version):
raise SystemExit('Use the archived Lean 4.19.0 toolchain.')
review = project / 'review'
fable = review / 'fable'
directories = [project, project/'asmproof', project/'cent/formal',
project/'further/formal', review/'formal', fable, fable/'enclosure']
roots = ['CentGameCap', 'FullHistoryPrice', 'FullHistoryRecords', 'FullHistoryRegret',
'IdealPlayer', 'HalfCardCap', 'RegretAccounting', 'AllDeckEnclosure']
layer = ['Problem14', 'Excursions', 'asmproof.GameLower',
'asmproof.GameCutoff', 'asmproof.GameLayer']
imports, sources = {}, {}
def collect(module):
if module in imports or module.split('.')[0] in {'Mathlib','Std','Init','Lean'}:
return
rel = pathlib.Path(*module.split('.')).with_suffix('.lean')
dirs = [d for d in directories if (d/rel).is_file()]
if len(dirs) != 1:
raise ValueError(f'{module} resolved to {dirs}')
root = dirs[0]
# All original analytic sources live under the first two roots. RecordReplay
# is checked anew, as in review/formal/check.sh.
if reuse and root in directories[:2] and module != 'RecordReplay':
return
src = root/rel
sources[module] = (root, src)
deps = re.findall(r'^import\s+([\w.]+)', src.read_text(), re.M)
# The optimized native library is ready after its original first consumer.
if module == 'SmallRows' and not reuse:
deps.append('asmproof.Game65536')
imports[module] = deps
for m in deps:
collect(m)
for module in roots:
collect(module)
prefix = pathlib.Path(subprocess.check_output([lean, '--print-prefix'], text=True).strip())
include = os.environ.get('P14_LEAN_INCLUDE', str(prefix/'include'))
cc = shlex.split(os.environ.get('CC', 'cc'))
native = work/'native'
native.mkdir()
plugin = native/'libasmproof_GameLayer.so'
reuse_plugin = os.environ.get('P14_LAYER_PLUGIN')
use_native = not reuse and sys.platform.startswith('linux')
lock = threading.Lock()
def compile_module(m):
root, src = sources[m]
dst = work/(m.replace('.','/')+'.olean')
dst.parent.mkdir(parents=True, exist_ok=True)
args = [lean, '--root='+str(root), '-s', '65536', '-j', '1']
if use_native and m in layer:
args.extend(['-c', str(native/(m+'.c'))])
if use_native and m == 'asmproof.Game65536':
subprocess.run([*cc,'-shared','-o',str(plugin),*[str(native/(n+'.o')) for n in layer]],check=True)
if use_native and m in ('asmproof.Game65536','SmallRows'):
args.append('--plugin='+str(plugin))
if reuse and reuse_plugin and m == 'SmallRows':
args.append('--plugin='+reuse_plugin)
proc = subprocess.run([*args,'-o',str(dst),str(src)],cwd=project,
stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True)
with lock:
print(f'{m}: exit {proc.returncode}', flush=True)
print(proc.stdout, end='', flush=True)
proc.check_returncode()
if use_native and m in layer:
subprocess.run([*cc,'-O3','-fPIC','-DLEAN_EXPORTING','-I',include,'-c',
str(native/(m+'.c')),'-o',str(native/(m+'.o'))],check=True)
dependencies = {m: set(ds).intersection(imports) for m,ds in imports.items()}
remaining = set(imports)
done = set()
pending = {}
with cf.ThreadPoolExecutor(max_workers=int(os.environ.get('P14_JOBS', '2'))) as pool:
while remaining or pending:
for m in sorted(remaining.copy()):
if dependencies[m] <= done:
pending[pool.submit(compile_module,m)] = m
remaining.remove(m)
if not pending:
raise RuntimeError('cyclic project imports')
finished,_ = cf.wait(pending,return_when=cf.FIRST_COMPLETED)
for job in finished:
job.result()
done.add(pending.pop(job))
print(f'Checked {len(done)} project modules in {sys.argv[3]} mode.', flush=True)
PY
~~~
#### `review/fable/enclosure/AllDeckEnclosure.lean`
~~~lean
import SmallRows
import CentGameCap
import asmproof.GameMachinePrice
namespace Problem14.GameLayer
open private axis_red axis_black interior from asmproof.GameLayer
/-- The archived strip is a Bellman lower table at every depth. -/
theorem lower_all (n : ℕ) :
value n n * GameCutoff.ways n n ≤ scale * GameCutoff.total n n n := by
let table : GameCutoff.Table scale := ⟨value, axis_red, axis_black, interior⟩
exact GameCutoff.table_lower scale n table n n le_rfl
end Problem14.GameLayer
namespace P14Entry
open Problem14 P14Quote.Coefficient
private theorem total_price (n : ℕ) :
GameComparison.price n = (GameCutoff.total n n n : ℝ)/(weight (deck n n) : ℝ) := by
unfold GameComparison.price
rw [closedNumerator_eq_bellman]
have h := congrArg (fun z : ℤ => (z:ℝ)) (GameCutoff.cast_total n n n)
simp only [Excursions.mass,Int.cast_natCast,Int.cast_sub,Int.cast_mul] at h
rw [h]
private theorem weight_pos (n : ℕ) : 0<(weight (deck n n) : ℝ) := by
rw [GameComparison.deck_count]
exact_mod_cast Nat.choose_pos (by omega : n≤n+n)
private theorem coefficient_bounds : 522037/1000000 ≤ K ∧ K ≤ 522038/1000000 := by
have h := P14Quote.Coefficient.threshold_coefficient
change (P14Quote.coefficient:ℝ)/10^18 ≤ K ∧ K ≤ ((P14Quote.coefficient:ℝ)+1)/10^18 at h
norm_num [P14Quote.coefficient] at h
constructor <;> linarith only [h.1,h.2]
private theorem lower_small (n : ℕ) (hn : n≤32767) :
K*Real.sqrt n-(137/1000)/(2*(n:ℝ)+1)^((1:ℝ)/5) ≤ GameComparison.price n := by
let d := SmallRows.denom n
let v := GameLayer.value n n
have ⟨dh,dh5,ineq⟩ := SmallRows.lower_small n hn
have dp : (0:ℝ) test i a
| k+1, i, a => if test i a then run advance test k (i+1) (advance i a) else false
theorem run_sound {α : Type} (advance : Nat → α → α) (test : Nat → α → Bool)
(state : Nat → α) (step : ∀ i, advance i (state i) = state (i+1))
(k i j : Nat) (ok : run advance test k i (state i)=true)
(lo : i≤j) (hi : j≤i+k) : test j (state j)=true := by
induction k generalizing i with
| zero =>
have eq : j=i := by omega
subst j
exact ok
| succ k ih =>
simp only [run] at ok
cases h : test i (state i)
· simp [h] at ok
· by_cases eq : i=j
· simpa only [eq] using h
· simp only [h,↓reduceIte,step] at ok
exact ih _ ok (by omega) (by omega)
def denom (n : Nat) : Nat :=
((List.range 101).find? (fun d => decide (10^5*(2*n+1) ≤ d^5))).getD 101
def lowerAt (n v : Nat) : Prop :=
let d := denom n
0GameLayer.rows (2*i))
lower_step 32767 0 n ok.1 (by omega) (by omega)
have f := of_decide_eq_true h
simpa only [GameLayer.value,←Nat.two_mul] using f
theorem upper_small (n : Nat) (hn : n≤1799) : upperAt n (Upper.cell (2*n) n).1 (Upper.cell (2*n) n).2 := by
have ok := Bool.and_eq_true_iff.mp verified
have h := run_sound upperStep upperTest (fun i=>Upper.row (2*i))
upper_step 1799 0 n ok.2 (by omega) (by omega)
unfold upperTest at h
have i : n+1 < (Upper.row (2*n)).length := by rw [Upper.row_length]; omega
change decide (upperAt n ((Upper.row (2*n))[n+1]!).1.1 ((Upper.row (2*n))[n+1]!).1.2) = true at h
rw [getElem!_pos (Upper.row (2*n)) (n+1) i, Upper.row_eq _ _ i] at h
have e : (-1:Int)+(n+1:Nat) = (n:Int) := by omega
rw [e] at h
exact of_decide_eq_true h
#print axioms lower_small
#print axioms upper_small
end Problem14.SmallRows
~~~
#### `review/fable/enclosure/certify.cpp`
~~~cpp
// C++17. Two independent integer Bellman sweeps; no floating point.
#include
#include
#include
#include
#include
#include
using u64 = std::uint64_t;
using Big = mpz_class;
constexpr u64 S = 1ULL << 30;
constexpr u64 km = 522037, kp = 522038, unit = 1000000;
constexpr int last = 32767, upper_last = 1799;
static Big sq(Big a) { return a*a; }
static u64 pow5(u64 a) { return a*a*a*a*a; }
// The left endpoint uses the attainable policy of stopping at a strip wall
// when positive and exhausting the deck when negative. All rounding is down.
// The right endpoint uses the full physical state space and rounds up.
int main() {
constexpr int low = -2048, high = 256, guard = 2;
std::vector lo(high-low+2*guard+1), nextlo(lo.size());
std::vector up(4*upper_last+2*guard+1), nextup(up.size());
u64 d = 10;
Big central_count = 1, full_walk_count = 1;
for (int t=0; t<=2*last; ++t) {
if (t > 0) {
for (int x=std::max(-t,low+(t&1)); x<=std::min(t,high-(t&1)); x+=2) {
const int i = x-low+guard;
u64 stop = static_cast(std::max(x,0))*S;
if (x<=low+1 || x>=high-1 || std::abs(x)==t) nextlo[i]=stop;
else {
const u64 sum = static_cast(t-x)*lo[i+1]+static_cast(t+x)*lo[i-1];
nextlo[i]=std::max(stop,sum/static_cast(2*t));
}
}
lo.swap(nextlo);
if (t<=2*upper_last) {
for (int x=-t; x<=t; x+=2) {
const int i=x+2*upper_last+guard;
const u64 stop=static_cast(std::max(x,0))*S;
if (std::abs(x)==t) nextup[i]=stop;
else {
const u64 sum=static_cast(t-x)*up[i+1]+static_cast(t+x)*up[i-1];
nextup[i]=std::max(stop,(sum+2*t-1)/static_cast(2*t));
}
}
up.swap(nextup);
}
}
if ((t&1)==0) {
const auto n=static_cast(t/2);
while (pow5(d)<100000ULL*(t+1)) ++d;
const u64 v=lo[-low+guard];
// sqrt(n)*kp/unit <= v/S + 137/(100*d).
if (n*sq(Big(kp)*S*100*d) >
sq(Big(unit)*(Big(100)*d*v+137*S))) return EXIT_FAILURE;
if (n<=upper_last) {
const u64 w=up[2*upper_last+guard];
// w/S <= km/unit*sqrt(n+1/2)
if (2*sq(Big(unit)*w) > (2*n+1)*sq(Big(km)*S)) return EXIT_FAILURE;
// w/S <= (58905/200000) * 4^n / C(2n,n).
if (n > 0) {
central_count = central_count * (4*n-2) / n;
full_walk_count *= 4;
}
if (200000*Big(w)*central_count > 58905*Big(S)*full_walk_count)
return EXIT_FAILURE;
}
}
}
std::printf("Verified lower bounds at %d roots and both square-root and central-binomial upper bounds at %d roots, including n=0.\n",
last+1,upper_last+1);
}
~~~
#### `review/fable/enclosure/check.sh`
~~~bash
#!/usr/bin/env bash
set -euo pipefail
here=$(cd -- "$(dirname -- "$0")" && pwd)
work=$(mktemp --directory)
trap 'rm --force --recursive -- "$work"' EXIT
${CXX:-c++} -O3 -std=c++17 -Wall -Wextra "$here/certify.cpp" -lgmpxx -lgmp -o "$work/certify"
"$work/certify"
export LEAN_PATH="$work:${P14_ANALYTIC_LEAN_PATH:?give compiled Problem 14, review, cent, and mathlib module paths}"
opts=()
if [[ -n ${P14_LAYER_PLUGIN:-} ]]; then
opts+=("--plugin=$P14_LAYER_PLUGIN")
fi
for module in SmallRows AllDeckEnclosure; do
"${LEAN:-lean}" "${opts[@]}" --root="$here" -o "$work/$module.olean" "$here/$module.lean"
done
~~~
#### `review/fable/independent/p14_sweep.c`
~~~c
// Build: gcc -O2 -o p14_sweep p14_sweep.c -lm Run: ./p14_sweep 8388608 sweep.csv crossings.csv
// Columns of sweep.csv: t (cards), V (optimal value), r = 4^n/C(2n,n), regret of the report's hybrid, of the 79-rule,
// of the rule (2x+1)^2 >= 4 alpha^2 t, of the 79-rule followed above 65,536 cards by that rule, P(optimal player ends with zero), stop threshold.
// The far-negative wall moves at -7*sqrt(t); it biases V by about 1e-10 relative (use a wider wall for 12-digit comparisons).
// sweep.c -- independent check of the red/black stopping game ("Problem 14").
// One backward pass over t = remaining cards. State (t,x): x = current balance = blacks_left - reds_left.
// P(next card red, balance +1) = (t-x)/(2t). Long double (x87 80-bit) throughout; integer tests for the rules.
#include
#include
#include
#include
#include
typedef long double LD;
typedef unsigned __int128 u128;
static inline int stop79(long t, long x){ return 79*t <= 112*x*x + 109*x + 14; }
static inline int stopBM(uint64_t t, uint64_t x){
const uint64_t beta = UINT64_C(13013657395120439157);
uint64_t cutoff = (uint64_t)(((u128)beta * t + beta) >> 64);
uint64_t k = x + 1; return k*k > cutoff; }
int main(int argc, char**argv){
long NMAX = atol(argv[1]); const char* outp = argv[2]; const char* crossp = argv[3];
const LD alpha = 0.839923675692372689603L, fourA2 = 4*alpha*alpha;
long Wmax = (long)ceill(7.0L*sqrtl((LD)NMAX)) + 6, Hmax = (long)floorl(2.0L*sqrtl((LD)NMAX)) + 8;
long OFF = Wmax + 4, SZ = OFF + Hmax + 8;
LD *V=calloc(SZ,sizeof(LD)), *Dh=calloc(SZ,sizeof(LD)), *D7=calloc(SZ,sizeof(LD)), *Dq=calloc(SZ,sizeof(LD)), *Dh2=calloc(SZ,sizeof(LD)), *U=calloc(SZ,sizeof(LD));
long *tstar = calloc(Hmax+8, sizeof(long));
FILE *fo = fopen(outp,"w"), *fc = fopen(crossp,"w");
fprintf(fo,"t,V,r,Dhyb,D79,Dhalf,Dhyb2,Pexhaust,bopt\n");
U[OFF] = 1.0L; // t=0: exhausted, value 0, reached exhaustion
LD r = 1.0L; // r_n = 4^n / C(2n,n)
LD maxDh=0, maxDq=0, maxDh2=0, maxD7=0; long aDh=0, aDq=0, aDh2=0, aD7=0;
LD maxDh_small=0; long aDh_small=0; // sup over even t <= 482618
double nextgrid = 2.0;
for(long t=1; t<=NMAX; t++){
long W = (long)ceill(7.0L*sqrtl((LD)t)) + 2, H = (long)floorl(2.0L*sqrtl((LD)t)) + 3;
long lo = (-t > -W) ? -t : -W, hi = (t < H) ? t : H;
if(((lo % 2) + 2) % 2 != t % 2) lo++;
if(((hi % 2) + 2) % 2 != t % 2) hi--;
LD inv = 1.0L/(2.0L*(LD)t); long bopt = 0;
for(long x=lo; x<=hi; x+=2){
long i = x + OFF; LD wu = (LD)(t-x)*inv, wd = (LD)(t+x)*inv;
LD C = wu*V[i+1] + wd*V[i-1];
LD eh = wu*Dh[i+1] + wd*Dh[i-1], e7 = wu*D7[i+1] + wd*D7[i-1], eq = wu*Dq[i+1] + wd*Dq[i-1], eh2 = wu*Dh2[i+1] + wd*Dh2[i-1];
LD eu = wu*U[i+1] + wd*U[i-1];
if(x <= 0){ V[i]=C; Dh[i]=eh; D7[i]=e7; Dq[i]=eq; Dh2[i]=eh2; U[i]=eu; continue; }
int os = ((LD)x >= C); LD v = os ? (LD)x : C; LD loc_cont = v - C, loc_stop = v - (LD)x;
if(os){ if(!bopt) bopt = x; } else if(x < Hmax+8 && tstar[x]==0) tstar[x] = t;
int s7 = stop79(t,x), sb = (t <= 65536) ? s7 : stopBM((uint64_t)t,(uint64_t)x);
LD k = (LD)(2*x+1); int sq = (k*k >= fourA2*(LD)t); int sh2 = (t <= 65536) ? s7 : sq;
V[i] = v; U[i] = os ? 0.0L : eu;
Dh[i] = sb ? loc_stop : loc_cont + eh;
D7[i] = s7 ? loc_stop : loc_cont + e7;
Dq[i] = sq ? loc_stop : loc_cont + eq;
Dh2[i] = sh2 ? loc_stop : loc_cont + eh2;
}
long it = hi + 2 + OFF; V[it] = (LD)(hi+2); Dh[it]=D7[it]=Dq[it]=Dh2[it]=0; U[it]=0; // forced stop above 2*sqrt(t)
long ib = lo - 2 + OFF; V[ib]=0; Dh[ib]=D7[ib]=Dq[ib]=Dh2[ib]=0; U[ib]=0; // far-negative filler (weight ~e^-98)
if(t % 2 == 0){
long n = t/2; r *= (LD)(2*n)/(LD)(2*n-1);
if(Dh[OFF] > maxDh){ maxDh = Dh[OFF]; aDh = t; }
if(t <= 482618 && Dh[OFF] > maxDh_small){ maxDh_small = Dh[OFF]; aDh_small = t; }
if(Dq[OFF] > maxDq){ maxDq = Dq[OFF]; aDq = t; }
if(Dh2[OFF] > maxDh2){ maxDh2 = Dh2[OFF]; aDh2 = t; }
if(D7[OFF] > maxD7){ maxD7 = D7[OFF]; aD7 = t; }
int special = (t==52||t==64||t==16484||t==16486||t==65536||t==65538||t==131070||t==200000||t==437186||t==482618||t==482620||t==1000000||t==2000000||t==NMAX||(t&(t-1))==0);
if(special || (double)t >= nextgrid){
fprintf(fo,"%ld,%.21Lg,%.21Lg,%.12Lg,%.12Lg,%.12Lg,%.12Lg,%.15Lg,%ld\n", t, V[OFF], r, Dh[OFF], D7[OFF], Dq[OFF], Dh2[OFF], U[OFF], bopt);
while((double)t >= nextgrid) nextgrid *= 1.0746078283213174; // 10^(1/32)
}
}
}
fprintf(fo,"#sup,hybrid,%.12Lg,at,%ld\n#sup,hybrid_le_482618,%.12Lg,at,%ld\n#sup,half,%.12Lg,at,%ld\n#sup,hybrid2,%.12Lg,at,%ld\n#sup,79,%.12Lg,at,%ld\n", maxDh,aDh,maxDh_small,aDh_small,maxDq,aDq,maxDh2,aDh2,maxD7,aD7);
fprintf(fc,"L,tstar\n"); for(long L=1; L
#include
#include
int main(int argc, char**argv){
for(int a=1; a n) w = n;
long X = 2*w + 1, Hn = w + 1;
double *U1 = calloc((size_t)X*Hn, sizeof(double)), *U2 = calloc((size_t)X*Hn, sizeof(double)), *U3 = calloc((size_t)X, sizeof(double));
#define IDX(x,h) ((size_t)((x)+w)*Hn + (h))
for(long h=0; h<=w; h++){ U1[IDX(0,h)] = (double)h; U2[IDX(0,h)] = (double)h; }
U3[w] = 0.0;
for(long t=1; t<=N; t++){
long lo = (-t > -w) ? -t : -w, hi = (t < w) ? t : w;
if(((lo % 2) + 2) % 2 != t % 2) lo++;
if(((hi % 2) + 2) % 2 != t % 2) hi--;
for(long x=lo; x<=hi; x+=2){
double pu = (double)(t-x)/(2.0*(double)t), pd = (double)(t+x)/(2.0*(double)t);
if(x == w && t > w){ for(long h=0; h<=w; h++){ U1[IDX(x,h)] = (double)w; U2[IDX(x,h)] = (double)w; } U3[x+w] = (double)w; continue; }
if(x == -w && t > w){ for(long h=0; h<=w; h++){ U1[IDX(x,h)] = (double)h; U2[IDX(x,h)] = (double)h; } U3[x+w] = 0.0; continue; }
double *u1p = (pu > 0) ? &U1[IDX(x+1,0)] : NULL, *u1m = (pd > 0) ? &U1[IDX(x-1,0)] : NULL;
double *u2p = (pu > 0) ? &U2[IDX(x+1,0)] : NULL, *u2m = (pd > 0) ? &U2[IDX(x-1,0)] : NULL;
double *o1 = &U1[IDX(x,0)], *o2 = &U2[IDX(x,0)];
for(long h=0; h<=w; h++){
double c1 = (u1p ? pu*u1p[h] : 0.0) + (u1m ? pd*u1m[h] : 0.0);
o1[h] = (x > h && (double)x > c1) ? (double)x : c1;
}
double nom1 = (x > 0) ? o1[x] : 0.0; // U_1(t,x,x): after banking x with one nomination left
for(long h=0; h<=w; h++){
double c2 = (u2p ? pu*u2p[h] : 0.0) + (u2m ? pd*u2m[h] : 0.0);
o2[h] = (x > h && nom1 > c2) ? nom1 : c2;
}
double c3 = ((pu > 0) ? pu*U3[x+1+w] : 0.0) + ((pd > 0) ? pd*U3[x-1+w] : 0.0);
double nom2 = (x > 0) ? o2[x] : 0.0;
U3[x+w] = (x > 0 && nom2 > c3) ? nom2 : c3;
}
}
double r = 1.0; for(long i=1; i<=n; i++) r *= (double)(2*i)/(double)(2*i-1);
double V = U1[IDX(0,0)], P = (r - 1.0)/2.0;
printf("pairs=%ld band=%ld one=%.9f two=%.9f three=%.9f prophet=%.9f midpoint=%.9f frac2=%.5f%% frac3=%.5f%%\n", n, w, V, U2[IDX(0,0)], U3[w], P, (V+P)/2, 100*(U2[IDX(0,0)]-V)/(P-V), 100*(U3[w]-V)/(P-V));
fflush(stdout); free(U1); free(U2); free(U3);
}
return 0;
}
~~~
#### `review/fable/regret/check_mean.c`
~~~c
#define main peak_entry
#include "peaks.c"
#undef main
static uint64_t state=UINT64_C(991832);
static uint64_t draw(void) {
state=state*UINT64_C(6364136223846793005)+1442695040888963407ULL;
return state;
}
int main(void) {
for(int i=0;i<100000;++i) {
uint64_t den=2*(1+draw()%MAX), a=draw()%(den+1), b=den-a;
unsigned s=31-__builtin_clz((unsigned)den-1);
struct Div d={((U)1<<(64+s))/den,den,s};
U x=((U)(draw()&((UINT64_C(1)<<38)-1))<<64)|draw();
U y=((U)(draw()&((UINT64_C(1)<<38)-1))<<64)|draw();
assert(avg(x,y,a,b,d)==(x*a+y*b)/den);
}
puts("100000 exact high-word division checks passed");
}
~~~
#### `review/fable/regret/decompose.py`
~~~python
"""Outward bounds on the proxy gap, regret, lower-comparison slack and full cap."""
from fractions import Fraction as F
from decimal import Decimal, localcontext, ROUND_FLOOR, ROUND_CEILING
from pathlib import Path
import sys
S = 2**51
P = 2**100
a, b = F(83992367569237,10**14), F(83992367569238,10**14)
values = {}
for line in Path(sys.argv[1] if len(sys.argv)>1 else Path(__file__).with_name('values.txt')).read_text().splitlines():
if line.startswith('conditional'): continue
raw = list(map(int,line.split()))
values[raw[0]] = raw[1:]
def show(bounds):
def rounded(v,mode):
with localcontext() as c:
c.prec=80
return (Decimal(v.numerator)/Decimal(v.denominator)).quantize(Decimal('0.0000000001'),rounding=mode)
return f'[{rounded(bounds[0],ROUND_FLOOR)}, {rounded(bounds[1],ROUND_CEILING)}]'
def add(x,y):return x[0]+y[0],x[1]+y[1]
def sub(x,y):return x[0]-y[1],x[1]-y[0]
def ratio(x,y):return x[0]/y[1],x[1]/y[0]
rl = ru = ul = uu = P
for n in range(1,max(values)//2+1):
N=2*n
# r_n=4^n/C(2n,n), R_N(0)/R_(N-2)(0)=(5N-7)/(5N-5).
rl,ru=rl*N//(N-1),-(-ru*N//(N-1))
ul,uu=ul*(5*N-7)//(5*N-5),-(-uu*(5*N-7)//(5*N-5))
if N not in (482620,1048576,1048578):continue
Q=((1-b*b)*rl/P,(1-a*a)*ru/P)
V,old,mix,half,rule79=[(F(q,S),F(q+3*N+1,S)) for q in values[N]]
configurations=[('old',old,197356261)] if N==482620 else [('half',half,179780061),('mixed',mix,179735647)]
for policy,E,M in configurations:
C=F(M*ul,P*10**9), F(M*uu,P*10**9)
gap=sub(Q,V); regret=sub(V,E); slack=sub(C,sub(Q,E))
print(f'N={N} {policy}: V={show(V)}, Q={show(Q)}, Q-V={show(gap)}, V-E={show(regret)}, E-H={show(slack)}, cap={show(C)}, gap fraction={show(ratio(gap,C))}')
~~~
#### `review/fable/regret/dominance.c`
~~~c
/* A posteriori comparison of the uninterrupted 79 policy with the old hybrid.
cc -O3 -march=native -std=gnu11 dominance.c -o dominance */
#include
#include
#include
#include
typedef __uint128_t U;
#ifndef HORIZON
#define HORIZON 2097152
#endif
enum { WALL=8192, CAP=3072, STRIDE=(WALL+CAP)/2+4 };
static const uint64_t S=UINT64_C(1)<<50;
static uint64_t value[2][STRIDE];
int main(void) {
int b79=1, flo=0, min_t=0, min_x=0, first_t=0;
unsigned count=0;
uint64_t least=UINT64_MAX;
assert(HORIZON<=8388608);
for (int t=1;t<=HORIZON;++t) {
int p=t&1,prev=1-p;
while (79LL*t>112LL*b79*b79+109LL*b79+14) ++b79;
int b=b79+((b79^t)&1);
int bo=b;
if(t>65536) {
const U A=UINT64_C(83992367569237),D=UINT64_C(100000000000000);
while(D*D*(flo+1)*(flo+1)(A+1)*(A+1)*(t+1));
bo=flo+((flo^t)&1);
}
assert(0>64)*m+((U)(uint64_t)v*m>>64);
value[p][j]=(uint64_t)(high>>s);
if(x>=bo) {
assert(value[p][j]>x*S);
uint64_t gain=value[p][j]-x*S;
if(gain=largest[i]:
candidates[i].append(r[0])
for cs in candidates:print(len(cs), cs[0], cs[-1])
assert max(candidates[0])<=327264 and max(candidates[1])<=80848
~~~
#### `review/fable/regret/first_error.py`
~~~python
"""Find the earliest nonoptimal reachable conditional half-card exercise."""
from fractions import Fraction
A, D = 83992367569237, 10**14
w, v = [1], [0]
bad=[]
for t in range(1,111):
w = [a+b for a,b in zip([0]+w,w+[0])]
cont = [a+b for a,b in zip([0]+v,v+[0])]
v=cont.copy()
for k in range(t//2+1,t+1):
x=2*k-t
cash=x*w[k]
v[k]=max(cash,cont[k])
lhs=(2*x+1)**2*D**2
stop=lhs>=4*A*A*t
assert stop==(lhs>=4*(A+1)**2*t)
chosen=cash if stop else cont[k]
if chosen != v[k]:
bad.append((t+abs(x),t,x,Fraction(v[k]-chosen,w[k])))
first=min(bad)
assert first[:3]==(110,102,8)
print(first)
~~~
#### `review/fable/regret/heat_join.c`
~~~c
/* Join the five binary files generated by heat_tail.c, in order 0,...,4. */
#include
#include
#include
#include
typedef __uint128_t U;
enum {N=8388608,W=14200};
int main(int argc,char **argv) {
if(argc!=6)return 2;
FILE *a[5];for(int i=0;i<5;++i){a[i]=fopen(argv[i+1],"rb");if(!a[i])return 1;}
U pl=(U)1<<95,ph=pl;
uint64_t maxupper[5]={0};int at[5]={0};
const uint64_t fs=UINT64_C(1000000000000000);
assert(20ULL*W*W>7ULL*65*(N+1));
assert((U)(N/2)*fs<((U)200<<65));
for(int t=2;t<=N;t+=2) {
uint64_t v[5];for(int i=0;i<5;++i) if(fread(v+i,8,1,a[i])!=1)return 1;
pl=pl*(t-1)/t;ph=(ph*(t-1)+t-1)/t;
uint64_t low=pl>>33, high=(ph+((U)1<<33)-1)>>33;
int sample=t==52||t==65536||t==131070||t==482618||t==482620||t==1000000||
t==1048576||t==2097152||t==4194304||t==N;
if(sample)printf("N=%d",t);
for(int k=1;k<5;k++) {
int64_t raw=(int64_t)v[0]-(int64_t)v[k],rad=t+1000000;
assert(raw+rad>=0);
uint64_t hi=(uint64_t)(((U)(raw+rad)*fs+low-1)/low)+200,lo=0;
if(raw>rad){
uint64_t z=(U)(raw-rad)*fs/high;
if(z>200)lo=z-200;
}
if(t>1048576 && hi>maxupper[k]){maxupper[k]=hi;at[k]=t;}
if(sample)printf(" %" PRIu64 " %" PRIu64,lo,hi);
}
if(sample)putchar('\n');
}
for(int i=0;i<5;++i){assert(fgetc(a[i])==EOF);fclose(a[i]);}
for(int k=1;k<5;++k)printf("tail %d upper=%" PRIu64 " at=%d units_per_dollar=%" PRIu64 "\n",k,maxupper[k],at[k],fs);
/* Each cap is below the corresponding finite-peak lower bound. */
assert(maxupper[1]
#include
#include
#include
typedef __uint128_t U;
enum { N=8388608, W=14200, H=4600, O=W/2+3, L=O+H/2+4 };
static const uint64_t one=UINT64_C(1)<<62;
static const U unit=(U)1<<95;
struct Interval{U lo,hi;};
static struct Interval ratio(struct Interval p,unsigned a,unsigned b){
struct Interval q={p.lo*a/b,(p.hi*a+b-1)/b}; if(q.hi>unit)q.hi=unit;return q;
}
static uint64_t lower(struct Interval p){return p.lo>>33;}
static uint64_t upper(struct Interval p){return (p.hi+((U)1<<33)-1)>>33;}
static uint64_t mass[2][H/2+4], val[2][L];
int main(int argc,char **argv) {
if(argc!=3) return 2;
int mode=atoi(argv[1]); assert(mode>=0&&mode<=4);
FILE *out=fopen(argv[2],"wb");if(!out)return 1;
int floor=0,raw=1,oldedge=0,age=0;
struct Interval edge={unit,unit},center=edge;
uint64_t mass_error=0;mass[0][0]=one;
const U A=UINT64_C(83992367569237),D=UINT64_C(100000000000000);
for(int t=1;t<=N;++t){
int p=t&1,pr=1-p,e;
if(mode==0) {
while(2LL*floor*floor<5LL*t)++floor;
e=floor+((floor^t)&1);if(e>t)e=t;
} else if(mode==4 || ((mode==1||mode==2)&&t<=65536)){
while(79LL*t>112LL*raw*raw+109LL*raw+14)++raw;
e=raw+((raw^t)&1);
} else if(mode==1){
while(D*D*(floor+1)*(floor+1)4*(A+1)*(A+1)*t);
e=raw+((raw^t)&1);
}
assert(abs(e-oldedge)==1 && e<=H);
edge=ratio(edge,t,e>oldedge?t+e:t-e);oldedge=e;
int last=(e-p)/2;
if(mode==0) {
if(p) center=ratio(center,t,t+1);
if(t%128==1){
struct Interval anchor=center;mass_error=0;age=0;
for(int i=0;i<=last;++i) {
mass[p][i]=lower(anchor);
uint64_t width=upper(anchor)-mass[p][i];
if(width>mass_error)mass_error=width;
int x=2*i+p;
if(i0)mass[p][i++]=mass[pr][0];
for(;i>1;
if(upper(edge)-lower(edge)>mass_error)mass_error=upper(edge)-lower(edge);
++age;
}
assert((mass_error+age+1)*e<=1000000);
} else assert((upper(edge)-lower(edge))*e<=1000000);
int reach=t=O?O:r+1;
for(int j=l;j>1;
for(int j=split;j<=r;++j){
uint64_t skip=(val[pr][j+p]+val[pr][j+p-1])>>1;
uint64_t stop=(2*(j-O)+p)*mass[p][j-O];val[p][j]=skip>stop?skip:stop;
}
if(!p && fwrite(&val[0][O],sizeof(uint64_t),1,out)!=1)return 1;
}
return fclose(out)!=0;
}
~~~
#### `review/fable/regret/peaks.c`
~~~c
/* Certified locations of two finite maxima. No floating point.
Compile: cc -std=gnu11 -O3 -march=native peaks.c -o peaks */
#include
#include
#include
#include
typedef __uint128_t U;
enum {W=4096,H=1024,MAX=327264,MIXMAX=80848,SZ=(W+H)/2+4};
static const U S=(U)1<<92;
static U opt[2][SZ],oldrule[2][SZ],mixrule[2][SZ];
static void decimal(U v) {
char digits[42]; int i=41;digits[i]=0;
do {digits[--i]='0'+v%10;v/=10;} while(v);
fputs(digits+i,stdout);
}
/* Compute exact floor(v/d), with v < d*2^103, d<2^20. Pair-of-limbs
reciprocal multiplication leaves an exact residual <2^61. A second
reciprocal multiplication approximates the remaining quotient within 1. */
struct Div {uint64_t m,d; unsigned s;};
static inline U avg(U pu,U pd,unsigned a,unsigned b,struct Div div) {
U v=pu*a+pd*b;
U high=(v>>64)*div.m + ((U)(uint64_t)v*div.m>>64);
U q=high>>div.s;
uint64_t rem=(uint64_t)(v-q*div.d);
uint64_t correction=(uint64_t)((U)rem*div.m>>(64+div.s));
return q+correction+(rem-correction*div.d>=div.d);
}
static int h79=1, hid=0, half=1;
static void bounds(int t,int *hy,int *mx) {
const U A=UINT64_C(83992367569237),D=UINT64_C(100000000000000),L=A*A*t;
if(t<=65536) {
while(112*h79*h79+109*h79+14<79*t) ++h79;
*hy=*mx=h79+((h79^t)&1);
} else {
while(D*D*(hid+1)*(hid+1)(A+1)*(A+1)*(t+1));
*hy=hid+((hid^t)&1);
while(D*D*(2*half+1)*(2*half+1)<4*L) ++half;
assert(D*D*(2*half+1)*(2*half+1)>4*(A+1)*(A+1)*t);
*mx=half+((half^t)&1);
}
}
int main(void) {
U biggest[2]={0,0},biggestcomp[2]={0,0};
int which[2]={0,0},runner[2]={0,0};
int claim[2]={326148,78622};
U witness[2]={0,0}, runner_lower[2]={0,0}, other_upper[2]={0,0};
int runner_claim[2]={326150,78624};
assert(2ULL*H*H>=5ULL*MAX);
assert(20ULL*W*W>7ULL*116*(MAX+1));
assert((U)MAX*S<((U)1<<116));
for(int t=1;t<=MAX;++t) {
int p=t&1,prev=1-p,bhy,bmx;
bounds(t,&bhy,&bmx);
unsigned d=2*t,s=31-__builtin_clz(d-1);
struct Div div={((U)1<<(64+s))/d,d,s};
int lo=t0?S*x:0;
if(x==-W||x==H) {opt[p][j]=oldrule[p][j]=mixrule[p][j]=cash;continue;}
unsigned a=t-x,b=t+x;
U val=avg(opt[prev][up],opt[prev][dn],a,b,div);
opt[p][j]=val>cash?val:cash;
oldrule[p][j]=x>=bhy?cash:avg(oldrule[prev][up],oldrule[prev][dn],a,b,div);
if(t<=65536) mixrule[p][j]=oldrule[p][j];
else if(t<=MIXMAX)
mixrule[p][j]=x>=bmx?cash:avg(mixrule[prev][up],mixrule[prev][dn],a,b,div);
}
if(!p) {
int c=W/2+1;
U raw[2]={opt[0][c]-oldrule[0][c], t<=MIXMAX?opt[0][c]-mixrule[0][c]:0};
for(int k=0;k<2;++k){
if(k==1 && t>MIXMAX) continue;
U err=(U)t+1;
if(t==claim[k]) witness[k]=raw[k]-err;
else if(t==runner_claim[k]) runner_lower[k]=raw[k]-err;
else if(raw[k]+err>other_upper[k]) other_upper[k]=raw[k]+err;
if(raw[k]+err>biggest[k]) {biggest[k]=raw[k]+err;which[k]=t;}
if(t!=claim[k] && raw[k]+err>biggestcomp[k]) {
biggestcomp[k]=raw[k]+err;runner[k]=t;
}
}
}
}
for(int k=0;k<2;++k) {
printf("policy=%s claimed_at=%d lower=",k?"79-then-half":"old",claim[k]);decimal(witness[k]);
printf(" max_other_upper=");decimal(biggestcomp[k]);printf(" at=%d max_upper=",runner[k]);
decimal(biggest[k]);printf(" at=%d units=2^-92 verified=%d",which[k],witness[k]>biggestcomp[k]);
printf(" runner_verified=%d\n",runner_lower[k]>other_upper[k]);
assert(witness[k]>biggestcomp[k] && runner_lower[k]>other_upper[k]);
}
return 0;
}
~~~
#### `review/fable/regret/rare_opening.cpp`
~~~cpp
// Directed conditional evaluation of the uninterrupted 79-rule on the first disagreement.
// Units are 2^-46 dollars. Only nonzero-probability children enter the recursion.
#include
#include
#include
#include
#include
struct Interval { std::uint64_t low, high; };
int main() {
constexpr int target = 65833, left = -2048, right = 256;
constexpr std::uint64_t unit = std::uint64_t{1} << 46;
std::vector row(right-left+1), next(row);
for (int t=1; t<=target; ++t) {
int first=std::max(-t,left);
if ((first+t)%2) ++first;
for (int x=first; x<=std::min(t,right); x+=2) {
auto &value=next[x-left];
if (x==-t) value={0,0};
else if (x>0 && 79LL*t<=112LL*x*x+109LL*x+14) {
auto cash=x*unit;
value={cash,cash};
} else if (x<=left+1) {
value={0,t*unit}; // exhaustion or an upper bound on every eventual payoff
} else {
assert(x((v+round)/(2*t));
};
value={mean(up.low,down.low,0),mean(up.high,down.high,2*t-1)};
}
}
row.swap(next);
}
auto d=row[215-left];
std::cout << d.low-215*unit << ' ' << d.high-215*unit << ' ' << unit << '\n';
}
~~~
#### `review/fable/regret/rare_opening.py`
~~~python
"""Convert a conditional interval in integer units to root regret in dollars."""
from fractions import Fraction
from math import comb
import sys
low, high, scale = map(int, sys.stdin.read().split())
reach = Fraction(comb(33024, 215), comb(66048, 215))
lo, hi = (reach * k / scale for k in (low, high))
assert Fraction(5335, 10**73) < lo <= hi < Fraction(5336, 10**73)
print("5.335e-70 < advantage in dollars < 5.336e-70")
print(f"conditional gain interval: [{low}/{scale}, {high}/{scale}]")
~~~
#### `review/fable/regret/values.c`
~~~c
/* Certified 51-bit Bellman lower values for independently decomposing the bounds. */
#include
#include
#include
#include
typedef __uint128_t U;
enum {W=6144,H=1792,MAX=1048578,SZ=(W+H)/2+4};
static const U S=(U)1<<51;
static uint64_t opt[2][SZ],oldrule[2][SZ],mixrule[2][SZ],half[2][SZ],only79[2][SZ];
struct Div {uint64_t m; unsigned s;};
static inline uint64_t avg(uint64_t pu, uint64_t pd,unsigned a,unsigned b,struct Div div) {
U v=(U)pu*a+(U)pd*b;
U high=(v>>64)*div.m+((U)(uint64_t)v*div.m>>64);
return (uint64_t)(high>>div.s);
}
static int samples[]={52,65536,65538,66048,66306,66308,78622,131070,326148,437186,482618,482620,1000000,1048576,1048578};
int main(void) {
int j79=1,jhalf=1,jbrown=0;
const U A=UINT64_C(83992367569237),D=UINT64_C(100000000000000);
assert(2ULL*H*H>=5ULL*MAX);
assert(20ULL*W*W>7ULL*100*(MAX+1));
assert((U)MAX*S<((U)1<<100));
for(int t=1;t<=MAX;++t) {
int p=t&1,pr=1-p;
while(79LL*t>112LL*j79*j79+109LL*j79+14) ++j79;
while(D*D*(2*jhalf+1)*(2*jhalf+1)<4*A*A*t) ++jhalf;
assert(D*D*(2*jhalf+1)*(2*jhalf+1)>4*(A+1)*(A+1)*t);
while(D*D*(jbrown+1)*(jbrown+1)(A+1)*(A+1)*(t+1));
int b79=j79+((j79^t)&1),bh=jhalf+((jhalf^t)&1),
bo=t<=65536?b79:jbrown+((jbrown^t)&1),bm=t<=65536?b79:bh;
unsigned den=2*t,s=31-__builtin_clz(den-1);
struct Div div={((U)1<<(64+s))/den,s};
int lo=t0?(uint64_t)(S*x):0;
if(x==-W||x==H) {opt[p][j]=oldrule[p][j]=mixrule[p][j]=half[p][j]=only79[p][j]=cash;continue;}
unsigned a=t-x,b=t+x;
uint64_t val=avg(opt[pr][up],opt[pr][dn],a,b,div);
opt[p][j]=val>cash?val:cash;
oldrule[p][j]=x>=bo?cash:avg(oldrule[pr][up],oldrule[pr][dn],a,b,div);
mixrule[p][j]=x>=bm?cash:avg(mixrule[pr][up],mixrule[pr][dn],a,b,div);
half[p][j]=x>=bh?cash:avg(half[pr][up],half[pr][dn],a,b,div);
only79[p][j]=x>=b79?cash:avg(only79[pr][up],only79[pr][dn],a,b,div);
if(t==65833 && x==215)
printf("conditional %d %d %" PRIu64 "\n",t,x,only79[p][j]);
}
for(unsigned i=0;i0) != test:
recorded.append((m,p))
print('scope 0 <= m <= 201, 0 <= p <= 100, excluding the empty urn')
print('ties', ties)
for desc, er in zip(('printed 11','full alpha, unchanged c','alpha*sqrt(t)-0.495','alpha*sqrt(t)-0.5'), errors):
print(desc, len(er), er)
assert ties == [(2,1)] and not errors[0]
if __name__ == '__main__': replay()
~~~
#### `review/fable/survival/audit.py`
~~~python
"""Check the F3 normalization and its small-deck zero probabilities exactly."""
import argparse
import csv
import math
from fractions import Fraction
def exact_rows(t_max):
cash = [0]
zero = [1]
counts = [1]
for t in range(1, t_max + 1):
def sums(c):
return [a+b for a,b in zip([0]+c,c+[0])]
counts = sums(counts)
draw = sums(cash)
zero_draw = sums(zero)
scores = [(2*m-t)*counts[m] for m in range(t+1)]
# Stop on ties; the tuple cash[0]=0 is the separate terminal condition.
cash = [max(x,y) for x,y in zip(scores,draw)]
zero = [0 if x>=y else p for x,y,p in zip(scores,draw,zero_draw)]
if t % 2 == 0:
yield t,Fraction(cash[t//2],counts[t//2]),Fraction(zero[t//2],counts[t//2])
def main():
parser = argparse.ArgumentParser()
parser.add_argument('csv')
parser.add_argument('--exact', type=int, default=600)
parser.add_argument('--replay', help='output of replay.cpp')
args = parser.parse_args()
with open(args.csv) as source:
rows = {int(r['cards']):r for r in csv.DictReader(source)}
pkey='prob_optimal_player_ends_with_zero'
value_key='optimal_value_Vn'
small=[]
for n,v,p in exact_rows(args.exact):
if n in rows:
# The supplied table rounds its original long-double values.
assert abs(float(v)-float(rows[n][value_key]))<5e-10
assert abs(float(p)-float(rows[n][pkey]))<5e-10
small.append(n)
if n==52:
print(f'52 exact P0 = {p}, V = {v}')
print(f'{len(small)} supplied rows through {small[-1]} cards agree with exact counting')
mu=.231166686734485919
if args.replay:
discrepancies = []
with open(args.replay) as source:
for line in source:
t, price, risk = line.split()
t=int(t)
if t not in rows:
continue
discrepancies.append((t,abs(float(risk)-float(rows[t][pkey]))))
print('Wider-wall replay max P0 difference',max(discrepancies,key=lambda x:x[1]))
print('cards P0 cards^mu*P0 pairs^mu*P0 dyadic slope')
for i in range(16,24):
t=2**i
r=float(rows[t][pkey])
s=math.log2(r/float(rows[t//2][pkey]))
print(f'{t:7d} {r:.9f} {t**mu*r:.9f} {(t/2)**mu*r:.9f} {s:.7f}')
for k in ['proxy_minus_Vn',pkey]:
v = float(rows[2**23][k])
print(k, 'scaled by cards', v*2**(23*mu),'scaled by pairs',v*2**(22*mu))
if __name__=='__main__':
main()
~~~
#### `review/fable/survival/replay.cpp`
~~~cpp
// Independent probability replay. Two rows, direct probability weights, and a
// wide negative wall. Optional tabulation up to the supplied card count.
#include
#include
#include
#include
#include
int main(int argc, char **argv) {
const int n = argc > 1 ? std::atoi(argv[1]) : 65536;
const double wall = argc > 2 ? std::atof(argv[2]) : 9.;
if (n < 2 || n%2 || n > (1<<25) || wall < 5 || wall > 16) return 2;
const int mid = static_cast(std::ceil(wall*std::sqrt(n)))+8;
const int upper = static_cast(std::ceil(2*std::sqrt(n)))+8;
std::vector v0(mid+upper), v1(mid+upper);
std::vector z0(mid+upper), z1(mid+upper);
z0[mid] = 1;
// h=V-x is the optional future return. For x<0 its floor equals -x.
// Outside the negative wall assign payoff zero, probability one.
for (int t = 1; t <= n; ++t) {
int low = std::max(-t, -static_cast(std::ceil(wall*std::sqrt(t))));
int high = std::min(t, static_cast(std::ceil(2*std::sqrt(t)))+3);
if ((low-t)%2) ++low;
if ((high-t)%2) --high;
const double inv = 1./(2*t);
for (int x = low; x <= high; x += 2) {
const int i = x+mid;
// Work with expected additional profit so the stopping threshold is
// a comparison to zero. The only low-deck tie is (t,x)=(3,1).
const double gain = ((t-x)*v0[i+1] + (t+x)*v0[i-1] - 2*x)*inv;
const bool cash = x>0 && (gain<=0 || (t==3 && x==1));
v1[i] = cash ? 0 : gain;
z1[i] = cash ? 0 : ((t-x)*z0[i+1]+(t+x)*z0[i-1])*inv;
}
v1[mid+high+2]=0;
z1[mid+high+2]=0;
v1[mid+low-2]=-(low-2);
z1[mid+low-2]=1;
if (t == 52 || t == 2000000 || t == n || (t>=1024 && !(t&(t-1))))
std::printf("%d %.15g %.15g\n",t,v1[mid],z1[mid]);
v0.swap(v1); z0.swap(z1);
}
}
~~~
#### `review/fable/ties/rank.cpp`
~~~cpp
// Check exact diagonal data from ties.cpp against candidate polynomial recurrences.
// The determinant reported is for the square minor on n=0,...,cols-1.
// c++ -std=c++17 -O3 rank.cpp -lgmpxx -lgmp -o rank && ./rank < D640.txt
#include
#include
#include
#include
#include
#include
constexpr uint32_t prime=(uint32_t(1)<<31)-1;
uint32_t mod(uint64_t v) { uint32_t w=(v&prime)+(v>>31);return w>=prime ? w-prime : w; }
uint32_t power(uint32_t a,uint32_t e) {
uint32_t b=1;
while (e) { if (e&1)b=mod(uint64_t(a)*b);a=mod(uint64_t(a)*a);e>>=1; }
return b;
}
uint32_t determinant(const std::vector& seq,int r,int d) {
const int n=(r+1)*(d+1);
if (seq.size() mat(n*n);
for (int i=0;i seq;
int i; mpz_class v;
while (std::cin>>i>>v) { if (i!=int(seq.size())) return 2; seq.push_back(mpz_fdiv_ui(v.get_mpz_t(),prime)); }
const std::pair specs[]={{1,300},{2,200},{3,150},{5,100},{8,66},{12,46},{20,28}};
std::cout<<"order degree rank determinant_mod_2147483647\n";
for(auto [r,d]:specs) {
const auto det=determinant(seq,r,d);
if (!det) throw std::runtime_error("singular leading square minor");
std::cout<draw)-(cash0 or (action[r,b]==0 and stop_on_ties):
deals=c*comb(t,r)
payout[b-r]+=deals
draws[2*n-t]+=deals
else:
for z in [(r-1,b),(r,b-1)]:
if min(z)>=0:prefixes[z]=prefixes.get(z,0)+c
return payout,draws,arrivals
if __name__=="__main__":
n=26
a,total=policies(n); decks=comb(2*n,n)
assert [z for z in a if a[z]==0]==[(1,2)]
results=[]
for tie in [True,False]:
payout,draws,arrivals=played(n,a,tie)
assert sum(payout.values())==sum(draws.values())==decks
assert sum(x*c for x,c in payout.items())==total
risk=Fraction(payout[0],decks); turns=Fraction(sum(x*c for x,c in draws.items()),decks)
print('stop tie' if tie else 'draw tie','deals with zero',payout[0],'risk',risk,float(risk),'draws',turns,float(turns))
results.append((payout,draws,arrivals))
stop,draw=results
p=Fraction(3*stop[2],decks)
assert stop[2]==draw[2]
assert all(draw[0][h]-stop[0][h]=={0:1,1:-2,2:1}.get(h,0)*stop[2] for h in set(stop[0])|set(draw[0]))
print('prefixes',stop[2], 'reach probability',p,float(p),'delta risk',p/3,'delta cards',2*p,'expected price',Fraction(total,decks))
~~~
#### `review/fable/ties/ties.cpp`
~~~cpp
// Every Bellman comparison on 0<=r,b<=n, using exact signed integers.
// Build: c++ -std=c++17 -O3 ties.cpp -lgmpxx -lgmp -o ties
#include
#include
#include
#include
#include
#include
int main(int argc, char** argv) {
if (argc!=2 && argc!=3) return 2;
int n=0; std::string arg=argv[1];
auto parsed=std::from_chars(arg.data(),arg.data()+arg.size(),n);
if (parsed.ec!=std::errc{} || parsed.ptr!=arg.data()+arg.size() || n<=0 || n>1000000) return 2;
bool diagonal=argc==3 && std::string(argv[2])=="--diagonal";
bool extend=argc==3 && std::string(argv[2])=="--all-black-counts";
if (argc==3 && !diagonal && !extend) return 2;
int bmax=n;
if (extend) {
int margin=1;
while (int64_t(margin)*margin<16LL*n) ++margin;
bmax+=margin;
}
std::vector count(bmax+1,1), value(bmax+1);
mpz_class candidate;
uint64_t stop=0,draw=0,ties=0;
for (int r=0;r<=n;++r) {
for (int b=0;b<=bmax;++b) {
if (r || b) {
if (r && b) count[b]+=count[b-1];
// Before maximizing, value[b] contains the r-child total,
// zero on the first row. The b-child total is to its left.
if (b) value[b]+=value[b-1];
mpz_mul_si(candidate.get_mpz_t(),count[b].get_mpz_t(),b-r);
int cmp=mpz_cmp(candidate.get_mpz_t(),value[b].get_mpz_t());
if (extend && b==bmax && cmp<=0) {
std::cerr<<"last column does not consist entirely of strict stops\n"; return 1;
}
if (cmp>0) { ++stop; mpz_swap(value[b].get_mpz_t(),candidate.get_mpz_t()); }
else if (cmp<0) ++draw;
else { ++ties; std::cerr<<"tie r="<
#### `review/formal/CentGameCap.lean`
~~~lean
import asmproof.UpperGame
import CentPolicyCap
/-! Endpoint cancellation for the exact finite Problem 14 value. The
upper comparison is the pre-Wallis part of GameUpperPrice.upper_price.
The policy-specific lower envelope and the finite-sweep guarantee appear
as explicit premises attaching the independently verified policy and
its C certificates. -/
namespace Problem14.CentGameCap
open Upper GameUpperPrice GameComparison GameCentral
open P14Quote.Coefficient
private theorem nextBarrier (c : ℝ) (t : ℕ) (j : ℤ) :
barrier c (t+1) j = barrier c t j + barrier c t (j-1) := by
simp only [barrier, Upper.heat, Int.cast_add]
ring
private theorem tight_upper {c : ℝ} (hc : 58905 ≤ 100000*c) (T n : ℕ) (hn : T≤2*n)
(cut : test T=true)
(stop : ∀ t : ℕ, T
by_cases out : j<0 ∨ (t:ℤ) omega
| succ t =>
have e := stop (t+1) (by omega) j (by omega) (by omega)
have p := ih t (by omega) (by omega) j
have q := ih t (by omega) (by omega) (j-1)
rw [nextBarrier] at e ⊢
simp only [cell,advance,Int.cast_max,Int.cast_add,Int.cast_mul] at e ⊢
rw [mul_max_of_nonneg _ _ (by norm_num)]
exact max_le e (by linarith only [p,q])
have g := prop (2*n) hn n
have a : (cell (2*n) n).2 = (closedNumerator n n : ℤ)-n*(weight (deck n n):ℤ) := by
rw [two_mul,cell_eq_game n n n (by omega),closedNumerator_eq_bellman]; rfl
rw [a,barrier,mid_center] at g
have b : (heat bump (2*n) n : ℝ) ≤ 0 := by exact_mod_cast bump_center n
let w := weight (deck n n)
have wpos : (0:ℝ)< w := by
dsimp [w]; rw [GameComparison.deck_count]; exact_mod_cast Nat.choose_pos (by omega : n≤n+n)
have pre : GameComparison.price n ≤ (c/2)*GameWallis.invMass n := by
unfold GameComparison.price GameWallis.invMass
rw [GameComparison.deck_count,←two_mul,←Nat.centralBinom_eq_two_mul_choose]
change (0:ℝ) < weight (deck n n) at wpos
rw [GameComparison.deck_count,←two_mul,←Nat.centralBinom_eq_two_mul_choose] at g wpos
push_cast at g
rw [←mul_div_assoc,div_le_div_iff_of_pos_right wpos]
linarith only [g,b]
exact pre
theorem exact_common_upper (n : ℕ) (hn : 1800≤n) :
GameComparison.price n ≤ (1-threshold^2)*GameWallis.invMass n := by
have e := brownian_root_bounds threshold_spec.1 threshold_spec.2
norm_num [xLo,xHi] at e
have cap : threshold ≤ 839925/1000000 := by linarith
have hpos := threshold_spec.1
have coef : 58905≤100000*(2*(1-threshold^2)) := by
nlinarith [mul_nonneg (sub_nonneg.mpr cap) (show 0≤839925/1000000+threshold by linarith)]
have h := tight_upper coef 3600 n (by omega) verified_cutoff_3600 (fun t ht => UpperReal.game_obstacle t (by omega))
linarith only [h]
private theorem denom_pos (n : ℕ) : 0 < product 5 n := by
induction n with
| zero => decide
| succ n ih => exact Nat.mul_pos (by omega) ih
/-- One strict bound, in dollars, for any policy with the indicated
achieved finite return and attained high-deck lower comparator. -/
theorem all_sizes (n : ℕ) (policy : ℝ)
(small : n ≤ 241309 → price n-policy ≤ (2075264:ℝ)/2^32)
(large : 241310 ≤ n → (1-threshold^2)*GameWallis.invMass n -
((197356261:ℝ)/10^9)*((product 3 n:ℝ)/(product 5 n:ℝ)) ≤ policy) :
price n-policy < 9804191707/10^12 := by
by_cases tiny : n≤241309
· exact (small tiny).trans_lt (by norm_num)
· have big : 241310≤n := by omega
have hi := exact_common_upper n (by omega)
have lo := large big
have dp : 0<(product 5 n:ℝ) := by exact_mod_cast denom_pos n
have cert := CentPolicyCap.large_cap n big
have zz : ((9804191707:ℝ)*10^9)*(product 5 n:ℝ) >
((10:ℝ)^12*197356261)*(product 3 n:ℝ) := by
exact_mod_cast cert
have comparison : ((197356261:ℝ)/10^9)*((product 3 n:ℝ)/(product 5 n:ℝ)) <
9804191707/10^12 := by
rw [← mul_div_assoc, div_lt_iff₀ dp]
linarith only [zz]
linarith only [hi,lo,comparison]
#print axioms exact_common_upper
#print axioms all_sizes
end Problem14.CentGameCap
~~~
#### `review/formal/FullHistoryPrice.lean`
~~~lean
import Vouchers
import asmproof.GameMachinePrice
/-! Full-history semantics for the ordinary balanced game, with exact root
normalization and connections to the scalar machine and printed certificates. -/
namespace Problem14.FullHistoryPrice
open Vouchers
/-- Legal shifted totals for deterministic stopping, where the continuation
at each distinct history may be chosen independently. With zero vouchers,
the constructor allowing an unseen card to be inspected is impossible. -/
def totals (n : ℕ) : Set ℕ := {v | Attains n (.finite 0) (deck n n) v}
/-- Any count-only rule defines an allowable full-history strategy. -/
theorem rule_legal (R : ℕ) (q : Rule) (t : Tree) :
Attains R (.finite 0) t (score R q t) := by
induction t with
| empty => simpa [score,paths] using Attains.empty (R:=R) (.finite 0)
| leaf => simpa [score,paths,firstPay] using Attains.leaf (R:=R) (.finite 0)
| branch s l r hl hr =>
rw [score_branch]
cases h : q s
· exact Attains.draw s hl hr
· exact Attains.stop _ _ _ _
/-- The maximum over all legal decision trees equals the maximum over
state-based stopping sets. The latter is attained by a state-based rule. -/
theorem greatest_total (n : ℕ) :
IsGreatest (totals n) (closedNumerator n n) ∧
∃ q : Rule, score n q (deck n n) = closedNumerator n n := by
have eq : closedNumerator n n = best n (deck n n) (.finite 0) := by
rw [closedNumerator_eq_bellman,zero_eq_bellman]
constructor
· rw [eq]
exact ⟨attainable n (deck n n) (.finite 0), fun _ hv => bounds hv⟩
· have h := optimal_in_scores n n
obtain ⟨stops,_,hq⟩ := List.mem_map.mp h
exact ⟨fun s => decide (s ∈ stops), hq.trans (closedNumerator_eq_bellman n n).symm⟩
/-- Normalize one shifted integer total, removing the n-dollar payoff shift
and averaging over all equally probable completed color words. -/
noncomputable def dollars (n v : ℕ) : ℝ :=
((v:ℝ)-n*(weight (deck n n):ℝ))/(weight (deck n n):ℝ)
def payoffs (n : ℕ) : Set ℝ := dollars n '' totals n
/-- Maximum expected cash over the full-history policies. -/
noncomputable def fullPrice (n : ℕ) : ℝ :=
dollars n (best n (deck n n) (.finite 0))
theorem greatest_price (n : ℕ) : IsGreatest (payoffs n) (fullPrice n) := by
constructor
· exact ⟨_,attainable n (deck n n) (.finite 0),rfl⟩
· rintro _ ⟨v,hv,rfl⟩
change dollars n v ≤ dollars n (best n (deck n n) (.finite 0))
apply div_le_div_of_nonneg_right _ (Nat.cast_nonneg _)
exact sub_le_sub_right (by exact_mod_cast bounds hv) _
@[simp] theorem fullPrice_eq_price (n : ℕ) : fullPrice n = GameComparison.price n := by
unfold fullPrice dollars GameComparison.price
rw [zero_eq_bellman,closedNumerator_eq_bellman]
/-- The particular fair price certified by the executable is attained over
all observed-history stopping policies. Every such policy earns at most it. -/
theorem price_is_greatest (n : ℕ) : IsGreatest (payoffs n) (GameComparison.price n) := by
rw [← fullPrice_eq_price]
exact greatest_price n
/-- Randomly choosing among any finite family of ordinary full-history
strategies cannot improve the expected payoff over the same ceiling. -/
theorem finite_mixture_le {ι : Type*} (n : ℕ) (s : Finset ι) (w z : ι → ℝ)
(hw : ∀ i ∈ s, 0 ≤ w i) (total : ∑ i ∈ s, w i = 1)
(allowed : ∀ i ∈ s, z i ∈ payoffs n) :
∑ i ∈ s, w i * z i ≤ GameComparison.price n := by
calc
_ ≤ ∑ i ∈ s, w i * GameComparison.price n :=
Finset.sum_le_sum (fun i hi => mul_le_mul_of_nonneg_left ((price_is_greatest n).2 (allowed i hi)) (hw i hi))
_ = GameComparison.price n := by rw [← Finset.sum_mul, total, one_mul]
/-- The full-history dollar value and a state-only maximizing rule, in one
statement for every deck size (including the empty deck). -/
theorem markov_suffices (n : ℕ) :
IsGreatest (payoffs n) (GameComparison.price n) ∧
∃ q : Rule, dollars n (score n q (deck n n)) = GameComparison.price n := by
obtain ⟨_,q,hq⟩ := greatest_total n
refine ⟨price_is_greatest n,q,?_⟩
rw [hq]
rfl
open P14Entry P14Quote
/-- The model of the actual scalar instructions returns an enclosure of
the legally attainable full-history maximum on its stated machine domain. -/
theorem scalar_machine {n f g hint : ℕ} (hn : 32768≤n) (hu : n<2^64)
(d0 d1 d2 d3 : ℕ) (fl : f<2^64) (fh : g<2^64) {mem : D.Table} (table : D.tableOK mem)
(s : M.State) (sl sh : R.CPU) (sd : D.State) :
IsGreatest (payoffs n) (fullPrice n) ∧
EntryReturns n f g hint d0 d1 d2 d3 mem s sl sh sd (fun z =>
(z.outLo:ℝ)/10^6 ≤ fullPrice n ∧ fullPrice n ≤ (z.outHi:ℝ)/10^6) := by
refine ⟨greatest_price _,?_⟩
simpa only [fullPrice_eq_price] using
P14Entry.machine_encloses_game (hint:=hint) hn hu d0 d1 d2 d3 fl fh table s sl sh sd
/-- A record accepted by the output verifier bounds the full-history
maximum and its nearest cent; either convention at a half-cent tie is legal. -/
theorem printed_record {o : Record} {w : Witness} (check : o.Check w) :
IsGreatest (payoffs o.pairs) (fullPrice o.pairs) ∧
((o.lo:ℝ)/10^6 ≤ fullPrice o.pairs ∧ fullPrice o.pairs ≤ (o.hi:ℝ)/10^6 ∧
∀ c : ℕ, (c:ℝ)-1/2 ≤ 100*fullPrice o.pairs → 100*fullPrice o.pairs ≤ (c:ℝ)+1/2 →
(o.lowCent ≤ c ∧ c ≤ o.highCent) ∧ (o.single = true → c=o.lowCent)) := by
refine ⟨greatest_price _,?_⟩
simpa only [fullPrice_eq_price] using P14Entry.printed_game check
#print axioms markov_suffices
#print axioms scalar_machine
#print axioms printed_record
end Problem14.FullHistoryPrice
~~~
#### `review/formal/FullHistoryRecords.lean`
~~~lean
import FullHistoryPrice
import RecordReplay
/-! The three archived checked records also certify the rounded maximum
over legal full-history stopping policies, in integer cents. -/
namespace Problem14.FullHistoryPrice
open P14CheckedOutput
theorem checked_records :
⌊100*fullPrice 133787000+1/2⌋₊ = 603822 ∧
⌊100*fullPrice 500000000+1/2⌋₊ = 1167312 ∧
⌊100*fullPrice 1000000000000+1/2⌋₊ = 52203768 := by
simpa only [fullPrice_eq_price] using And.intro roundedCents0 (And.intro roundedCents1 roundedCents2)
#print axioms checked_records
end Problem14.FullHistoryPrice
~~~
#### `review/formal/FullHistoryRegret.lean`
~~~lean
import FullHistoryPrice
import CentGameCap
import CentPolicy
/-! A single conditional regret theorem for the actual class of policies in
the one-cent analysis, lifted to every legal full-history competitor. The
hypotheses describe finite comparison checks and a pointwise contact
inequality. No assumption on the achieved large-deck *root* price is used. -/
namespace Problem14.FullHistoryRegret
open FullHistoryPrice GameLower GameComparison GameFractional GameCentral
open P14Quote.Coefficient (threshold)
abbrev cutoff : ℕ := 65536
noncomputable def rate : ℝ := 197356261/10^9
/-- The late policy is the deployed integer 79-rule. A physical frontier
is the first stopping column on each large remaining-time layer. -/
def player (wall : Frontier cutoff) (s : State) : Bool :=
let t := s.1+s.2
let x := s.2-s.1
if t≤cutoff then decide (0 a j+u*b j) k m = heat a k m+u*heat b k m := by
induction k generalizing m with
| zero => rfl
| succ k ih =>
cases m with
| zero => exact ih 0
| succ m => simp only [heat,ih]; ring
private theorem proxy_heat (k m : ℕ) :
heat (proxy cutoff) k m = proxy (cutoff+k) m := by
unfold proxy
rw [heat_sum,←comparator_heat (2*(1-threshold^2)) cutoff (by decide),
←coefficient_heat]
private theorem balanced_proxy (n : ℕ) (hn : 3≤2*n) : proxy (2*n) n =
(1-threshold^2)*(2:ℝ)^(2*n)-rate*C (2*n) n := by
unfold proxy H
rw [Upper.mid_center, odd_center n hn]
push_cast
ring
private theorem lower_root (n : ℕ) (large : 241310≤n) (wall : Frontier cutoff)
(inside : n≤wall.column (2*n))
(row : ∀ r b, r+b=cutoff → r≤n → b≤wall.column cutoff →
proxy cutoff b ≤ (CentPolicy.policyMass n (player wall) r b:ℝ))
(contact : ∀ k r b, r+b=cutoff+k → r≤n → b=wall.column (cutoff+k) →
proxy (cutoff+k) b ≤ (stopMass r b:ℝ)) :
(1-threshold^2)*GameWallis.invMass n -
((197356261:ℝ)/10^9)*((product 3 n:ℝ)/(product 5 n:ℝ)) ≤
dollars n (score n (player wall) (deck n n)) := by
let k := 2*n-cutoff
have hk : cutoff+k=2*n := by dsimp [k,cutoff]; omega
have raw := CentPolicy.policy_lower_from_terminal money cutoff n wall
(player wall) (proxy cutoff)
(by intro r b ht; change (if r+b≤cutoff then _ else _) = _; rw [if_neg (by omega)])
row
(by intro j r b ht hr hw; rw [proxy_heat]; exact contact j r b ht hr hw)
k n n (by omega) (by omega) (by simpa only [hk] using inside)
rw [proxy_heat,hk,balanced_proxy n (by omega)] at raw
have w : weight (deck n n)=(2*n).choose n := by rw [deck_count,two_mul]
have wp : (0:ℝ)<(2*n).choose n := by exact_mod_cast Nat.choose_pos (by omega : n≤2*n)
change _ ≤ (CentPolicy.policyMass n (player wall) n n : ℝ) at raw
simp only [CentPolicy.policyMass,Int.cast_sub,Int.cast_mul,Int.cast_natCast,w] at raw
unfold GameWallis.invMass dollars
rw [←central_ratio, w, Nat.centralBinom]
rw [←mul_div_assoc,←mul_div_assoc,←sub_div, div_le_div_iff_of_pos_right wp]
simpa only [rate] using raw
/-- The inputs are a bound from the finite sweep, the initial certified
layer, the admissible advancing frontier (plus the balanced start lying
inside it), and the inequality at exercise. The conclusion quantifies
over all history-dependent ordinary strategies and holds in unshifted
expected dollars for the late 79-rule / early frontier policy. -/
theorem all_competitors (wall : Frontier cutoff)
(small : ∀ n≤241309, GameComparison.price n -
dollars n (score n (player wall) (deck n n)) ≤ (2075264:ℝ)/2^32)
(inside : ∀ n≥241310, n≤wall.column (2*n))
(row : ∀ n≥241310, ∀ r b, r+b=cutoff → r≤n → b≤wall.column cutoff →
proxy cutoff b ≤ (CentPolicy.policyMass n (player wall) r b:ℝ))
(contact : ∀ k r b, r+b=cutoff+k → b=wall.column (cutoff+k) →
proxy (cutoff+k) b ≤ (stopMass r b:ℝ))
(n : ℕ) :
dollars n (score n (player wall) (deck n n)) ∈ payoffs n ∧
∀ competitor ∈ payoffs n,
competitor - dollars n (score n (player wall) (deck n n)) < 9804191707/10^12 := by
constructor
· exact ⟨_,rule_legal n (player wall) (deck n n),rfl⟩
· intro competitor legal
have ceiling := (price_is_greatest n).2 legal
have bound := CentGameCap.all_sizes n _ (small n)
(fun h => lower_root n h wall (inside n h) (row n h)
(fun k r b ht _ hw => contact k r b ht hw))
linarith only [ceiling,bound]
#print axioms all_competitors
end Problem14.FullHistoryRegret
~~~
#### `review/formal/HalfCardCap.lean`
~~~lean
import FullHistoryPrice
import CentGameCap
/-! Independent central bound for the two half-card policies. The
normalized central product at and beyond 2^20 total cards is verified using
only the first 2,048 factors and a universal polynomial inequality. -/
namespace Problem14.HalfCardCap
open GameCentral FullHistoryPrice
open P14Quote.Coefficient (threshold)
private def p := product 3
private def q := product 5
private theorem qpos (n : ℕ) : 0 decide
| succ n ih => exact Nat.mul_pos (by omega) ih
private theorem local_moment (n : ℕ) (hn : 1≤n) :
(n+1)*(10*n+3)^5 ≤ n*(10*n+5)^5 := by
obtain ⟨j,rfl⟩ := Nat.exists_eq_add_of_le hn
have e : (1+j+1)*(10*(1+j)+3)^5 +
(16789+j*(63232+j*(84200+j*(48000+j*10000)))) = (1+j)*(10*(1+j)+5)^5 := by ring
exact e ▸ Nat.le_add_right _ _
/-- mR_m^5 decreases, where the subscript here counts pairs. This
cross-multiplied form uses no floating point, gamma functions or limits. -/
private theorem moments (m k : ℕ) (hm : 1≤m) :
(m+k)*(p (m+k))^5*(q m)^5 ≤ m*(p m)^5*(q (m+k))^5 := by
induction k with
| zero => exact Nat.le_refl _
| succ k ih =>
let n := m+k
have pl : p (n+1) = (10*n+3)*p n := rfl
have ql : q (n+1) = (10*n+5)*q n := rfl
change (n+1)*(p (n+1))^5*(q m)^5 ≤ m*(p m)^5*(q (n+1))^5
rw [pl,ql,Nat.mul_pow,Nat.mul_pow]
calc
_ = ((n+1)*(10*n+3)^5)*((p n)^5*(q m)^5) := by ring
_ ≤ (n*(10*n+5)^5)*((p n)^5*(q m)^5) :=
Nat.mul_le_mul_right _ (local_moment n (by dsimp [n]; omega))
_ = (n*(p n)^5*(q m)^5)*(10*n+5)^5 := by ring
_ ≤ (m*(p m)^5*(q n)^5)*(10*n+5)^5 := Nat.mul_le_mul_right _ ih
_ = _ := by ring
private theorem tail (m b a d n : ℕ) (hm : 1≤m) (mb : m≤b) (bn : b≤n)
(h : m*(p m)^5*d^5 < b*a^5*(q m)^5) :
d*p n < a*q n := by
have w := moments m (n-m) hm
rw [show m+(n-m)=n by omega] at w
have sep : (n*(q m)^5)*(d*p n)^5 < (n*(q m)^5)*(a*q n)^5 := by
rw [Nat.mul_pow,Nat.mul_pow]
calc
_ = (n*(p n)^5*(q m)^5)*d^5 := by ring
_ ≤ (m*(p m)^5*(q n)^5)*d^5 := Nat.mul_le_mul_right _ w
_ = (m*(p m)^5*d^5)*(q n)^5 := by ring
_ < (b*a^5*(q m)^5)*(q n)^5 := Nat.mul_lt_mul_of_pos_right h (Nat.pow_pos (qpos n))
_ = b*((q m)^5*a^5*(q n)^5) := by ring
_ ≤ n*((q m)^5*a^5*(q n)^5) := Nat.mul_le_mul_right _ bn
_ = _ := by ring
by_cases ok : d*p n < a*q n
· exact ok
· exfalso
exact (Nat.not_lt_of_ge (Nat.pow_le_pow_left (Nat.le_of_not_gt ok) 5))
(Nat.lt_of_mul_lt_mul_left sep)
abbrev centralNum : ℕ := 748318041695
abbrev centralDen : ℕ := 2^44
set_option maxRecDepth 25000 in
set_option maxHeartbeats 20000000 in
private theorem first_factors :
2048*(p 2048)^5*centralDen^5 < 524288*centralNum^5*(q 2048)^5 := by decide +kernel
/-- Independent, kernel-only uniform enclosure for the entire central tail. -/
theorem central_bound (n : ℕ) (hn : 524288≤n) :
centralDen*product 3 n < centralNum*product 5 n :=
tail 2048 524288 centralNum centralDen n (by decide) (by decide) hn first_factors
inductive Kind where | half | mixed
def lambdaNum : Kind → ℕ
| .half => 179780061 | .mixed => 179735647
def finiteNum : Kind → ℕ
| .half => 104567189475 | .mixed => 234108592
def targetNum : Kind → ℕ
| .half => 7647297 | .mixed => 7645408
private theorem small_compare (k : Kind) :
(finiteNum k:ℝ)/2^52 < (targetNum k:ℝ)/10^9 := by
cases k <;> norm_num [finiteNum,targetNum]
private theorem large_compare (k : Kind) :
((lambdaNum k:ℝ)/10^9)*(centralNum/centralDen:ℝ) < (targetNum k:ℝ)/10^9 := by
cases k <;> norm_num [lambdaNum,targetNum,centralNum,centralDen]
/-- Given the finite sweep and the specified attained lower comparator,
each policy has the indicated strict global regret ceiling in dollars.
The full-history upper bound on the game and the central estimate are
proved theorems. The lower bound hypotheses are where the independently
verified finite/terminal tables and the analytic exercise argument enter. -/
theorem all_sizes (k : Kind) (rule : Rule) (n : ℕ)
(small : n≤524288 → GameComparison.price n-dollars n (score n rule (deck n n))
≤ (finiteNum k:ℝ)/2^52)
(large : 524288≤n → (1-threshold^2)*GameWallis.invMass n -
((lambdaNum k:ℝ)/10^9)*((product 3 n:ℝ)/(product 5 n:ℝ)) ≤
dollars n (score n rule (deck n n))) :
∀ z ∈ payoffs n, z-dollars n (score n rule (deck n n)) < (targetNum k:ℝ)/10^9 := by
intro z legal
have upper := (price_is_greatest n).2 legal
by_cases sn : n≤524288
· linarith only [upper,(small sn).trans_lt (small_compare k)]
· have hn : 524288≤n := by omega
have price := CentGameCap.exact_common_upper n (by omega)
have eq := large hn
have qp : 0<(product 5 n:ℝ) := by exact_mod_cast qpos n
have cp : (0:ℝ) norm_num [targetNum]
#print axioms central_bound
#print axioms all_sizes
end Problem14.HalfCardCap
~~~
#### `review/formal/IdealPlayer.lean`
~~~lean
import FullHistoryPrice
import CentGameCap
import CentPolicy
import CentQuick
/-! An unconditional all-deck subcent theorem for an explicitly defined
mathematical hybrid. Use the optimal DP on small decks; above the cutoff
use the ideal Brownian contact column followed by an exact finite endgame.
This is a different policy from the deployed 79-rule / dyadic approximation. -/
namespace Problem14.IdealPlayer
open GameLower GameComparison GameFractional GameCentral
open GameLowerPrice GameCutoff GameCalibration FullHistoryPrice
open P14Quote.Coefficient
private theorem root_hi : threshold ≤ 1 :=
(brownian_root_bounds threshold_spec.1 threshold_spec.2).2.trans (by norm_num [xHi])
noncomputable def idealWall : Frontier time :=
frontier threshold threshold_spec.1 root_hi time (by decide)
private def unusedWall (t : ℕ) : Frontier t where
column := fun _ => 0
advance := by intros; omega
physical := by intros; omega
/-- The early formula of the small-deck wall is unreachable. The explicit
cutoff at the initial deck size makes this branch use the exact optimizer. -/
noncomputable def play (n : ℕ) : Rule :=
if n<233631 then CentPolicy.rule n (2*n) (unusedWall (2*n))
else CentPolicy.rule n time idealWall
private theorem endgame_row (n r b : ℕ) (h : r+b=time) (hr : r≤n)
(inside : b decide
| succ n ih => exact Nat.mul_pos (by omega) ih
/-- At every balanced deck size the hybrid earns within one cent of the
actual price. There are no certificate, boundary or approximation premises. -/
theorem subcent (n : ℕ) :
GameComparison.price n - dollars n (score n (play n) (deck n n)) < 1/100 := by
by_cases small : n<233631
· rw [play,if_pos small,CentPolicy.exact_endgame _ _ _ _ _ (by omega)]
unfold GameComparison.price dollars
rw [closedNumerator_eq_bellman,sub_self]
norm_num
· have hi := CentGameCap.exact_common_upper n (by omega)
have lo := lower_price n (by omega)
have p : 0<(product 5 n:ℝ) := by exact_mod_cast prod_pos n
have cut := (CentQuick.exact_debit_threshold n).2 (by omega)
have h : 20*(product 3 n:ℝ) < (product 5 n:ℝ) := by exact_mod_cast cut
have d : (1/5:ℝ)*((product 3 n:ℝ)/(product 5 n:ℝ)) < 1/100 := by
rw [←mul_div_assoc, div_lt_iff₀ p]
linarith only [h]
linarith only [hi,lo,d]
/-- Full-history, policy-level cash guarantee at all nonnegative sizes. -/
theorem all_ordinary_strategies (n : ℕ) :
dollars n (score n (play n) (deck n n)) ∈ payoffs n ∧
∀ z ∈ payoffs n, z - dollars n (score n (play n) (deck n n)) < 1/100 := by
refine ⟨⟨_,rule_legal _ _ _,rfl⟩,?_⟩
intro z legal
have hh := (price_is_greatest n).2 legal
linarith only [hh,subcent n]
#print axioms subcent
#print axioms all_ordinary_strategies
end Problem14.IdealPlayer
~~~
#### `review/formal/check.sh`
~~~bash
#!/usr/bin/env bash
set -euo pipefail
# First build the project's full mathlib/assembly verification graph. The
# argument names the extracted project root. Set P14_ANALYTIC_LEAN_PATH to
# its compiled module directory followed by the pinned mathlib library paths.
project=$(cd -- "${1:?give the extracted project root}" && pwd)
here=$(cd -- "$(dirname -- "$0")" && pwd)
work=$(mktemp --directory)
trap 'rm --force --recursive -- "$work"' EXIT
export LEAN_PATH="$work:${P14_ANALYTIC_LEAN_PATH:?give compiled project and mathlib paths}"
lean_cmd=${LEAN:-lean}
compile() {
local src=$1 module
module=$(basename -- "$src" .lean)
"$lean_cmd" --root="$(dirname -- "$src")" -o "$work/$module.olean" "$src"
}
compile "$project/further/formal/Vouchers.lean"
for module in CentCutoff CentQuick CentPolicyCap CentPolicy; do
compile "$project/cent/formal/$module.lean"
done
compile "$project/asmproof/RecordReplay.lean"
for module in CentGameCap FullHistoryPrice FullHistoryRecords FullHistoryRegret IdealPlayer HalfCardCap; do
compile "$here/$module.lean"
done
~~~
#### `review/formal/replay.log`
~~~text
'Problem14.CentCutoff.exact_debit_threshold' depends on axioms: [propext,
Classical.choice,
Lean.ofReduceBool,
Quot.sound]
'Problem14.CentQuick.exact_debit_threshold' depends on axioms: [propext, Quot.sound]
'Problem14.CentPolicyCap.first_subcent' depends on axioms: [propext, Classical.choice, Lean.ofReduceBool, Quot.sound]
'Problem14.CentPolicyCap.large_cap' depends on axioms: [propext, Classical.choice, Lean.ofReduceBool, Quot.sound]
'Problem14.CentPolicyCap.small_cap' does not depend on any axioms
'Problem14.CentPolicy.policy_lower' depends on axioms: [propext, Classical.choice, Quot.sound]
'Problem14.CentGameCap.exact_common_upper' depends on axioms: [propext, Classical.choice, Lean.ofReduceBool, Quot.sound]
'Problem14.CentGameCap.all_sizes' depends on axioms: [propext, Classical.choice, Lean.ofReduceBool, Quot.sound]
'Problem14.FullHistoryPrice.markov_suffices' depends on axioms: [propext, Classical.choice, Quot.sound]
'Problem14.FullHistoryPrice.scalar_machine' depends on axioms: [propext,
Classical.choice,
Lean.ofReduceBool,
Quot.sound]
'Problem14.FullHistoryPrice.printed_record' depends on axioms: [propext,
Classical.choice,
Lean.ofReduceBool,
Quot.sound]
'Problem14.FullHistoryPrice.checked_records' depends on axioms: [propext,
Classical.choice,
Lean.ofReduceBool,
Quot.sound]
'Problem14.FullHistoryRegret.all_competitors' depends on axioms: [propext,
Classical.choice,
Lean.ofReduceBool,
Quot.sound]
'Problem14.IdealPlayer.subcent' depends on axioms: [propext, Classical.choice, Lean.ofReduceBool, Quot.sound]
'Problem14.IdealPlayer.all_ordinary_strategies' depends on axioms: [propext,
Classical.choice,
Lean.ofReduceBool,
Quot.sound]
'Problem14.HalfCardCap.central_bound' depends on axioms: [propext, Classical.choice, Quot.sound]
'Problem14.HalfCardCap.all_sizes' depends on axioms: [propext, Classical.choice, Lean.ofReduceBool, Quot.sound]
~~~
#### `review/heat5m.log`
~~~text
pairs=5000000 wall=15001 cells=91550427997 interval=[1358268294122938070/1163589468354244,1358268294133588701/1163589468354243] lower=1167.308858547889 upper=1167.308858557044
~~~
#### `review/heat_independent.log`
~~~text
pairs=1000000 wall=6547 cells=8014541894 interval=[1358260719377406661/2601864888956427,1358260719379699598/2601864888956426] lower=522.033532618285 upper=522.033532619167
pairs=10000000 wall=21381 cells=260704415933 interval=[1358269636195002935/822782013875311,1358269636215922742/822782013875310] lower=1650.825629740665 upper=1650.825629766093
~~~
#### `review/peak-limit.py`
~~~python
"""Numerical evaluation of the direct-peak Huffman subsequential mean. Optional SciPy."""
from math import exp, expm1, floor, log, sqrt
from scipy.special import lambertw
from scipy.optimize import brentq
entropy = (1 + .5772156649015328606/2)/log(2)-1
qmin = -log(2/exp(1))/(2*log(2))
def sums(theta, a):
kmin = floor(theta+a+qmin)
total_kraft = width = 0
expected_k = kmin
for k in range(kmin+1,kmin+70):
h = -.5*2**(2*(theta+a-k))
zlo = -.5*lambertw(h,0).real
zhi = -.5*lambertw(h,-1).real
new_width = sqrt(zhi)-sqrt(zlo)
expected_k += -expm1(-zlo)+exp(-zhi)
total_kraft += 2**(theta-k+1)*(new_width-width)
width = new_width
return total_kraft,expected_k
def limit(theta):
a = brentq(lambda x: sums(theta,x)[0]-1,0,1)
return a,sums(theta,a)[1]-theta-entropy
if __name__=='__main__':
for t in [0,.25,.5,.75]:
print(t,*limit(t))
~~~
#### `review/reproduce-regressions.py`
~~~python
"""Replay the 2022 fits on a local copy of FeepingCreature's published data."""
import math
import sys
from pathlib import Path
def fit(xs, ys, functions):
# Center before QR to retain precision at the 133,787,000-pair observation.
cols = [[1.0] * len(xs)] + [[f(x) for x in xs] for f in functions]
qs, rs = [], []
for col in cols:
residual = col.copy()
coeffs = []
for q in qs:
weight = math.fsum(x * y for x, y in zip(q, residual))
residual = [v - weight * e for v, e in zip(residual, q)]
coeffs.append(weight)
norm = math.sqrt(math.fsum(v * v for v in residual))
qs.append([v / norm for v in residual])
rs.append(coeffs + [norm])
coefficients = [math.fsum(x * y for x, y in zip(q, ys)) for q in qs]
for row in reversed(range(len(coefficients))):
coefficients[row] -= math.fsum(rs[col][row] * coefficients[col]
for col in range(row + 1, len(cols)))
coefficients[row] /= rs[row][row]
predicted = [math.fsum(c * x for c, x in zip(coefficients, row))
for row in zip(*cols)]
df = len(xs) - len(cols)
error = math.sqrt(math.fsum((y - z) ** 2 for y, z in zip(ys, predicted)) / df)
return coefficients, df, error, predicted
def main():
tab = [float(x) for x in Path(sys.argv[1]).read_text().split()]
assert len(tab) == 22975
x = list(range(1, len(tab))) + [100000]
y = tab[1:] + [165.076]
log, root = math.log, math.sqrt
observed = [fit(x, y, fs) for fs in ([log], [root], [log, root])]
cases = [
("positive sizes, square root", observed[1]),
("positive sizes, joint fit", observed[2]),
("all sizes including zero, square root", fit([0] + x, [tab[0]] + y, [root])),
("observations plus predictions, joint fit",
fit(x * 4, y + sum((f[3] for f in observed), []), [log, root])),
("add historical record, square root",
fit(x + [133787000], y + [6038.22], [root])),
]
for label, (coef, df, rse, _) in cases:
print(label, *(f"{v:.12g}" for v in coef), df, f"{rse:.12g}", sep="\t")
if __name__ == "__main__":
main()
~~~
#### `review/rule/certify.c`
~~~c
/* Finite comparisons of stopping policies. Requires 64-bit and 128-bit
unsigned integers. No floating point, lookup table, or math library. */
#ifdef NDEBUG
#error The interval and boundary checks require assertions.
#endif
#include
#include
#include
#include
#include
typedef unsigned __int128 u128;
#ifdef EXTEND
enum { WALL=4094, LAST=1048576, TAIL_BITS=45, SWITCH=65536, STRIDE=WALL+3 };
#else
enum { WALL=3072, LAST=482618, TAIL_BITS=55, SWITCH=65536, STRIDE=WALL+3 };
#endif
static const uint64_t scale=UINT64_C(1)<<52;
static uint64_t opt[2][STRIDE], half[2][STRIDE], hybrid[2][STRIDE], revised[2][STRIDE];
struct divisor { uint64_t m; int s; };
static struct divisor prepare(unsigned d) {
int s=31-__builtin_clz(d-1);
return (struct divisor){ ((u128)1<<(64+s))/d, s };
}
/* q=floor(v*m / 2^(64+s)), evaluated by splitting v into 64-bit limbs.
0 <= v/d - q < 3, since m=floor(2^(64+s)/d), d<=2^(s+1)
and v <= d*WALL*scale, with WALL*scale < 2^64. */
static inline uint64_t mean(uint64_t a,uint64_t b,uint64_t wa,uint64_t wb,
struct divisor div) {
u128 v=(u128)a*wa+(u128)b*wb;
u128 high=(v>>64)*div.m + (((u128)(uint64_t)v*div.m)>>64);
return (uint64_t)(high>>div.s);
}
static int half_lower=1, brown_floor=0, old_lower=1;
static void boundaries(int t, int *bhalf, int *bhybrid) {
const u128 d=UINT64_C(100000000000000), l=UINT64_C(83992367569237), h=l+1;
int x=half_lower;
while (d*d*(2*x+1)*(2*x+1)<4*l*l*t) ++x;
assert(d*d*(2*x+1)*(2*x+1)>4*h*h*t);
assert(x==1 || d*d*(2*x-1)*(2*x-1)<4*l*l*t);
const u128 native=(u128)4*UINT64_C(13013657395120439157)*t;
assert(((u128)(2*x+1)*(2*x+1)<<64)>=native);
assert(x==1 || ((u128)(2*x-1)*(2*x-1)<<64)112LL*x*x+109LL*x+14) ++x;
old_lower=x;
} else {
x=brown_floor;
while (d*d*(x+1)*(x+1)h*h*(t+1));
brown_floor=x;
}
*bhybrid=x+((x^t)&1);
assert(*bhalf>0 && *bhybrid>0 && *bhalf> TAIL_BITS);
if(t<=65536) tails=1; /* This range even satisfies t*scale*2^-100 < 1. */
const uint64_t radius=3*(uint64_t)t+tails;
uint64_t roots[]={half[0][j],hybrid[0][j],revised[0][j]};
const char *names[]={"half","hybrid","79-then-half"};
if (rows) fprintf(rows,"%d",t);
for(int k=0;k<3;++k) {
assert(opt[0][j]>=roots[k]);
uint64_t raw=opt[0][j]-roots[k];
uint64_t lo=raw>radius?raw-radius:0, hi=raw+radius;
if (rows) fprintf(rows," %" PRIu64 " %" PRIu64 " %" PRIu64,raw,lo,hi);
if(lo>largest_lower[k]) { largest_lower[k]=lo; lower_at[k]=t; }
if(hi>largest_upper[k]) { largest_upper[k]=hi; upper_at[k]=t; }
if(raw>largest_raw[k]) { largest_raw[k]=raw; raw_at[k]=t; }
if(t==20000 || t==482618 || t==LAST) {
printf("through=%d %s max_lo=%" PRIu64 " at=%d max_hi=%" PRIu64 " at=%d max_raw=%" PRIu64 " at=%d scale=%" PRIu64 "\n",
t,names[k],largest_lower[k],lower_at[k],largest_upper[k],upper_at[k],
largest_raw[k],raw_at[k],scale);
}
}
if (rows) fputc('\n',rows);
}
int main(int argc,char **argv) {
FILE *rows=NULL;
if(argc==2) { rows=fopen(argv[1],"w"); if(!rows) return 2; }
else if(argc!=1) return 2;
assert((u128)WALL*scale<((u128)1<<64));
assert((uint64_t)20*WALL*WALL>7ULL*TAIL_BITS*(LAST+1));
assert((uint64_t)20*WALL*WALL>7ULL*100*(65536+1));
for(int t=1;t<=LAST;++t) {
int p=t&1, old=1-p, hi=t0?(uint64_t)x*scale:0;
if(x==-WALL||x==WALL) {
opt[p][j]=half[p][j]=hybrid[p][j]=revised[p][j]=cash;
continue;
}
int up=j+p, down=up-1;
unsigned a=t-x,b=t+x;
uint64_t wait=mean(opt[old][up],opt[old][down],a,b,d);
opt[p][j]=cash>wait?cash:wait;
half[p][j]=x>=bh?cash:mean(half[old][up],half[old][down],a,b,d);
hybrid[p][j]=x>=bb?cash:mean(hybrid[old][up],hybrid[old][down],a,b,d);
if(t<=SWITCH) revised[p][j]=hybrid[p][j];
else revised[p][j]=x>=bh?cash:mean(revised[old][up],revised[old][down],a,b,d);
}
if(!p) record(t,rows);
}
return rows && fclose(rows)!=0;
}
~~~
#### `review/rule/cutoff-half.txt`
~~~text
T=482618 tilt=17/8 cubic=105000 mode=1 survivors=241601 worst=-1344 lambda=195233017/10^9 central_upper=873941876893/17592186044416
T=482618 tilt=17/8 cubic=120000 mode=1 survivors=241601 worst=-1278 lambda=194750247/10^9 central_upper=873941876893/17592186044416
T=482618 tilt=17/8 cubic=135000 mode=1 survivors=241601 worst=-1224 lambda=194547099/10^9 central_upper=873941876893/17592186044416
T=482618 tilt=17/8 cubic=150000 mode=1 survivors=241601 worst=-1180 lambda=194554242/10^9 central_upper=873941876893/17592186044416
~~~
#### `review/rule/cutoff-hybrid.txt`
~~~text
T=482618 tilt=17/8 cubic=120000 mode=2 survivors=241601 worst=-1278 lambda=194704752/10^9 central_upper=873941876893/17592186044416
T=482618 tilt=17/8 cubic=135000 mode=2 survivors=241601 worst=-1224 lambda=194501683/10^9 central_upper=873941876893/17592186044416
~~~
#### `review/rule/cutoff.c`
~~~c
/* Pointwise cutoff certificate for the half-card policy and the 79/half hybrid.
Compile with cc -O3 -std=gnu11 cutoff.c -o cutoff. Example:
./cutoff 482618 17 1 135000 (time, tilt in eighths, policy, cubic weight)
Policy 1 plays half throughout; policy 2 plays 79 through 65,536. */
#include
#include
#include
#include
#include
#ifdef NDEBUG
#error The certificate needs assertions enabled.
#endif
typedef __int128 Int128;
typedef unsigned __int128 Uint128;
static int T, wall;
enum {high_cap=2048};
static const uint64_t policy_unit = UINT64_C(1) << 32;
static const int64_t unit = INT64_C(1) << 44;
static int tilt_eighths, run_half;
static int cash_out(int t, int x) {
if (!run_half || (run_half==2 && t<=65536)) return x>0 && 79LL*t <= 112LL*x*x+109LL*x+14;
if (x<=0) return 0;
const Uint128 d=UINT64_C(100000000000000), a=UINT64_C(83992367569237);
const Uint128 lhs=d*d*(2*x+1)*(2*x+1);
assert((lhs>=4*a*a*t)==(lhs>=4*(a+1)*(a+1)*t));
return lhs>=4*a*a*t;
}
/* At the artificial negative edge the rule's payoff is bounded below by 0.
Every possible cash-out is positive and a full deck returns to zero. */
static int cutoff_policy(uint64_t **output) {
size_t length = wall + high_cap + 1;
uint64_t *old = calloc(length, sizeof(*old));
uint64_t *next = calloc(length, sizeof(*next));
assert(old && next);
int top = 0;
for (int t = 1; t <= T; ++t) {
top += cash_out(t, top - 1) ? -1 : 1;
assert(top <= high_cap && cash_out(t, top) && !cash_out(t, top - 2));
int bottom = t <= wall ? -t : -wall + (t & 1);
next[wall + bottom] = 0;
const uint64_t recip=t==1?0:((Uint128)1<<64)/t;
for (int x = bottom+2; x < top; x += 2) {
uint64_t up_count = (unsigned)(t - x)/2;
uint64_t down_count = (unsigned)(t + x)/2;
/* All values <= high_cap*policy_unit by induction. The weighted
numerator <= T*high_cap*policy_unit <= 2^63. The high
product with floor(2^64/t) rounds the result downward. */
uint64_t v=up_count*old[wall+x+1]+down_count*old[wall+x-1];
next[wall+x]=(Uint128)v*recip>>64;
}
next[wall+top] = top*policy_unit;
uint64_t *tmp = old;
old = next;
next = tmp;
}
free(next);
*output = old;
return top;
}
static uint64_t ceil_unsigned(Uint128 a, uint64_t b) {
Uint128 q = a/b + (a%b != 0);
assert(q <= UINT64_MAX);
return (uint64_t)q;
}
static int64_t ceil_signed(Int128 a, int64_t b) {
Int128 q = a/b + (a%b > 0);
assert(INT64_MIN <= q && q <= INT64_MAX);
return (int64_t)q;
}
static void compare(uint64_t *policy, int top, int cubic_weight) {
int frontier=2;
/* The first exercise at time T under the upper-time half-card rule. */
while ((Uint128)UINT64_C(100000000000000)*UINT64_C(100000000000000)
*(2*frontier+1)*(2*frontier+1) <
(Uint128)4*UINT64_C(83992367569237)*UINT64_C(83992367569237)*T)
frontier+=2;
assert((Uint128)UINT64_C(100000000000000)*UINT64_C(100000000000000)
*(2*frontier+1)*(2*frontier+1) >
(Uint128)4*UINT64_C(83992367569238)*UINT64_C(83992367569238)*T);
assert(cash_out(T,frontier));
assert(frontier==2 || (Uint128)UINT64_C(100000000000000)*UINT64_C(100000000000000)
*(2*frontier-3)*(2*frontier-3) <
(Uint128)4*UINT64_C(83992367569237)*UINT64_C(83992367569237)*T);
const int last=(T+frontier-2)/2;
const int64_t den=(int64_t)T*(T-1)*(T-2);
uint64_t rlo=unit, rhi=unit, dlo=0, dhi=0, fhi=unit/2;
uint64_t central=0, max_billionths=0; int worst=0;
for (int m=0; m<=last; ++m) {
int x=2*m-T;
uint64_t lower = x < -wall ? 0 : x >= top ? x*policy_unit : policy[wall+x];
int64_t cubic = (int64_t)x*x*x - (3LL*T-2)*x;
/* 58905643803/1e11 >= 2(1-alpha^2), checked by the coefficient
bracket accompanying the existing analytic comparison proof. */
Int128 deficit = (Int128)ceil_unsigned((Uint128)58905643803ULL*fhi, 100000000000ULL)
+ ceil_signed(-(Int128)tilt_eighths*x*unit, 8*T)
+ ceil_signed((Int128)cubic_weight*cubic*unit, den)
- (Int128)lower * (unit / policy_unit);
assert(rlo>0);
if (deficit > 0) {
uint64_t billionths = ceil_unsigned((Uint128)deficit*1000000000, rlo);
if (billionths > max_billionths) { max_billionths=billionths; worst=x; }
}
if (x == 0) central = rhi;
if (m == last) break;
/* r=R_T, d first difference; f=F_T/p_T. All endpoints in Q44. */
uint64_t dl = (uint64_t)(((Uint128)5*m*dlo + 4*rlo) / (5*(T-m)));
uint64_t dh = ceil_unsigned((Uint128)5*m*dhi + 4*rhi, 5*(T-m));
assert(dl <= dh && dh < rlo);
rlo -= dh; rhi -= dl; dlo = dl; dhi = dh;
assert(fhi <= UINT64_MAX - (uint64_t)(unit/2));
uint64_t q = ceil_unsigned((Uint128)(m+1)*(fhi+unit/2), T-m);
assert(q <= UINT64_MAX - (uint64_t)(unit/2));
fhi = unit/2 + q;
}
printf("T=%d tilt=%d/8 cubic=%d mode=%d survivors=%d worst=%d lambda=%" PRIu64 "/10^9 central_upper=%" PRIu64 "/%" PRIu64 "\n",
T,tilt_eighths,cubic_weight,run_half,last+1,worst,max_billionths,central,(uint64_t)unit);
fflush(stdout);
}
int main(int argc,char **argv) {
if(argc<5) return 2;
T=atoi(argv[1]); tilt_eighths=atoi(argv[2]); run_half=atoi(argv[3]);
assert(T>=65536 && T<=1048576 && T%2==0 && tilt_eighths>=8 && tilt_eighths<=32 &&
run_half>=0 && run_half<=2);
int root=1; while(root*root=0 && k<500000);
compare(policy,top,k);
}
free(policy);
return 0;
}
~~~
#### `review/rule/exact.py`
~~~python
"""Find the first failing balanced root for two stopping rules by counting paths."""
from fractions import Fraction
D = 10**14
A = 83992367569237
def check(limit):
ways, optimal, half, old = [[z] for z in (1, 0, 0, 0)]
seen = set()
for t in range(1, limit + 1):
layers = (ways, optimal, half, old)
w, o, h, a = ([i+j for i, j in zip([0]+l, l+[0])] for l in layers)
for k in range(t//2+1, t+1):
x = 2*k-t
stop = x*w[k]
o[k] = max(stop, o[k])
lhs = D*D*(2*x+1)**2
assert (lhs >= 4*A*A*t) == (lhs >= 4*(A+1)**2*t)
if lhs >= 4*A*A*t:
h[k] = stop
if 79*t <= 112*x*x+109*x+14:
a[k] = stop
ways, optimal, half, old = w, o, h, a
if t % 2 == 0:
k=t//2
for name,policy in [('half',h), ('79',a)]:
if o[k] != policy[k] and name not in seen:
loss = Fraction(o[k]-policy[k], w[k])
print(f'first suboptimal: {name}, cards={t}, approximate regret={float(loss):.14g}')
if name == 'half':
print(f'exact half-card loss: {loss}')
seen.add(name)
if t == 220:
print(f'exact half-card loss at 220 cards: {Fraction(o[k]-h[k],w[k])}')
if t == 3600:
print(f'79 rule optimal at 3600 cards: {a[k]==o[k]}')
if len(seen)==2 and t>=3600:
return
print(f'Without discrepancy through {limit} total cards:', sorted({'half','79'}-seen))
if __name__=='__main__':
check(4000)
~~~
#### `review/rule/extended.txt`
~~~text
through=20000 half max_lo=104567188153 at=220 max_hi=104567189475 at=220 max_raw=104567188814 at=220 scale=4503599627370496
through=20000 hybrid max_lo=7073031 at=20000 max_hi=7193033 at=20000 max_raw=7133032 at=20000 scale=4503599627370496
through=20000 79-then-half max_lo=7073031 at=20000 max_hi=7193033 at=20000 max_raw=7133032 at=20000 scale=4503599627370496
through=482618 half max_lo=104567188153 at=220 max_hi=104567189475 at=220 max_raw=104567188814 at=220 scale=4503599627370496
through=482618 hybrid max_lo=1186240372915 at=326108 max_hi=1186325823898 at=326188 max_raw=1186283095800 at=326148 scale=4503599627370496
through=482618 79-then-half max_lo=213507426 at=78068 max_hi=234108592 at=79222 max_raw=223770241 at=78622 scale=4503599627370496
through=1048576 half max_lo=104567188153 at=220 max_hi=104567189475 at=220 max_raw=104567188814 at=220 scale=4503599627370496
through=1048576 hybrid max_lo=1186240372915 at=326108 max_hi=1186325823898 at=326188 max_raw=1186283095800 at=326148 scale=4503599627370496
through=1048576 79-then-half max_lo=213507426 at=78068 max_hi=234108592 at=79222 max_raw=223770241 at=78622 scale=4503599627370496
~~~
#### `review/rule/half64.c`
~~~c
/* Native half-card policy. Define P14_HALF_LIBRARY for the callable routine alone. */
#include
#include
bool p14_halfcard_stop(uint64_t t, uint64_t profit, bool hybrid) {
/* profit is max(actual signed score,0). At exhaustion collect zero. */
if (!t) return true;
if (!profit) return false;
if (hybrid && t<=65536)
return 79*t<=112*profit*profit+109*profit+14; /* feasible profit <= t */
if (profit>=UINT32_MAX) return true;
const uint64_t beta=UINT64_C(13013657395120439157);
const __uint128_t rhs=(__uint128_t)beta*t;
uint64_t pivot=(uint64_t)(rhs>>64)+((uint64_t)rhs>(UINT64_C(1)<<62));
return profit*(profit+1)>=pivot;
}
#ifndef P14_HALF_LIBRARY
#include
#include
#include
static bool parse(const char *s,uint64_t *out) {
uint64_t v=0;
if (!*s) return false;
while (*s) {
unsigned c=(unsigned char)*s++-'0';
if (c>9 || v>(UINT64_MAX-c)/10) return false;
v=10*v+c;
}
*out=v; return true;
}
int main(int argc,char **argv) {
bool hybrid=argc==4 && strcmp(argv[1],"--hybrid")==0;
if (argc!=3+(int)hybrid) {
fputs("Usage: half64 [--hybrid] REMAINING_CARDS SCORE\n",stderr);
return 2;
}
const char *score=argv[2+hybrid];
bool negative=*score=='-';
uint64_t t,x;
if (!parse(argv[1+hybrid],&t) || !parse(score+negative,&x) || x>t || ((x^t)&1)) {
fputs("Input must be a feasible 64-bit deck state.\n",stderr);
return 2;
}
puts(p14_halfcard_stop(t,negative?0:x,hybrid)?"stop":"draw");
}
#endif
~~~
#### `review/rule/half_player.py`
~~~python
#!/usr/bin/env python3
"""Half-card stopping rule for balanced red/black decks of arbitrary size.
For example: python3 half_player.py 65600 216
Add --hybrid to use the 79 rule through 65,536 remaining cards.
The root-bracketing functions are shared with the earlier one-cent player.
"""
from functools import lru_cache
from math import isqrt
LO = 83992367569237
HI = 83992367569238
DEN = 10**14
CUT = 65536
C64 = 13013657395120439157
def ceildiv(a, b):
return -(-a//b)
def atan_inv(q, unit):
"""Outward bounds, scaled by unit, for atan(1/q)."""
lo = hi = k = 0
power = q
while True:
den = (2*k+1)*power
floor = unit//den
ceil = ceildiv(unit, den)
if not floor:
# The alternating tail has magnitude below the first missing term.
return (lo, hi+1) if k%2 == 0 else (lo-1, hi)
if k%2 == 0:
lo, hi = lo+floor, hi+ceil
else:
lo, hi = lo-ceil, hi-floor
power *= q*q
k += 1
def profile_coefficients(unit):
"""Enclose A(0)=sqrt(pi/2) and coefficients of A'=1+yA."""
l5,h5 = atan_inv(5,unit)
l239,h239 = atan_inv(239,unit)
lo = isqrt((16*l5-4*h239)*unit//2)
hi = 1+isqrt((16*h5-4*l239)*unit//2)
coeffs = [(lo,hi),(unit,unit)]
while max(coeffs[-2][1],coeffs[-1][1]) > 1:
n = len(coeffs)
lo,hi = coeffs[-2]
coeffs.append((lo//n,ceildiv(hi,n)))
return coeffs
def residual(y,unit,coeffs):
"""Enclose unit*((1-z*z)*A(z)-z), z=y/unit in [0.8,0.85]."""
lo = hi = 0
for a,b in reversed(coeffs):
lo,hi = a+y*lo//unit, b+ceildiv(y*hi,unit)
# All omitted coefficients are at most one unit; sum z^j <= 1/(1-.85)<7.
hi += 7
factor = unit*unit-y*y
return factor*lo//(unit*unit)-y, ceildiv(factor*hi,unit*unit)-y
@lru_cache(maxsize=16)
def squared_slope(bits):
"""Return floor(2^bits times a certified lower approximation to alpha²)."""
if bits < 10:
raise ValueError('at least ten bits are required')
precision = bits+16+bits.bit_length()
while True:
unit = 1 << precision
coeffs = profile_coefficients(unit)
lo,hi = LO*unit//DEN,ceildiv(HI*unit,DEN)
if residual(lo,unit,coeffs)[0] <= 0 or residual(hi,unit,coeffs)[1] >= 0:
lo,hi = 83*unit//100,ceildiv(84*unit,100)
assert residual(lo,unit,coeffs)[0] > 0
assert residual(hi,unit,coeffs)[1] < 0
target = unit >> bits
while hi-lo > target:
mid = (lo+hi)//2
low,high = residual(mid,unit,coeffs)
if low > 0:
lo = mid
elif high < 0:
hi = mid
else:
# |((1-y²)A(y)-y)'| >= y² > 1/2 throughout the bracket.
# Handles exact dyadic roots as well as arbitrarily close ones.
radius = 2*max(-low,high)
a,b = max(lo,mid-radius),min(hi,mid+radius)
if b-a >= hi-lo:
break
lo,hi = a,b
if hi-lo <= target:
return (lo*lo << bits)//(unit*unit)
precision += 16
def coefficient(t):
if t < 0:
raise ValueError('negative remaining card count')
if t.bit_length() <= 64:
return C64,64
# 2^k >= 1024*sqrt(t+1). Squaring and rounding loses <1.6 more ulps
# in alpha, even for huge t; the resulting displacement is <1/256.
k = ((t+1).bit_length()+1)//2+10
return squared_slope(k),k
def stop(t, x, hybrid=False):
if t < 0 or abs(x) > t or (x - t) % 2:
raise ValueError("score must be a feasible state at remaining time t")
if t == 0:
return True
if x <= 0:
return False
if hybrid and t <= CUT:
return 79*t <= 112*x*x + 109*x + 14
numerator, bits = coefficient(t)
return ((2*x+1)**2 << bits) >= 4*t*numerator
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--hybrid", action="store_true")
parser.add_argument("remaining_cards", type=int)
parser.add_argument("score", type=int)
args = parser.parse_args()
try:
print("stop" if stop(args.remaining_cards, args.score, args.hybrid) else "draw")
except ValueError as err:
parser.error(str(err))
~~~
#### `review/rule/inspect.py`
~~~python
"""Check the main numerical comparisons from rows produced by certify.c."""
from fractions import Fraction as F
import sys
S = 1 << 52
floor_at_220 = None
second_ceiling = 0
maxima = [[0, 0] for _ in range(3)]
samples = {}
n_expected = 2
for line in sys.stdin:
fields = list(map(int, line.split()))
n = fields[0]
assert n == n_expected and len(fields) == 10
n_expected += 2
if n in (52,108,110,220,1000,20000,65536,65538,324112,326148,482618):
samples[n] = fields
for k in range(3):
point,lo,hi = fields[1+3*k:4+3*k]
assert 0 <= lo <= point <= hi
maxima[k][0] = max(maxima[k][0],lo)
maxima[k][1] = max(maxima[k][1],hi)
if n == 220:
floor_at_220 = fields[2]
else:
second_ceiling = max(second_ceiling,fields[3])
assert n_expected-2 in (482618,1048576)
assert second_ceiling < floor_at_220
exact220 = F(72488967276486426577168700697814634219544059316768826981483,
3122024123597085540529144157661138972950207588060244786268891680)
assert samples[220][2] <= S*exact220 <= samples[220][3]
assert maxima[0][1] < F(24,10**6)*S
assert maxima[2][1] < F(6,10**8)*S
if n_expected-2 == 482618:
assert samples[324112][6] < maxima[1][0]
print('Unique maximum half-card loss at 220:', float(exact220), 'dollars')
for name,(lo,hi) in zip(['half','old hybrid','79 then half'], maxima):
print(name, 'maximum regret in', lo, hi, 'units of 2^-52 dollars')
base = samples[65536]
print('Old hybrid peak divided by switch-time regret:',
float(F(maxima[1][0],base[6])), float(F(maxima[1][1],base[5])))
~~~
#### `review/rule/large-half.txt`
~~~text
T=1048576 tilt=17/8 cubic=300000 mode=1 survivors=524718 worst=-1810 lambda=179780061/10^9 central_upper=748318041695/17592186044416
~~~
#### `review/rule/large-hybrid.txt`
~~~text
T=1048576 tilt=17/8 cubic=300000 mode=2 survivors=524718 worst=-1810 lambda=179735647/10^9 central_upper=748318041695/17592186044416
~~~
#### `review/rule/output.txt`
~~~text
through=20000 half max_lo=104567188153 at=220 max_hi=104567189475 at=220 max_raw=104567188814 at=220 scale=4503599627370496
through=20000 hybrid max_lo=7073031 at=20000 max_hi=7193033 at=20000 max_raw=7133032 at=20000 scale=4503599627370496
through=20000 79-then-half max_lo=7073031 at=20000 max_hi=7193033 at=20000 max_raw=7133032 at=20000 scale=4503599627370496
through=482618 half max_lo=104567188153 at=220 max_hi=104567189475 at=220 max_raw=104567188814 at=220 scale=4503599627370496
through=482618 hybrid max_lo=1186282076587 at=326148 max_hi=1186284115017 at=326150 max_raw=1186283095800 at=326148 scale=4503599627370496
through=482618 79-then-half max_lo=223524565 at=78608 max_hi=224015961 at=78634 max_raw=223770241 at=78622 scale=4503599627370496
first suboptimal: half, cards=110, approximate regret=2.0670367635986e-06
exact half-card loss: 2789854560504399388648199/1349687925069778859939436617184
exact half-card loss at 220 cards: 72488967276486426577168700697814634219544059316768826981483/3122024123597085540529144157661138972950207588060244786268891680
79 rule optimal at 3600 cards: True
Without discrepancy through 4000 total cards: ['79']
~~~
#### `review/rule/test_players.py`
~~~python
"""Check native and arbitrary-size player decisions, constants and main caps."""
import ctypes
from fractions import Fraction as F
from math import isqrt
from pathlib import Path
import random
import subprocess
import tempfile
import half_player as p
base = Path(__file__).resolve().parent
assert (F(p.HI,p.DEN)-F(1,256*2**32))**2 <= F(p.C64,2**64) <= F(p.LO,p.DEN)**2
rng = random.Random(170136)
with tempfile.TemporaryDirectory() as tmp:
lib = Path(tmp)/'half.so'
subprocess.run(['cc','-std=gnu11','-O3','-DP14_HALF_LIBRARY','-fPIC','-shared',
str(base/'half64.c'),'-o',str(lib)],check=True)
native = ctypes.CDLL(str(lib)).p14_halfcard_stop
native.argtypes = [ctypes.c_uint64,ctypes.c_uint64,ctypes.c_bool]
native.restype = ctypes.c_bool
# All layers in the certificate. The decision is monotone in positive x,
# so it is enough to check the first permissive integer and its predecessor.
for t in range(1,1048577):
z = isqrt(4*p.LO*p.LO*t//p.DEN**2)
x = max(1,(z+1)//2)
if (2*x+1)**2*p.DEN**2 < 4*p.LO*p.LO*t:
x += 1
assert (2*x+1)**2*p.DEN**2 > 4*p.HI*p.HI*t
assert native(t,x,False)
if x>1:
assert (2*x-1)**2*p.DEN**2 < 4*p.LO*p.LO*t
assert not native(t,x-1,False)
for t in [0,1,2,52,65536,65537,2**64-1]+[rng.randrange(2**64) for _ in range(2000)]:
m=isqrt(p.C64*t >> 64)
for z in list(range(max(0,m-4),min(t,m+4)+1))+[0,t]:
x=z+((z^t)&1)
if x>t:
continue
for hybrid in (False,True):
for score in (-x,x):
assert native(t,max(score,0),hybrid) == p.stop(t,score,hybrid)
# For arbitrary horizons compare generated targets at two extra precision levels.
for bits in (65,67,127,256,512):
t=2**(bits-1)+rng.randrange(2**(bits-2))
a,k=p.coefficient(t)
aa=p.squared_slope(k+32)
assert abs(aa-a*2**32)<4*2**32
m=isqrt(a*t>>k)
for x in range(max(0,m-5),m+6):
if (x^t)&1: continue
assert p.stop(t,x) == ((2*x+1)**2*2**k>=4*a*t)
for numer,central,cap in [(194547099,873941876893,F(9664681,10**9)),
(179780061,748318041695,F(7647297,10**9)),
(179735647,748318041695,F(7647297,10**9))]:
assert F(numer*central,10**9 * 2**44) < cap
print("Checked every cutoff-layer boundary, 64-bit and arbitrary-size player cases, and global cap products.")
~~~
#### `review/spectral_check.py`
~~~python
"""Recheck the spectral root, certified heat price intervals, and the optional OLS comparison.
Needs mpmath. Pass --heat /path/to/heat to regenerate each input interval with the
integer Bellman solver (the 10M-pair case visits 260,704,415,933 cells). To
recheck the actual Gwern fit, pass --observations bottomup-values0to22974.txt.
"""
import argparse
from fractions import Fraction
from math import comb, sqrt
from pathlib import Path
import re
import subprocess
import mpmath as mp
# Each fraction comes from the heat solver with truncation budget 1e-12.
INTERVALS = {
100: ("1348964916560388904/259861492806636994", "1348964916560576179/259861492806636993"),
1000: ("1356556498480170435/82267918283906708", "1356556498480254592/82267918283906707"),
10000: ("1357953889865839924/26018326910776644", "1357953889865903264/26018326910776643"),
100000: ("1358212693734799393/8227809956831982", "1358212693735096435/8227809956831981"),
1000000: ("1358260719377406661/2601864888956427", "1358260719379699598/2601864888956426"),
5000000: ("1358268294122938070/1163589468354244", "1358268294133588701/1163589468354243"),
10000000: ("1358269636195002935/822782013875311", "1358269636215922742/822782013875310"),
}
def evaluate_fraction(x):
r = Fraction(x)
return mp.mpf(r.numerator) / r.denominator
def regression(sizes, scores):
x = list(map(sqrt, sizes))
xm = sum(x) / len(x)
ym = sum(scores) / len(scores)
slope = sum((s-xm)*(v-ym) for s, v in zip(x, scores)) / sum((s-xm)**2 for s in x)
return ym - slope*xm, slope
def edge_test():
# Build the coefficient polynomial independently by convolution of the two
# fractional binomial series, and check the three required signs.
p = Fraction(46233337, 10**8)
for k in range(6, 45):
left, right = [Fraction(1)], [Fraction(1)]
for j in range(1, k+4):
left.append(-left[-1] * (p-j+1)/j)
right.append(right[-1] * (k-p-j+1)/j)
coeff = [sum(left[i]*right[m-i] for i in range(m+1)) for m in range(k+4)]
ratios = [value / comb(k, m) for m, value in enumerate(coeff[:k+1])]
assert all(b < a for a, b in zip(ratios, ratios[1:]))
assert all(value < 0 for value in coeff[k+1:])
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--heat", type=Path)
parser.add_argument("--observations", type=Path)
args = parser.parse_args()
mp.mp.dps = 50
alpha = mp.findroot(lambda y: (1-y*y)*mp.sqrt(mp.pi/2)*mp.exp(y*y/2)*mp.erfc(-y/mp.sqrt(2))-y,
(mp.mpf(".83"), mp.mpf(".85")))
p = mp.findroot(lambda z: mp.pcfd(z, -alpha), (mp.mpf(".45"), mp.mpf(".47")))
spectrum = lambda z: mp.quad(lambda u: u**z*mp.exp(-u*u/2)*mp.cos(alpha*u+z*mp.pi/2),
[0, 1, mp.inf])
assert abs(spectrum(p)) < mp.mpf("1e-45")
mu = p/2
K = (1-alpha**2)*mp.sqrt(mp.pi)
print("alpha =", mp.nstr(alpha, 36), "p* =", mp.nstr(p, 36), "mu =", mp.nstr(mu, 36))
edge_test()
for n, (lower, upper) in INTERVALS.items():
if args.heat:
row = subprocess.check_output([str(args.heat.resolve()), str(n), "1e-12"], text=True)
endpoints = re.search(r"interval=\[([\d/]+),([\d/]+)\]", row).groups()
assert endpoints == (lower, upper)
Q = (1-alpha**2)*mp.exp(n*mp.log(4)+2*mp.loggamma(n+1)-mp.loggamma(2*n+1))
low, high = [(Q-evaluate_fraction(x))*n**mu for x in (upper, lower)]
print(n, mp.nstr(low, 15), mp.nstr(high, 15))
n = 10000
pred = K*mp.sqrt(n)-mp.mpf(".102595")*n**(-mu)+K/(8*mp.sqrt(n))
print("10000-pair fitted value:", mp.nstr(pred, 18))
if args.observations:
data = list(map(float, args.observations.read_text().split()))
assert len(data) == 22975 and data[0] == 0
sizes = list(range(1,22975)) + [100000,133787000]
actual = data[1:] + [165.076, 6038.22]
fitted = [float(K)*sqrt(n)-.102595*n**(-float(mu))+float(K)/(8*sqrt(n)) for n in sizes]
print("actual / fitted OLS (intercept, slope):", regression(sizes, actual), regression(sizes, fitted))
if __name__ == "__main__":
main()
~~~
#### `review/spectral_pricing.tsv`
~~~text
pairs=26 lower=2.624475548993908 upper=2.6244755489939427 kernel_error=3.9139698426726711e-16 lower_hex=0x1.4feed0960a4d3p+1 upper_hex=0x1.4feed0960a521p+1
pairs=100 lower=5.191092000553243 upper=5.1910920005534891 kernel_error=6.2628938493625164e-16 lower_hex=0x1.4c3ad9f139d13p+2 upper_hex=0x1.4c3ad9f139e28p+2
pairs=300 lower=9.018086894484389 upper=9.0180868944854975 kernel_error=1.0753354315936465e-15 lower_hex=0x1.20942af7897e3p+3 upper_hex=0x1.20942af789a53p+3
pairs=1000 lower=16.48949586640127 upper=16.489495866407527 kernel_error=2.0356031313686907e-15 lower_hex=0x1.07d4f99e1b87cp+4 upper_hex=0x1.07d4f99e1bf5dp+4
pairs=3000 lower=28.578225084204575 upper=28.578225084236153 kernel_error=3.6105464414610644e-15 lower_hex=0x1.c94068f2262bp+4 upper_hex=0x1.c94068f228568p+4
pairs=10000 lower=52.192206459706589 upper=52.192206459894266 kernel_error=6.7229204605712015e-15 lower_hex=0x1.a189a38a54287p+5 upper_hex=0x1.a189a38a5a9b4p+5
pairs=30000 lower=90.410484150142735 upper=90.410484151104953 kernel_error=1.1767512045143396e-14 lower_hex=0x1.69a455f5018ecp+6 upper_hex=0x1.69a455f51216ap+6
pairs=100000 lower=165.07584652987446 upper=165.07584653568586 kernel_error=2.1581229919728885e-14 lower_hex=0x1.4a26d55b3aa6ep+7 upper_hex=0x1.4a26d55b6c924p+7
pairs=300000 lower=285.92637052976181 upper=285.92637055973672 kernel_error=3.7339876116542618e-14 lower_hex=0x1.1ded269e794e2p+8 upper_hex=0x1.1ded269efa0bep+8
pairs=1000000 lower=522.03353252755289 upper=522.03353270925152 kernel_error=6.8241456760466922e-14 lower_hex=0x1.05044acb3a989p+9 upper_hex=0x1.05044accc0ca7p+9
pairs=3000000 lower=904.1925508766385 upper=904.19255182724601 kernel_error=1.2006764294753299e-13 lower_hex=0x1.c418a581d2fd4p+9 upper_hex=0x1.c418a589cc674p+9
pairs=5000000 lower=1167.3088575325712 upper=1167.3088595785601 kernel_error=1.5509897246460724e-13 lower_hex=0x1.23d3c45262611p+10 upper_hex=0x1.23d3c45af73e3p+10
pairs=10000000 lower=1650.8256268740742 upper=1650.8256326403924 kernel_error=2.1864753730367898e-13 lower_hex=0x1.9cb4d71219b64p+10 upper_hex=0x1.9cb4d72a493fbp+10
~~~
#### `Excursions.lean`
~~~lean
import Problem14
/-! First-return acceleration, proved directly for the Bellman numerator.
The kernel below is an explicit difference of two ordinary binomial coefficients.
It also applies to sequences other than the optimal card-game value. -/
namespace Problem14.Excursions
/-- Pascal's array: choose (i+j) i. -/
def pascal : Nat → Nat → Int
| 0, _ => 1
| _+1, 0 => 1
| i+1, j+1 => pascal i (j+1) + pascal (i+1) j
theorem pascal_symm (i j : Nat) : pascal i j = pascal j i := by
induction i, j using pascal.induct with
| case1 j => cases j <;> simp [pascal]
| case2 i => simp [pascal]
| case3 i j h₁ h₂ => simp only [pascal, h₁, h₂, Int.add_comm]
/-- The Pascal array is exactly the number of equally likely deck words. -/
theorem weight_eq_pascal (r b : Nat) : (weight (deck r b) : Int) = pascal r b := by
have hw (s : State) (l t : Tree) : weight (.branch s l t) = weight l + weight t := by
simp [weight, paths]
induction r, b using deck.induct with
| case1 => simp [deck, weight, paths, pascal]
| case2 r ih => simp only [deck, hw, Int.natCast_add, ih]; cases r <;> simp [weight, paths, pascal]
| case3 b ih => simp only [deck, hw, Int.natCast_add, ih]; simp [weight, paths, pascal]
| case4 r b h₁ h₂ => simp only [deck, hw, Int.natCast_add, h₁, h₂, pascal]
/-- Number of prefixes from score -d first reaching 0 with j extra black draws.
At d=1 this is Catalan(j). -/
def kernel (d : Nat) : Nat → Int
| 0 => 1
| j+1 => pascal (j+1) (d+j) - pascal j (d+j+1)
theorem kernel_origin (j : Nat) : kernel 0 (j+1) = 0 := by
simp [kernel, pascal_symm (j+1) j]
theorem kernel_step (d j : Nat) :
kernel (d+1) (j+1) = kernel d (j+1) + kernel (d+2) j := by
cases j with
| zero => simp [kernel, pascal]; omega
| succ j =>
simp only [kernel]
have a : d+1+(j+1) = (d+(j+1))+1 := by omega
have b : d+2+j = d+(j+1)+1 := by omega
rw [a, b]
rw [pascal.eq_3 (j+1) (d+(j+1)), pascal.eq_3 j (d+(j+1)+1)]
omega
/-- Finite convolution sum k(j) f(b-j), j = 0,...,b. -/
def conv (k f : Nat → Int) : Nat → Int
| 0 => k 0 * f 0
| b+1 => k 0 * f (b+1) + conv (fun j => k (j+1)) f b
private theorem conv_add (p q f : Nat → Int) (b : Nat) :
conv (fun j => p j + q j) f b = conv p f b + conv q f b := by
induction b generalizing p q with
| zero => simp [conv, Int.add_mul]
| succ b ih =>
simp only [conv, Int.add_mul]
rw [ih (fun j => p (j+1)) (fun j => q (j+1))]
omega
private theorem conv_zero (f : Nat → Int) (b : Nat) :
conv (fun _ => 0) f b = 0 := by
induction b with
| zero => simp [conv]
| succ b ih => simpa [conv] using ih
private theorem conv_origin (f : Nat → Int) (b : Nat) :
conv (kernel 0) f b = f b := by
cases b with
| zero => simp [conv, kernel]
| succ b =>
simp only [conv, kernel_origin, conv_zero, Int.add_zero]
simp [kernel]
private theorem conv_step (d b : Nat) (f : Nat → Int) :
conv (kernel (d+1)) f (b+1) =
conv (kernel d) f (b+1) + conv (kernel (d+2)) f b := by
simp only [conv, kernel_step]
rw [conv_add (fun j => kernel d (j+1)) (kernel (d+2))]
simp [kernel, Int.add_assoc]
/-- A player can always play to exhaustion for the shifted terminal payoff R. -/
private theorem exhaustion_le (R : Nat) (t : Tree) :
R * weight t ≤ bellman R t := by
induction t with
| empty => simp [weight, paths, bellman]
| leaf => simp [weight, paths, bellman]
| branch s l r hl hr =>
apply Nat.le_trans _ (Nat.le_max_right _ _)
simpa only [weight, paths, List.length_map, List.length_append, Nat.mul_add]
using Nat.add_le_add hl hr
private theorem below (R : Nat) (s : State) (l r : Tree)
(h : reward R s ≤ R) :
bellman R (.branch s l r) = bellman R l + bellman R r := by
apply Nat.max_eq_right
calc
reward R s * (weight l + weight r) ≤ R * (weight l + weight r) :=
Nat.mul_le_mul_right _ h
_ = _ := Nat.mul_add ..
_ ≤ _ := Nat.add_le_add (exhaustion_le R l) (exhaustion_le R r)
/-- The terminal score summed over equiprobable decks, with the shift used
in Problem14.bellman removed. R is the original number of each color. -/
def mass (R r b : Nat) : Int :=
(bellman R (deck r b) : Int) - R * (weight (deck r b) : Int)
private theorem mass_draw (R : Nat) (s : State) (l r : Tree)
(h : reward R s ≤ R) :
(bellman R (.branch s l r) : Int) - R * (weight (.branch s l r) : Int) =
((bellman R l : Int) - R * (weight l : Int)) +
((bellman R r : Int) - R * (weight r : Int)) := by
rw [below R s l r h]
have hw : weight (.branch s l r) = weight l + weight r := by
simp [weight, paths]
rw [hw]
simp only [Int.natCast_add, Int.mul_add]
omega
/-- Every negative-score state's aggregate payoff is a finite binomial sum
over the diagonal. b+d ≤ R guarantees reachability in the original deck. -/
theorem collapse (R d b : Nat) (h : b+d ≤ R) :
mass R (b+d) b = conv (kernel d) (fun j => mass R j j) b := by
induction b generalizing d with
| zero =>
simp only [Nat.zero_add] at *
induction d with
| zero => simp [conv, kernel]
| succ d ih =>
have step : mass R (d+1) 0 = mass R d 0 := by
simp only [mass, deck]
rw [mass_draw]
· simp [bellman, weight, paths]
· simp [reward]
rw [step, ih (by omega)]
rfl
| succ b ih =>
induction d with
| zero => simp [conv_origin]
| succ d hd =>
have step : mass R (b+1+(d+1)) (b+1) =
mass R (b+1+d) (b+1) + mass R (b+(d+2)) b := by
have he : b+1+(d+1) = (b+1+d)+1 := by omega
have he' : b+(d+2) = b+1+d+1 := by omega
rw [he, he']
simp only [mass, deck]
apply mass_draw
simp only [reward]; omega
rw [step, hd (by omega), ih (d+2) (by omega), conv_step]
/-- The Catalan convolution used by the exact solver's diagonal update. -/
theorem negative_neighbor (R b : Nat) (hb : b+1 ≤ R) :
mass R (b+1) b = conv (kernel 1) (fun j => mass R j j) b :=
collapse R 1 b hb
end Problem14.Excursions
~~~
#### `FactorialPowers.lean`
~~~lean
import Std
/-!
Ordinary factorial and Euclidean quotient express every natural power, with
no variable-length sum/product in the resulting expression. The auxiliary
finite products below occur only in its proof.
Run with Lean 4.19.0: lean FactorialPowers.lean
-/
namespace Problem14.FactorialPowers
def fac : Nat → Nat
| 0 => 1
| n+1 => (n+1)*fac n
def two (x : Nat) : Nat :=
let k := fac (2*x+4)
fac (2*k) * fac (k-x) / (fac (2*k-x) * fac k)
def power (a b : Nat) : Nat :=
let h := (a+1)*(b+1)
let z := two (h*b)
let m := two h - a
z - m*(z/m)
private theorem fac_pos (n : Nat) : 0 < fac n := by
induction n with
| zero => decide
| succ n ih => exact Nat.mul_pos (by omega) ih
private def fall (k : Nat) : Nat → Nat
| 0 => 1
| i+1 => (k-i)*fall k i
private theorem fall_fac (k i : Nat) (hi : i ≤ k) :
fall k i * fac (k-i) = fac k := by
induction i with
| zero => simp [fall]
| succ i ih =>
have hj : k-i = (k-(i+1))+1 := by omega
calc
fall k (i+1) * fac (k-(i+1)) = fall k i*((k-i)*fac (k-(i+1))) := by
rw [fall]; ac_rfl
_ = fall k i*fac (k-i) := by
have hf : fac (k-i) = (k-i)*fac (k-(i+1)) := calc
_ = fac ((k-(i+1))+1) := congrArg fac hj
_ = _ := by rw [fac,←hj]
rw [hf]
_ = fac k := ih (by omega)
private theorem fall_pos (k i : Nat) (hi : i ≤ k) : 0 < fall k i := by
induction i with
| zero => simp [fall]
| succ i ih => exact Nat.mul_pos (by omega) (ih (by omega))
private def err (k : Nat) : Nat → Nat
| 0 => 0
| i+1 => (2*k-i)*err k i + (i*2^i)*fall k i
private theorem expansion (k i : Nat) (hi : i ≤ k) :
fall (2*k) i = 2^i*fall k i + err k i := by
induction i with
| zero => simp [fall,err]
| succ i ih =>
have he : 2*k-i = 2*(k-i)+i := by omega
rw [fall,ih (by omega),err,fall,Nat.pow_succ,Nat.mul_add]
rw [he]
simp only [Nat.mul_add,Nat.add_mul]
ac_rfl
private theorem err_bound (k x : Nat) (hk : 2*x ≤ k) (i : Nat) (hi : i ≤ x) :
err k i*(k-x) ≤ (4^i*x)*fall k i := by
induction i with
| zero => simp [err]
| succ i ih =>
let d := k-i
let e := err k i
let q := fall k i
let c := 4^i*x
have h0 : e*(k-x) ≤ c*q := ih (by omega)
have h1 : 2*k-i ≤ 3*d := by dsimp [d]; omega
have t1 := Nat.mul_le_mul h1 h0
have coeff : i*2^i ≤ c := by
dsimp [c]
rw [Nat.mul_comm]
exact Nat.mul_le_mul (Nat.pow_le_pow_left (by decide : 2 ≤ 4) i) (by omega)
have h2 : k-x ≤ d := by dsimp [d]; omega
have t2 := Nat.mul_le_mul (Nat.mul_le_mul_right q coeff) h2
change ((2*k-i)*e + i*2^i*q)*(k-x) ≤ 4^(i+1)*x*(d*q)
rw [Nat.add_mul,Nat.pow_succ]
calc
(2*k-i)*e*(k-x) + i*2^i*q*(k-x)
≤ 3*d*(c*q) + (c*q)*d := by
apply Nat.add_le_add _ t2
simpa only [Nat.mul_assoc] using t1
_ = 4^i*4*x*(d*q) := by
change 3*d*((4^i*x)*q) + ((4^i*x)*q)*d = _
have he : 4^i*4*x*(d*q) = ((4^i*x)*q)*d*4 := by ac_rfl
rw [he]
have hf : 3*d*(4^i*x*q) = ((4^i*x)*q)*d*3 := by ac_rfl
rw [hf]
omega
/- Each increment of x introduces two new factorial factors, whose product
is at least 16. This elementary bound leaves ample space for the error. -/
private theorem large_fac (x : Nat) : 4^x*(x+1)*2 ≤ fac (2*x+4) := by
induction x with
| zero => decide
| succ x ih =>
have he : 2*(x+1)+4 = (2*x+4)+1+1 := by omega
rw [he,fac,fac,Nat.pow_succ]
have ha : x+1+1 ≤ (x+1)*2 := by omega
have hh := Nat.mul_le_mul_left (4^x*4) ha
calc
4^x*4*(x+1+1)*2 ≤ 4^x*4*((x+1)*2)*2 := Nat.mul_le_mul_right 2 hh
_ = 8*(4^x*(x+1)*2) := by
change _ = (4*2)*(4^x*(x+1)*2); ac_rfl
_ ≤ 8*fac (2*x+4) := Nat.mul_le_mul_left 8 ih
_ ≤ ((2*x+4+1+1)*(2*x+4+1))*fac (2*x+4) := by
apply Nat.mul_le_mul_right
have := Nat.mul_le_mul (by omega : 2 ≤ 2*x+4+1+1) (by omega : 4 ≤ 2*x+4+1)
exact this
_ = _ := Nat.mul_assoc _ _ _
private theorem above_error (x : Nat) : 4^x*x+x < fac (2*x+4) := by
have h := large_fac x
rw [Nat.mul_succ (4^x) x] at h
have hp := Nat.pow_pos (n:=x) (by decide : 0 < 4)
have h2 : x ≤ 4^x*x := Nat.le_mul_of_pos_left x hp
omega
theorem two_eq (x : Nat) : two x = 2^x := by
let k := fac (2*x+4)
have he : 4^x*x+x < k := above_error x
have hp := Nat.pow_pos (n:=x) (by decide : 0 < 4)
have hx : x ≤ 4^x*x := Nat.le_mul_of_pos_left x hp
have h1 := err_bound k x (by omega) x (by omega)
have h2 := Nat.mul_lt_mul_of_pos_right (by omega : 4^x*x < k-x) (fall_pos k x (by omega))
have h3 : err k x < fall k x := by
have hh := Nat.lt_of_le_of_lt h1 h2
rw [Nat.mul_comm (k-x)] at hh
exact Nat.lt_of_mul_lt_mul_right hh
have low : 2^x*fall k x ≤ fall (2*k) x := by rw [expansion k x (by omega)]; omega
have high : fall (2*k) x < (2^x+1)*fall k x := by
rw [expansion k x (by omega),Nat.succ_mul]; omega
unfold two
change fac (2*k)*fac (k-x)/(fac (2*k-x)*fac k) = 2^x
have hnum := fall_fac (2*k) x (by omega)
have hden := fall_fac k x (by omega)
let scale := fac (2*k-x)*fac (k-x)
have hsc : 0 < scale := Nat.mul_pos (fac_pos _) (fac_pos _)
have num : fac (2*k)*fac (k-x) = fall (2*k) x*scale := by
rw [←hnum]; dsimp [scale]; ac_rfl
have den : fac (2*k-x)*fac k = fall k x*scale := by
rw [←hden]; dsimp [scale]; ac_rfl
rw [num,den]
apply Nat.div_eq_of_lt_le
· simpa only [Nat.mul_assoc] using Nat.mul_le_mul_right scale low
· simpa only [Nat.mul_assoc] using Nat.mul_lt_mul_of_pos_right high hsc
private theorem pow_congr_mod (a z m b : Nat) (h : a%m = z%m) :
a^b%m = z^b%m := by
induction b with
| zero => rfl
| succ b ih =>
rw [Nat.pow_succ,Nat.pow_succ,Nat.mul_mod,Nat.mul_mod (z^b)]
rw [ih,h]
theorem pow_via_two (a b : Nat) :
let h := (a+1)*(b+1)
2^(h*b) % (2^h-a) = a^b := by
dsimp only
let c := 2^(a+1)
have hc : a+1 < c := Nat.lt_two_pow_self
have hp : 0 < c^b := Nat.pow_pos (by omega)
have hpow : a^b ≤ c^b := Nat.pow_le_pow_left (by omega) b
have hlo : (a+2)*c^b ≤ c*c^b := Nat.mul_le_mul_right _ (by omega)
have hrest : a+1 ≤ (a+1)*c^b := Nat.le_mul_of_pos_right _ hp
rw [Nat.succ_mul] at hlo
have hlarge : a^b+a < 2^((a+1)*(b+1)) := by
rw [Nat.pow_mul,Nat.pow_succ,Nat.mul_comm]
change a^b+a < c*c^b
omega
let m := 2^((a+1)*(b+1))-a
have he : 2^((a+1)*(b+1)) = a+m := by dsimp [m]; omega
have hm : 2^((a+1)*(b+1))%m = a%m := by rw [he,Nat.add_mod_right]
change 2^(((a+1)*(b+1))*b)%m = a^b
rw [Nat.pow_mul, pow_congr_mod _ _ m b hm, Nat.mod_eq_of_lt (by dsimp [m]; omega)]
theorem power_eq (a b : Nat) : power a b = a^b := by
unfold power
simp only [two_eq]
rw [Nat.mul_comm (2^((a+1)*(b+1))-a), ← Nat.mod_eq_sub_div_mul]
exact pow_via_two a b
end Problem14.FactorialPowers
~~~
#### `FrontierExtension.lean`
~~~lean
import Std
/-! An integer Pascal array that agrees with a stopped game on and below its
diagonal agrees through the first stopping state of every row. The hypotheses
use unnormalized sums over equiprobable color strings. -/
namespace Problem14.FrontierExtension
/-- Rows are indexed by red cards, columns by black cards. The row threshold is
the first stopping column (ties may stop). The theorem also works on a tail of
rows, which is useful when the diagonal data are known only eventually. -/
theorem through_first_stop
(game extension : Nat → Nat → Int) (threshold : Nat → Nat) (start : Nat)
(grows : ∀ r ≥ start, threshold r < threshold (r+1))
(negative : ∀ r ≥ start, ∀ b ≤ r, game r b = extension r b)
(draw : ∀ r ≥ start, ∀ k, k+1 < threshold (r+1) →
game (r+1) (k+1) = game r (k+1) + game (r+1) k)
(pascal : ∀ r k, extension (r+1) (k+1) =
extension r (k+1) + extension (r+1) k)
(r b : Nat) (hr : start ≤ r) (hb : b ≤ threshold r) :
game r b = extension r b := by
by_cases lower : b ≤ r
· exact negative r hr b lower
· cases b with
| zero => omega
| succ k =>
have inside : k+1 < threshold (r+1) := Nat.lt_of_le_of_lt hb (grows r hr)
have parent := through_first_stop game extension threshold start grows negative
draw pascal (r+1) (k+1) (by omega) (by omega)
have sibling := through_first_stop game extension threshold start grows negative
draw pascal (r+1) k (by omega) (by omega)
have a := draw r hr k inside
have h := pascal r k
omega
termination_by b-r
decreasing_by all_goals omega
#print axioms through_first_stop
end Problem14.FrontierExtension
~~~
#### `Plateau.lean`
~~~lean
import Std
/-! The algebraic contradiction at the end of the hypergeometric obstruction.
This module is standalone and uses Lean 4.19.0's standard library. -/
namespace Problem14.Plateau
/-- Integer-valued little-o(r), suitable for a nonnegative frontier. -/
def Sublinear (f : Nat → Nat) :=
∀ c : Nat, ∃ N, ∀ r ≥ N, c * f r ≤ r
/-- Beyond any starting index and height there is a run of any prescribed
length. Endpoints are included. -/
theorem long_runs (f : Nat → Nat) (mon : ∀ i j, i ≤ j → f i ≤ f j)
(unb : ∀ J, ∃ i, J ≤ f i) (sub : Sublinear f) (I J d : Nat) :
∃ a, I ≤ a ∧ J ≤ f a ∧ ∀ j ≤ d, f (a+j) = f a := by
obtain ⟨i,hi⟩ := unb J
let o := max i I
have at_o : J ≤ f o := Nat.le_trans hi (mon _ _ (Nat.le_max_left _ _))
have io : I ≤ o := Nat.le_max_right _ _
apply Classical.byContradiction
intro hn
let L := d+1
have pos : 0 < L := Nat.zero_lt_succ _
have advance (r : Nat) (hr : o ≤ r) : f r < f (r+L) := by
apply Classical.byContradiction
intro h
apply hn
refine ⟨r, by omega, Nat.le_trans at_o (mon _ _ hr), ?_⟩
intro j hj
have a := mon r (r+j) (by omega)
have b := mon (r+j) (r+L) (by dsimp [L]; omega)
omega
have ramp (k : Nat) : k ≤ f (o+L*k) := by
induction k with
| zero => omega
| succ k ih =>
rw [Nat.mul_succ,←Nat.add_assoc]
have h := advance (o+L*k) (by omega)
exact Nat.lt_of_le_of_lt ih h
obtain ⟨N,hN⟩ := sub (L+L)
let k := N+o+1
have hk : k ≤ L*k := Nat.le_mul_of_pos_left k pos
have hbig : N ≤ o+L*k := by dsimp [k] at *; omega
have hhi := hN _ hbig
have hlo := Nat.mul_le_mul_left (L+L) (ramp k)
rw [Nat.add_mul] at hlo
dsimp only [k] at hk hlo hhi
omega
private def poly (p : List Int) (x : Int) : Int :=
p.foldr (fun a z => a + x*z) 0
private def quot (y : Int) : List Int → List Int
| [] => []
| _::p => match p with
| [] => []
| a::as => poly (a::as) y :: quot y (a::as)
private theorem quot_len (y : Int) (p : List Int) :
(quot y p).length = p.length - 1 := by
induction p with
| nil => rfl
| cons a p ih =>
cases p with
| nil => rfl
| cons b bs => simp only [quot,List.length_cons] at *; omega
private theorem poly_quot (x y : Int) (p : List Int) :
poly p x - poly p y = (x-y)*poly (quot y p) x := by
induction p with
| nil => simp [poly,quot]
| cons a p ih =>
cases p with
| nil => simp [poly,quot]
| cons b bs =>
change a+x*poly (b::bs) x - (a+y*poly (b::bs) y) =
(x-y)*(poly (b::bs) y+x*poly (quot y (b::bs)) x)
rw [Int.mul_add,Int.mul_left_comm (x-y) x,← ih,Int.mul_sub,Int.sub_mul]
omega
private theorem many_roots (p : List Int) (v : Nat → Int)
(inj : ∀ i j, v i = v j → i = j)
(hz : ∀ j < p.length, poly p (v j) = 0) : ∀ x, poly p x = 0 := by
by_cases h : p.length = 0
· have he := List.length_eq_zero_iff.mp h
subst p
simp [poly]
· let q := quot (v 0) p
have hl : q.length = p.length-1 := quot_len _ _
have base := hz 0 (by omega)
have step (j : Nat) (hj : j < q.length) : poly q (v (j+1)) = 0 := by
have e := poly_quot (v (j+1)) (v 0) p
change _ = _ * poly q _ at e
rw [base, hz _ (by omega)] at e
have ne : v (j+1)-v 0 ≠ 0 := by
intro e
have := inj (j+1) 0 (by omega)
omega
exact (Int.mul_eq_zero.mp (by simpa using e.symm)).resolve_left ne
have vanish := many_roots q (fun j => v (j+1))
(fun i j eq => by have := inj (i+1) (j+1) eq; omega) step
intro x
have e := poly_quot x (v 0) p
change _ = _*poly q x at e
rw [base,vanish] at e
omega
termination_by p.length
decreasing_by
rw [quot_len]
omega
/-- Coefficients are in ascending degree in t, then ascending degree in x. -/
def eval (p : List (List Int)) (t x : Int) : Int :=
poly (p.map (fun row => poly row x)) t
private theorem congruent (p : List (List Int)) (t x y : Int) :
(x-y) ∣ eval p t x - eval p t y := by
induction p with
| nil => simp [eval,poly]
| cons q p ih =>
obtain ⟨a,ha⟩ := ih
refine ⟨poly (quot y q) x + t*a, ?_⟩
change poly q x + t*eval p t x - (poly q y + t*eval p t y) = _
rw [Int.mul_add,Int.mul_left_comm (x-y) t,←ha,← poly_quot,Int.mul_sub]
omega
/-- Any rational polynomial can have denominators cleared to give this
integer-coefficient form. Zeros at all sufficiently late adjacent equal
frontier heights force the entire bivariate polynomial function to be zero. -/
theorem frontier_vanishing (p : List (List Int)) (f : Nat → Nat) (I : Nat)
(mon : ∀ i j, i ≤ j → f i ≤ f j)
(unb : ∀ J, ∃ i, J ≤ f i) (sub : Sublinear f)
(h : ∀ r ≥ I, f (r+1) = f r → eval p (2*r+f r : Nat) (f r) = 0) :
∀ t x : Int, eval p t x = 0 := by
have row (J : Nat) : ∃ j : Nat, J ≤ j ∧ ∀ t, eval p t j = 0 := by
obtain ⟨a,ha,hJ,run⟩ := long_runs f mon unb sub I J p.length
refine ⟨f a,hJ,?_⟩
apply many_roots _ (fun i => (2*(a+i)+f a : Nat))
· intro i j eq
omega
· intro i hi
simp only [List.length_map] at hi
have h0 := run i (by omega)
have h1 := run (i+1) (by omega)
have he := h (a+i) (by omega) (by rw [Nat.add_assoc,h1,h0])
simpa [eval,h0] using he
intro t x
let v := eval p t x
obtain ⟨j,hj,hrow⟩ := row (v.natAbs+x.natAbs+2)
have hd := congruent p t j x
rw [hrow] at hd
change (↑j - x) ∣ 0-v at hd
have hne : v = 0 := by
apply Classical.byContradiction
intro hn
have hd' := Int.natAbs_dvd_natAbs.mpr hd
have hm : (0-v).natAbs = v.natAbs := by simp
rw [hm] at hd'
have hle := Nat.le_of_dvd (Int.natAbs_pos.mpr hn) hd'
omega
exact hne
end Problem14.Plateau
~~~
#### `PlayerRule52.lean`
~~~lean
import Problem14
/-! An exact playing rule for a standard red/black deck.
With score x and t cards remaining, stop when x>0 and 3t≤x(4x+5).
The executable certificate checks both possible decisions against the
original Bellman numerator. All finite checks use Lean kernel reduction. -/
namespace Problem14.PlayerRule52
def stop (s : State) : Bool :=
let x := s.2-s.1
decide (s.1 (List.range (B+1)).all fun b =>
decide (action (tab R B) R r b = (tab R B r b).2)
private theorem tab_action (R B r b : Nat) (hb : b≤B) :
action (tab R B) R r b = action (model R) R r b := by
unfold action tab
rw [table_eq _ _ _ _ hb,table_eq _ _ _ _ hb,table_eq _ _ _ _ (by omega : b-1≤B)]
private theorem verified_action {R B : Nat} (ok : verify R B=true)
{r b : Nat} (hr : r≤R) (hb : b≤B) :
action (model R) R r b = bellman R (deck r b) := by
have h := List.all_eq_true.mp (List.all_eq_true.mp ok r
(List.mem_range.mpr (by omega))) b (List.mem_range.mpr (by omega))
have h' : action (tab R B) R r b = (tab R B r b).2 := of_decide_eq_true h
rw [tab_action _ _ _ _ hb] at h'
simpa only [tab, table_eq _ _ _ _ hb, model] using h'
set_option maxRecDepth 200000
set_option maxHeartbeats 0
private theorem standard_checked : verify 26 26=true := by decide +kernel
/-- Each of the 27×27 states independently attains the best first action. -/
theorem standard_action {r b : Nat} (hr : r≤26) (hb : b≤26) :
action (model 26) 26 r b = bellman 26 (deck r b) :=
verified_action standard_checked hr hb
private theorem policy_attains (R B : Nat) (ok : verify R B=true)
(r b : Nat) (hr : r≤R) (hb : b≤B) :
score R stop (deck r b) = bellman R (deck r b) := by
have choose {u v : Nat} (hu : u≤R) (hv : v≤B) := verified_action ok hu hv
induction r, b using deck.induct with
| case1 => simp [score,deck,paths,firstPay,bellman]
| case2 r ih =>
rw [←choose hr hb,deck.eq_2,score_branch,ih (by omega) hb]
simp [action,model,deck.eq_2,weight,paths,score]
| case3 b ih =>
rw [←choose hr hb,deck.eq_3,score_branch,ih hr (by omega)]
simp [action,model,deck.eq_3,weight,paths,score]
| case4 r b h₁ h₂ =>
rw [←choose hr hb,deck.eq_4,score_branch]
simp [action,model,deck.eq_4,weight,paths,h₁ (by omega) hb,h₂ hr (by omega)]
theorem standard_play {r b : Nat} (hr : r≤26) (hb : b≤26) :
score 26 stop (deck r b) = bellman 26 (deck r b) :=
policy_attains _ _ standard_checked _ _ hr hb
/-- Exact standard-deck expectation, with the constant shift removed. -/
theorem printed_rule_payoff :
(score 26 stop (deck 26 26) - 26*weight (deck 26 26))*15997372030584 =
41984711742427*weight (deck 26 26) := by
rw [standard_play (by decide) (by decide), ←closedNumerator_eq_bellman]
exact payoff52
/-- With 36 red and 43 black cards left, the rule draws. Stopping gains
the displayed numerator over drawing once and playing optimally thereafter. -/
theorem counterexample :
stop (36,43)=false ∧
action (model 43) 43 36 43 + 41671141584296606399 =
reward 43 (36,43)*weight (deck 36 43) := by
constructor
· decide
· change _ = _*(model 43 36 43).1
rw [←tab_action 43 43 36 43 (by decide),←table_eq 43 43 36 43 (by decide)]
decide +kernel
end Problem14.PlayerRule52
~~~
#### `PreviewRecall.lean`
~~~lean
import Std
/-! Finite-horizon preview and recall have the same feasible selected-time
rules, path by path. A path may belong to any specified family of legal
trajectories. Observations are indexed from zero: at time t exactly indices
0,...,t−1 have been revealed. Choices are permitted at times 0,...,N. -/
namespace Problem14.PreviewRecall
universe u v w e f
variable {Path : Type u} {Observation : Type v}
def SamePrefix (observe : Path → Nat → Observation) (t : Nat) (x y : Path) : Prop :=
∀ i, i h i (Nat.lt_of_lt_of_le hi le)
/-- A discrete stopping time: every path indistinguishable when x stops must
stop at the same time. This is measurability of each event {stop = t}. -/
structure Stopping (observe : Path → Nat → Observation) (N : Nat)
(stop : Path → Nat) : Prop where
bounded : ∀ x, stop x≤N
adapted : ∀ x y, SamePrefix observe (stop x) x y → stop y=stop x
/-- A decision at t may inspect the next k observations, truncated at N. -/
structure Preview (observe : Path → Nat → Observation) (N k : Nat)
(choose : Path → Nat) : Prop where
bounded : ∀ x, choose x≤N
adapted : ∀ x y, SamePrefix observe (min N (choose x+k)) x y → choose y=choose x
/-- At an ordinary stopping time, select any time at most k steps back.
Selection is measurable at commitment: among paths committing at the same
time with the same observations, it must agree. -/
structure Recall (observe : Path → Nat → Observation) (N k : Nat)
(choose : Path → Nat) where
commit : Path → Nat
stopping : Stopping observe N commit
window : ∀ x, commit x-k≤choose x ∧ choose x≤commit x
selected : ∀ x y, commit y=commit x → SamePrefix observe (commit x) x y →
choose y=choose x
variable {observe : Path → Nat → Observation} {N k : Nat} {choose : Path → Nat}
/-- A preview choice can be committed to at its last legal recall time. -/
def Preview.toRecall (p : Preview observe N k choose) : Recall observe N k choose where
commit x := min N (choose x+k)
stopping := {
bounded := fun _ => Nat.min_le_left _ _
adapted := fun x y h => congrArg (fun t => min N (t+k)) (p.adapted x y h) }
window x := ⟨Nat.sub_le_iff_le_add.mpr (Nat.min_le_right _ _),
Nat.le_min.mpr ⟨p.bounded x, Nat.le_add_right _ _⟩⟩
selected x y _ h := p.adapted x y h
/-- The preview window already discloses every observation the recall
policy used to select this time, even when the window reaches the horizon. -/
theorem Recall.toPreview (p : Recall observe N k choose) : Preview observe N k choose where
bounded x := Nat.le_trans (p.window x).2 (p.stopping.bounded x)
adapted := by
intro x y visible
have deadline := p.stopping.bounded x
have fresh := Nat.sub_le_iff_le_add.mp (p.window x).1
have atCommit : SamePrefix observe (p.commit x) x y :=
shorter visible (Nat.le_min.mpr ⟨deadline, fresh⟩)
exact p.selected x y (p.stopping.adapted x y atCommit) atCommit
theorem same_chosen_times :
Preview observe N k choose ↔ Nonempty (Recall observe N k choose) :=
⟨fun p => ⟨p.toRecall⟩, fun ⟨p⟩ => p.toPreview⟩
/-- A score can depend on the entire path and the chosen time. Evaluation
can be expectation under any fixed path distribution. -/
def attainable {Score : Type w} {Result : Type e} (feasible : (Path → Nat) → Prop)
(score : Path → Nat → Score) (evaluate : (Path → Score) → Result)
(value : Result) : Prop :=
∃ choose, feasible choose ∧ evaluate (fun x => score x (choose x)) = value
theorem same_attainable_values {Score : Type w} {Result : Type e}
(score : Path → Nat → Score) (evaluate : (Path → Score) → Result) :
attainable (Preview observe N k) score evaluate =
attainable (fun choose => Nonempty (Recall observe N k choose)) score evaluate := by
funext value
apply propext
constructor
· rintro ⟨j,p,v⟩
exact ⟨j,same_chosen_times.mp p,v⟩
· rintro ⟨j,p,v⟩
exact ⟨j,same_chosen_times.mpr p,v⟩
/-- In particular the optimized expected payoff agrees whenever optimization
is defined as a maximum or supremum of the attainable values. -/
theorem same_optimum {Score : Type w} {Result : Type e} {Optimum : Type f}
(score : Path → Nat → Score) (evaluate : (Path → Score) → Result)
(optimize : (Result → Prop) → Optimum) :
optimize (attainable (Preview observe N k) score evaluate) =
optimize (attainable (fun choose => Nonempty (Recall observe N k choose)) score evaluate) :=
congrArg optimize (same_attainable_values score evaluate)
#print axioms same_chosen_times
#print axioms same_optimum
end Problem14.PreviewRecall
~~~
#### `Problem14.lean`
~~~lean
import Std
/-!
Problem 14. Run with Lean 4.19.0: lean Problem14.lean.
All arithmetic is integral. With R original reds and B original blacks, the
shifted payoff at remaining state (r,b) is R-r+b, i.e. actual payoff plus B.
Every complete colour word has equal probability. A stopping set is any subset
of the rectangle of remaining counts. Its score is the sum, over the complete
words, of the shifted payoff at the first visited stopping state (R at exhaustion).
-/
namespace Problem14
abbrev State := Nat × Nat
abbrev Rule := State → Bool
inductive Tree where
| empty
| leaf
| branch (s : State) (red black : Tree)
def deck : Nat → Nat → Tree
| 0, 0 => .leaf
| r+1, 0 => .branch (r+1, 0) (deck r 0) .empty
| 0, b+1 => .branch (0, b+1) .empty (deck 0 b)
| r+1, b+1 => .branch (r+1, b+1) (deck r (b+1)) (deck (r+1) b)
def paths : Tree → List (List State)
| .empty => []
| .leaf => [[]]
| .branch s l r => (paths l ++ paths r).map (s :: ·)
def weight (t : Tree) := (paths t).length
def reward (R : Nat) (s : State) := R - s.1 + s.2
def firstPay (R : Nat) (q : Rule) : List State → Nat
| [] => R
| s :: ss => if q s then reward R s else firstPay R q ss
def score (R : Nat) (q : Rule) (t : Tree) :=
((paths t).map (firstPay R q)).sum
def bellman (R : Nat) : Tree → Nat
| .empty => 0
| .leaf => R
| .branch s l r =>
max (reward R s * (weight l + weight r)) (bellman R l + bellman R r)
private theorem const_sum {α : Type} (xs : List α) (c : Nat) :
(xs.map (fun _ => c)).sum = c * xs.length := by
induction xs with
| nil => simp
| cons a xs ih => simp [ih, Nat.mul_succ, Nat.add_comm]
private theorem sum_append (xs ys : List Nat) : (xs ++ ys).sum = xs.sum + ys.sum := by
induction xs with
| nil => simp
| cons _ xs ih => simp [ih, Nat.add_assoc]
theorem score_branch (R : Nat) (q : Rule) (s : State) (l r : Tree) :
score R q (.branch s l r) =
if q s then reward R s * (weight l + weight r)
else score R q l + score R q r := by
cases h : q s <;>
simp [score, paths, List.map_map, Function.comp_def, firstPay, h, weight,
const_sum, List.map_append, sum_append, Nat.mul_add]
theorem score_le_bellman (R : Nat) (q : Rule) (t : Tree) :
score R q t ≤ bellman R t := by
induction t with
| empty => simp [score, paths, bellman]
| leaf => simp [score, paths, firstPay, bellman]
| branch s l r hl hr =>
rw [score_branch]
simp only [bellman]
split <;> omega
def grid (R B : Nat) : List State :=
(List.range (R+1)).flatMap fun r => (List.range (B+1)).map fun b => (r,b)
private theorem in_grid {r b R B : Nat} (hr : r ≤ R) (hb : b ≤ B) :
(r,b) ∈ grid R B := by
simp [grid, List.mem_flatMap, List.mem_map]
omega
def subsets {α : Type} : List α → List (List α)
| [] => [[]]
| x :: xs => subsets xs ++ (subsets xs).map (x :: ·)
private theorem filter_in_subsets {α : Type} (f : α → Bool) (xs : List α) :
xs.filter f ∈ subsets xs := by
induction xs with
| nil => simp [subsets]
| cons x xs ih => cases h : f x <;> simp [subsets, List.filter_cons, h, ih]
def greedy (R : Nat) (s : State) : Bool :=
decide (bellman R (deck s.1 s.2) = reward R s * weight (deck s.1 s.2))
private theorem choose_at (R : Nat) (q : Rule) (s : State) (l r : Tree)
(hl : score R q l = bellman R l) (hr : score R q r = bellman R r)
(hs : q s = decide (bellman R (.branch s l r) =
reward R s * weight (.branch s l r))) :
score R q (.branch s l r) = bellman R (.branch s l r) := by
rw [score_branch, hs, hl, hr]
simp only [bellman, weight, paths, List.length_map, List.length_append]
split <;> simp_all <;> omega
private theorem greedy_attains (R B : Nat) (q : Rule)
(hq : ∀ s ∈ grid R B, q s = greedy R s) (r b : Nat)
(hr : r ≤ R) (hb : b ≤ B) : score R q (deck r b) = bellman R (deck r b) := by
induction r, b using deck.induct with
| case1 => simp [deck, score, paths, firstPay, bellman]
| case2 r ih =>
rw [deck]
apply choose_at
· exact ih (by omega) hb
· rfl
· simpa only [greedy, deck] using hq _ (in_grid hr hb)
| case3 b ih =>
rw [deck]
apply choose_at
· rfl
· exact ih hr (by omega)
· simpa only [greedy, deck] using hq _ (in_grid hr hb)
| case4 r b ihl ihr =>
rw [deck]
apply choose_at
· exact ihl (by omega) hb
· exact ihr hr (by omega)
· simpa only [greedy, deck] using hq _ (in_grid hr hb)
def scores (R B : Nat) : List Nat :=
(subsets (grid R B)).map fun stops =>
score R (fun s => decide (s ∈ stops)) (deck R B)
theorem optimal_in_scores (R B : Nat) : bellman R (deck R B) ∈ scores R B := by
apply List.mem_map.mpr
refine ⟨(grid R B).filter (greedy R), filter_in_subsets _ _, ?_⟩
apply greedy_attains R B _ _ R B (by omega) (by omega)
intro s hs
cases h : greedy R s <;> simp [List.mem_filter, hs, h]
theorem scores_bounded (R B x : Nat) (hx : x ∈ scores R B) :
x ≤ bellman R (deck R B) := by
obtain ⟨stops, _, rfl⟩ := List.mem_map.mp hx
apply score_le_bellman
private theorem subsets_length {α : Type} (xs : List α) :
(subsets xs).length = 2 ^ xs.length := by
induction xs with
| nil => simp [subsets]
| cons x xs ih => simp [subsets, ih, Nat.pow_succ]; omega
private theorem grid_length (R B : Nat) :
(grid R B).length = (R+1) * (B+1) := by
unfold grid
generalize h : List.range (R+1) = xs
have hx : xs.length = R+1 := by rw [← h]; simp
rw [← hx]
clear h hx
induction xs with
| nil => simp
| cons x xs ih => simp [List.flatMap_cons, ih, Nat.succ_mul, Nat.add_comm]
private theorem mem_le_sum (a : Nat) (xs : List Nat) (ha : a ∈ xs) :
a ≤ xs.sum := by
induction xs with
| nil => simp at ha
| cons x xs ih =>
simp at ha
simp only [List.sum_cons]
rcases ha with rfl | h
· omega
· have := ih h; omega
private theorem sum_bound (xs : List Nat) (n : Nat) (hb : ∀ x ∈ xs, x ≤ n) :
xs.sum ≤ xs.length * n := by
induction xs with
| nil => simp
| cons x xs ih =>
have ha := hb x (by simp)
have ht := ih (fun y hy => hb y (by simp [hy]))
simp only [List.sum_cons, List.length_cons, Nat.succ_mul]
omega
/-- With k bits per unit of payoff and fewer than 2^k terms, the highest
occupied bit, divided by k, recovers the largest score. -/
theorem radix_extract (xs : List Nat) (m k : Nat) (hm : m ∈ xs)
(hmax : ∀ x ∈ xs, x ≤ m) (hk : 0 < k) (hcount : xs.length < 2 ^ k) :
((xs.map (fun x => 2 ^ (x*k))).sum).log2 / k = m := by
let ys := xs.map (fun x => 2 ^ (x*k))
have hlo : 2 ^ (m*k) ≤ ys.sum := mem_le_sum _ _ (List.mem_map.mpr ⟨m, hm, rfl⟩)
have hpos : ys.sum ≠ 0 := Nat.ne_of_gt (Nat.lt_of_lt_of_le (Nat.two_pow_pos _) hlo)
have hbounds : ∀ y ∈ ys, y ≤ 2 ^ (m*k) := by
intro y hy
obtain ⟨x, hx, rfl⟩ := List.mem_map.mp hy
exact Nat.pow_le_pow_right (by decide) (Nat.mul_le_mul_right k (hmax x hx))
have hlen : ys.length < 2 ^ k := by simpa [ys] using hcount
have hhi : ys.sum < 2 ^ ((m+1)*k) := by
rw [Nat.succ_mul, Nat.pow_add, Nat.mul_comm]
exact Nat.lt_of_le_of_lt (sum_bound ys _ hbounds)
(Nat.mul_lt_mul_of_pos_right hlen (Nat.two_pow_pos _))
have hl := (Nat.le_div_iff_mul_le hk).mpr ((Nat.le_log2 hpos).mpr hlo)
have hu := (Nat.div_lt_iff_lt_mul hk).mpr ((Nat.log2_lt hpos).mpr hhi)
change ys.sum.log2 / k = m
omega
def stride (R B : Nat) := (R+1)*(B+1)+1
/-- A finite expression with no extremum and no unknown stopping boundary. -/
def closedNumerator (R B : Nat) : Nat :=
(((scores R B).map fun x => 2 ^ (x * stride R B)).sum).log2 / stride R B
theorem closedNumerator_eq_bellman (R B : Nat) :
closedNumerator R B = bellman R (deck R B) := by
apply radix_extract _ _ _ (optimal_in_scores R B) (scores_bounded R B)
· simp [stride]
· simp [scores, stride, subsets_length, grid_length, Nat.pow_succ]
have := Nat.two_pow_pos ((R+1)*(B+1))
omega
/- The closed expression is intentionally impractical. This independent
evaluator tabulates a row of (number of words, optimal shifted score) pairs.
The equality proof connects executable small instances to the general theorem. -/
abbrev Cell := Nat × Nat
def combine (R r b : Nat) (x y : Cell) : Cell :=
let w := x.1 + y.1
(w, max (reward R (r,b) * w) (x.2 + y.2))
def model (R r b : Nat) : Cell := (weight (deck r b), bellman R (deck r b))
private theorem model00 (R : Nat) : model R 0 0 = (1,R) := by
simp [model, deck, weight, paths, bellman]
private theorem modelR (R r : Nat) :
model R (r+1) 0 = combine R (r+1) 0 (model R r 0) (0,0) := by
simp [model, deck, weight, paths, bellman, combine]
private theorem modelB (R b : Nat) :
model R 0 (b+1) = combine R 0 (b+1) (0,0) (model R 0 b) := by
simp [model, deck, weight, paths, bellman, combine]
private theorem modelRB (R r b : Nat) :
model R (r+1) (b+1) = combine R (r+1) (b+1) (model R r (b+1)) (model R (r+1) b) := by
simp [model, deck, weight, paths, bellman, combine]
/-- Tabulate the one-dimensional recurrence seed, step(0,seed), ... . -/
def scan (seed : Cell) (step : Nat → Cell → Cell) : Nat → Array Cell
| 0 => #[seed]
| n+1 =>
let a := scan seed step n
a.push (step n a[n]!)
private theorem scan_size (seed : Cell) (step : Nat → Cell → Cell) (n : Nat) :
(scan seed step n).size = n+1 := by
induction n with
| zero => rfl
| succ n ih => simp [scan, ih]
private theorem scan_eq (f : Nat → Cell) (seed : Cell) (step : Nat → Cell → Cell)
(B : Nat) (h0 : seed = f 0) (hs : ∀ j < B, step j (f j) = f (j+1))
(i : Nat) (hi : i ≤ B) : (scan seed step B)[i]! = f i := by
induction B generalizing i with
| zero =>
have : i = 0 := by omega
subst i
simpa [scan] using h0
| succ n ih =>
let a := scan seed step n
have ha : a.size = n+1 := scan_size _ _ _
have hlo (j : Nat) (hj : j ≤ n) : a[j]! = f j :=
ih (fun k hk => hs k (by omega)) j hj
change (a.push (step n a[n]!))[i]! = f i
have him : i < (a.push (step n a[n]!)).size := by simp [ha]; omega
rw [getElem!_pos (a.push (step n a[n]!)) i him, Array.getElem_push]
split
· rename_i h
simpa [getElem!_pos a i h] using hlo i (by omega)
· have hh : i = n+1 := by omega
subst i
rw [hlo n (by omega)]
exact hs n (by omega)
def table (R B : Nat) : Nat → Array Cell
| 0 => scan (1,R) (fun b x => combine R 0 (b+1) (0,0) x) B
| r+1 =>
let prev := table R B r
scan (combine R (r+1) 0 prev[0]! (0,0))
(fun b x => combine R (r+1) (b+1) prev[b+1]! x) B
theorem table_eq (R B r b : Nat) (hb : b ≤ B) : (table R B r)[b]! = model R r b := by
induction r generalizing b with
| zero =>
unfold table
apply scan_eq (model R 0) _ _ _ ((model00 _).symm) _ b hb
intro j _
exact (modelB R j).symm
| succ r ih =>
unfold table
apply scan_eq (model R (r+1)) _ _ _ _ _ b hb
· rw [ih 0 (by omega), modelR]
· intro j hj
rw [ih (j+1) (by omega), modelRB]
/- This proof uses Lean kernel reduction, with no native-computation axiom. -/
set_option maxRecDepth 200000 in
set_option maxHeartbeats 10000000 in
theorem table52 : (table 26 26 26)[26]! =
(495918532948104, 14195407920665941) := by decide +kernel
theorem model52 : model 26 26 26 = (495918532948104, 14195407920665941) := by
rw [← table_eq 26 26 26 26 (by decide)]
exact table52
theorem closed52 : closedNumerator 26 26 = 14195407920665941 := by
rw [closedNumerator_eq_bellman]
exact congrArg Prod.snd model52
/-- Cross-multiplied exact expected payoff of a standard deck. -/
theorem payoff52 :
(closedNumerator 26 26 - 26 * weight (deck 26 26)) * 15997372030584 =
41984711742427 * weight (deck 26 26) := by
have hc : weight (deck 26 26) = 495918532948104 := congrArg Prod.fst model52
rw [closed52, hc]
end Problem14
~~~
#### `RationalObstruction.lean`
~~~lean
import Problem14
/-!
A restricted impossibility result for Problem 14, using only Lean's standard
library. A polynomial is a coefficient list in ascending degree, evaluated by
Horner's rule. The bivariate representation takes the black variable outside;
its coefficients are arbitrary polynomials in the red variable. Every rational
function over ℚ can be presented by two integer-coefficient polynomials after
clearing the finitely many coefficient denominators.
-/
namespace Problem14
private theorem weight_branch (s : State) (l r : Tree) :
weight (.branch s l r) = weight l + weight r := by
simp [weight, paths]
private theorem weight_black (b : Nat) : weight (deck 0 b) = 1 := by
induction b with
| zero => simp [deck, weight, paths, bellman, reward] <;> decide
| succ b ih => rw [deck, weight_branch, ih]; rfl
private theorem weight_one (b : Nat) : weight (deck 1 b) = b + 1 := by
induction b with
| zero => simp [deck, weight, paths, bellman, reward] <;> decide
| succ b ih => rw [deck, weight_branch, weight_black, ih]; omega
private theorem stop_all_black (b : Nat) : bellman 1 (deck 0 b) = b + 1 := by
induction b with
| zero => simp [deck, weight, paths, bellman, reward] <;> decide
| succ b ih =>
simp [deck, bellman, weight_black, reward, ih, show weight .empty = 0 from rfl,
Nat.add_comm, Nat.max_eq_left] <;> omega
private theorem one_red_tail (k : Nat) :
bellman 1 (deck 1 (k+2)) = (k+2) * (k+3) := by
induction k with
| zero => simp [deck, weight, paths, bellman, reward] <;> decide
| succ k ih =>
rw [deck.eq_4]
rw [bellman, weight_black, weight_one, stop_all_black, ih]
simp [reward, Nat.add_comm 1, Nat.mul_succ, Nat.succ_mul]
omega
/-- The additional payoff times the number of equiprobable decks. -/
def gainMass (r b : Nat) : Nat :=
bellman r (deck r b) - b * weight (deck r b)
theorem one_red_mass (b : Nat) : gainMass 1 b = if b < 2 then 1 else 0 := by
cases b with
| zero => simp [gainMass, deck, weight, paths, bellman, reward] <;> decide
| succ b => cases b with
| zero => simp [gainMass, deck, weight, paths, bellman, reward] <;> decide
| succ k => simp [gainMass, one_red_tail, weight_one, show ¬k+1+1<2 by omega]
/-- Coefficients start with the constant term. -/
def evalPoly (p : List Int) (x : Int) : Int :=
p.foldr (fun a rest => a + x * rest) 0
private theorem tail_zero_at_zero (p : List Int)
(h : ∀ k : Nat, evalPoly p (k+2 : Nat) = 0) : evalPoly p 0 = 0 := by
cases p with
| nil => rfl
| cons a p =>
simp only [evalPoly, List.foldr_cons, Int.zero_mul, Int.add_zero]
by_cases hn : a = 0
· exact hn
exfalso
have hp := h a.natAbs
change a + (↑(a.natAbs + 2) : Int) * evalPoly p (a.natAbs + 2 : Nat) = 0 at hp
have hd : (↑(a.natAbs + 2) : Int) ∣ a := by
refine ⟨-evalPoly p (a.natAbs + 2 : Nat), ?_⟩
rw [Int.mul_neg]
omega
have hh := Int.natAbs_dvd_natAbs.mpr hd
rw [Int.natAbs_ofNat] at hh
have := Nat.le_of_dvd (Int.natAbs_pos.mpr hn) hh
omega
/-- Plug in the red count first to obtain a polynomial in the black count. -/
def specializeRed (p : List (List Int)) (r : Nat) : List Int :=
p.map (fun a => evalPoly a r)
/-- No single rational function of the two initial counts equals the optimal
gain at every nonnegative integer state and has a nonzero denominator there.
The identities are cross-multiplied so the statement uses exact integers. -/
theorem no_bivariate_rational :
¬ ∃ p q : List (List Int), ∀ r b : Nat,
evalPoly (specializeRed q r) b ≠ 0 ∧
evalPoly (specializeRed p r) b * (weight (deck r b) : Int) =
evalPoly (specializeRed q r) b * (gainMass r b : Int) := by
rintro ⟨p, q, h⟩
have hz : evalPoly (specializeRed p 1) 0 = 0 := by
apply tail_zero_at_zero
intro k
have hk := (h 1 (k+2)).2
have hnon : ¬k+2<2 := by omega
rw [one_red_mass, if_neg hnon, weight_one] at hk
exact (Int.mul_eq_zero.mp (by simpa using hk)).resolve_right (by omega)
have hh := (h 1 0).2
simp [hz, weight_one, one_red_mass] at hh
exact (h 1 0).1 hh.symm
#print axioms no_bivariate_rational
end Problem14
~~~
#### `StraightLine.lean`
~~~lean
import Problem14
/-! The concrete fixed-length integer expression in straight_line.py.
The mathematical proof for every n is in straight_line.md. The last
theorems below use kernel reduction for the two feasible complete cases.
Large arguments of '&&&' can be replaced by 'arithmeticAnd', as proved
in the appendix to the accompanying derivation. -/
namespace Problem14.StraightLine
def arithmeticAnd (a b : Nat) : Nat :=
let ell := 2^(a+b+1)-1
let m := 2^a
let x := 2^(ell*m+a+2)
let y := (x+1)^ell+1
let j := ((1+x*y)^a * (1+y)^(ell-a) / y^b) % y
let powerOfTwo := (j^m % (x^m-2)) % (2*m)
let t := 2^(a+1)-1
(powerOfTwo^(a+1) % t^2) / t
def geometric (base count : Nat) : Nat := (base^count-1)/(base-1)
def tables (n radix stride : Nat) : Nat × Nat :=
let u := radix^stride
let z := u+radix
let m := 2*n+1
let p := geometric z m
let derivative := (m*z^(m-1)-p)/(z-1)
(p, 2*n*p + radix*derivative - u*derivative)
def goodBlocks (n word count : Nat) : Nat :=
let payload := 2^(4*n+1)
let radix := 4*payload
let stride := 2*n+1
let lastDigit := (n-1)*(stride+1)
let block := radix^(lastDigit+1)
let series := geometric block count
let row := geometric radix n
let col := geometric (radix^stride) n
let grid := row*col
let low := payload-1
let a := word &&& (low*grid*series)
let left := (a*radix) &&& (low*(grid-col)*series)
let down := (a*radix^stride) &&& (low*(grid-row)*series)
let rowIndex := (n*radix^n-radix*row)/(radix-1)
let boundary := 2*n*col + (2*n+1)*row + rowIndex
let draw := left+down+boundary*series
let stop := (((tables n radix stride).2 / radix^(stride+1)) &&& (low*grid))*series
let laneFlag := 2*payload
let flags := laneFlag*grid*series
let ge := fun x y : Nat => (flags+x-y) &&& flags
let noLess := (ge a stop) &&& (ge a draw)
let atMostStop := ge stop a
let atMostDraw := ge draw a
let noMore := atMostStop + atMostDraw - (atMostStop &&& atMostDraw)
let failures := (flags - (noLess &&& noMore)) / laneFlag
let blockFlag := block/2
((blockFlag*series-failures) &&& (blockFlag*series)) / blockFlag
/-- Outputs an integer numerator and a positive denominator. -/
def price (pairs : Nat) : Nat × Nat :=
let empty := 1/(pairs+1)
let n := pairs+empty
let payload := 2^(4*n+1)
let radix := 4*payload
let stride := 2*n+1
let lastDigit := (n-1)*(stride+1)
let block := radix^(lastDigit+1)
let series := geometric block block
let word := (block^(block+1)-block*series)/(block-1)
let winners := goodBlocks n word block
let chosen := (word/radix^lastDigit) &&& ((payload-1)*winners)
let copies := block/payload^(n*n)
let objective := (chosen % (block-1))/copies
let decks := ((tables n radix stride).1/radix^(lastDigit+stride+1)) % radix
((1-empty)*(objective - 2*n*decks), (1-empty)*decks+empty)
set_option maxRecDepth 8000 in
theorem price_zero : price 0 = (0,1) := by decide
set_option maxRecDepth 8000 in
theorem price_one : price 1 = (1,2) := by decide
/-- For the one-pair game, the unshifted aggregate agrees with the game
semantics in Problem14.lean (which add one dollar to each deck payoff). -/
theorem one_pair_matches_model :
(price 1).1 + (price 1).2 = (Problem14.model 1 1 1).2 ∧
(price 1).2 = (Problem14.model 1 1 1).1 := by
rw [price_one]
simp [Problem14.model, Problem14.deck, Problem14.bellman, Problem14.weight, Problem14.paths, Problem14.reward]
decide
end Problem14.StraightLine
~~~
#### `Tableau.lean`
~~~lean
import Problem14
/-!
A local addition-only certificate for the stopping game. It uses three natural
numbers per cell: number of colour words, aggregate shifted payoff on stopping
at this cell, and aggregate optimal shifted payoff. Each local check consists
of additions, comparisons and equality tests. No local multiplication and no
sums indexed by the deck size occur in the checker. This module verifies the
mathematical tableau constraints; bit packing is a separate representation.
-/
namespace Problem14.Tableau
structure Entry where
ways : Nat
stop : Nat
value : Nat
deriving DecidableEq, Repr
def vacant : Entry := ⟨0,0,0⟩
def origin (R : Nat) : Entry := ⟨1,R,R⟩
def Local (z red black : Entry) : Prop :=
z.ways = red.ways + black.ways ∧
z.stop + red.ways = red.stop + black.stop + black.ways ∧
z.stop ≤ z.value ∧ red.value + black.value ≤ z.value ∧
(z.value = z.stop ∨ z.value = red.value + black.value)
structure Valid (R B : Nat) (t : Nat → Nat → Entry) : Prop where
start : t 0 0 = origin R
redAxis : ∀ r < R, Local (t (r+1) 0) (t r 0) vacant
blackAxis : ∀ b < B, Local (t 0 (b+1)) vacant (t 0 b)
interior : ∀ r < R, ∀ b < B, Local (t (r+1) (b+1)) (t r (b+1)) (t (r+1) b)
theorem local_unique {z u red black : Entry}
(hz : Local z red black) (hu : Local u red black) : z = u := by
cases z
cases u
simp only [Local] at hz hu
congr 1 <;> omega
theorem unique {R B : Nat} {t u : Nat → Nat → Entry}
(ht : Valid R B t) (hu : Valid R B u) (r b : Nat) (hr : r ≤ R) (hb : b ≤ B) :
t r b = u r b := by
induction r,b using deck.induct with
| case1 => exact ht.start.trans hu.start.symm
| case2 r ih =>
have h := ht.redAxis r (by omega)
rw [ih (by omega) hb] at h
exact local_unique h (hu.redAxis r (by omega))
| case3 b ih =>
have h := ht.blackAxis b (by omega)
rw [ih hr (by omega)] at h
exact local_unique h (hu.blackAxis b (by omega))
| case4 r b ihl ihr =>
have h := ht.interior r (by omega) b (by omega)
rw [ihl (by omega) hb, ihr hr (by omega)] at h
exact local_unique h (hu.interior r (by omega) b (by omega))
def liftCell (k : Nat) (x : Cell) : Entry := ⟨x.1,k*x.1,x.2⟩
def genuine (R r b : Nat) := liftCell (R-r+b) (model R r b)
private theorem local_lift (k : Nat) (x y z : Cell) (L M : Entry)
(hw : z.1 = x.1 + y.1) (hv : z.2 = max (k*z.1) (x.2+y.2))
(hxw : L.ways = x.1) (hyw : M.ways = y.1)
(hxl : L.stop = k*x.1 + x.1) (hyl : M.stop + y.1 = k*y.1)
(hxv : L.value = x.2) (hyv : M.value = y.2) :
Local (liftCell k z) L M := by
unfold Local liftCell
simp only [hxw, hyw, hxv, hyv, hxl, hw, Nat.mul_add] at *
refine ⟨True.intro, ?_, ?_, ?_, ?_⟩
· omega
· rw [hv]; apply Nat.le_max_left
· rw [hv]; apply Nat.le_max_right
· rw [hv, Nat.max_def]; split <;> simp
theorem genuine_valid (R B : Nat) : Valid R B (genuine R) := by
constructor
· simp [genuine, liftCell, model, deck, bellman, paths, weight, origin]
· intro r hr
let x := model R r 0
let y : Cell := (0,0)
let z := model R (r+1) 0
apply local_lift (R-(r+1)+0) x y z
· simp [z,x,y,model,deck,weight,paths]
· simp [z,x,y,model,deck,weight,paths,bellman,reward]
· rfl
· rfl
· have he : R-r = (R-(r+1))+1 := by omega
simp [genuine,liftCell,x,he,Nat.succ_mul]
· simp [vacant,y]
· rfl
· rfl
· intro b _
let x : Cell := (0,0)
let y := model R 0 b
let z := model R 0 (b+1)
apply local_lift (R-0+(b+1)) x y z
· simp [z,x,y,model,deck,weight,paths]
· simp [z,x,y,model,deck,weight,paths,bellman,reward]
· rfl
· rfl
· simp [vacant,x]
· simp [genuine,liftCell,y,Nat.succ_mul,← Nat.add_assoc]
· rfl
· rfl
· intro r hr b _
let x := model R r (b+1)
let y := model R (r+1) b
let z := model R (r+1) (b+1)
apply local_lift (R-(r+1)+(b+1)) x y z
· simp [z,x,y,model,deck,weight,paths]
· simp [z,x,y,model,deck,weight,paths,bellman,reward]
· rfl
· rfl
· have he : R-r+(b+1) = (R-(r+1)+(b+1))+1 := by omega
simp [genuine,liftCell,x,he,Nat.succ_mul]
· simp [genuine,liftCell,y,Nat.succ_mul,← Nat.add_assoc]
· rfl
· rfl
/-- Any rectangle satisfying the local arithmetic constraints yields the
optimal numerator proved in Problem14.lean. -/
theorem accepted_value {R B : Nat} {t : Nat → Nat → Entry} (ht : Valid R B t) :
(t R B).value = closedNumerator R B := by
rw [unique ht (genuine_valid R B) R B (by omega) (by omega),
closedNumerator_eq_bellman]
rfl
theorem ways_bound (R B : Nat) {t : Nat → Nat → Entry} (ht : Valid R B t)
(r b : Nat) (hr : r ≤ R) (hb : b ≤ B) : (t r b).ways ≤ 2^(r+b) := by
induction r,b using deck.induct with
| case1 => rw [ht.start]; simp [origin]
| case2 r ih =>
have hw := (ht.redAxis r (by omega)).1
have h := ih (by omega) hb
simp only [Nat.succ_eq_add_one, vacant, Nat.add_zero, Nat.pow_succ] at *
omega
| case3 b ih =>
have hw := (ht.blackAxis b (by omega)).1
have h := ih hr (by omega)
simp only [Nat.succ_eq_add_one, vacant, Nat.zero_add, Nat.pow_succ] at *
omega
| case4 r b ihl ihr =>
have hl := ihl (by omega) hb
have hu := ihr hr (by omega)
have hw := (ht.interior r (by omega) b (by omega)).1
simp only [Nat.succ_add, Nat.add_succ, Nat.add_zero, Nat.pow_succ] at *
omega
private theorem value_local {z x y : Entry} {cap : Nat} (h : Local z x y)
(hs : z.stop ≤ cap*z.ways) (hx : x.value ≤ cap*x.ways) (hy : y.value ≤ cap*y.ways) :
z.value ≤ cap*z.ways := by
obtain ⟨h0,_,_,_,h4⟩ := h
rcases h4 with h | h
· exact h ▸ hs
· rw [h, h0, Nat.mul_add]
exact Nat.add_le_add hx hy
theorem value_bound (R B r b : Nat) (hr : r ≤ R) (hb : b ≤ B) :
(genuine R r b).value ≤ (R+B)*(genuine R r b).ways := by
have hv := genuine_valid R B
have hs (i j : Nat) (hj : j ≤ B) :
(genuine R i j).stop ≤ (R+B)*(genuine R i j).ways := by
unfold genuine liftCell
apply Nat.mul_le_mul_right
omega
induction r,b using deck.induct with
| case1 => rw [hv.start]; simp [origin]
| case2 r ih =>
exact value_local (hv.redAxis r (by omega)) (hs _ _ hb)
(ih (by omega) hb) (by simp [vacant])
| case3 b ih =>
exact value_local (hv.blackAxis b (by omega)) (hs _ _ hb)
(by simp [vacant]) (ih hr (by omega))
| case4 r b ihl ihr =>
exact value_local (hv.interior r (by omega) b (by omega)) (hs _ _ hb)
(ihl (by omega) hb) (ihr hr (by omega))
/-- A single uniform limit sufficient for every field in the tableau. -/
theorem field_bound (R B r b : Nat) (hr : r ≤ R) (hb : b ≤ B) :
let t := genuine R r b
let q := (R+B+1)*2^(R+B)
t.ways ≤ q ∧ t.stop ≤ q ∧ t.value ≤ q := by
dsimp only
have hw := ways_bound R B (genuine_valid R B) r b hr hb
have hpow := Nat.pow_le_pow_right Nat.zero_lt_two (Nat.add_le_add hr hb)
have hp : (genuine R r b).ways ≤ 2^(R+B) := Nat.le_trans hw hpow
have upper := Nat.mul_le_mul_left (R+B) hp
have hv := value_bound R B r b hr hb
have hs : (genuine R r b).stop ≤ (R+B)*(genuine R r b).ways := by
unfold genuine liftCell
apply Nat.mul_le_mul_right
omega
rw [Nat.succ_mul]
omega
private def inRange (R : Nat) : Tree → Prop
| .empty | .leaf => True
| .branch s l r => s.1 ≤ R ∧ inRange R l ∧ inRange R r
private theorem deck_inRange (R r b : Nat) (hr : r ≤ R) :
inRange R (deck r b) := by
induction r,b using deck.induct with
| case1 => simp [deck,inRange]
| case2 r ih => simp [deck,inRange,hr, ih (by omega)]
| case3 b ih => simp [deck,inRange,ih hr]
| case4 r b ihl ihr => simp [deck,inRange,hr,ihl (by omega),ihr hr]
private theorem weight_node (s : State) (l r : Tree) :
weight (.branch s l r) = weight l + weight r := by simp [weight,paths]
private theorem shift (R k : Nat) (t : Tree) (ht : inRange R t) :
bellman (R+k) t = bellman R t + k * weight t := by
induction t with
| empty => simp [bellman,weight,paths]
| leaf => simp [bellman,weight,paths]
| branch s l r hl hr =>
obtain ⟨hs,htl,htr⟩ := ht
have hrew : reward (R+k) s = reward R s + k := by
unfold reward
omega
rw [bellman,bellman,weight_node,hl htl,hr htr,hrew,Nat.add_mul]
rw [Nat.mul_add k]
omega
/-- Exactly the axis checks and the four comparison tests performed in
straight_line.py after unpacking its lanes. Each interior exercise digit is
(2*n+b-r)*number of colour words, indexed by the actual remaining counts. -/
structure PriceTable (n : Nat) (a : Nat → Nat → Nat) : Prop where
redAxis : ∀ r ≤ n, a r 0 = 2*n
blackAxis : ∀ b ≤ n, a 0 b = 2*n+b
cell : ∀ r < n, ∀ b < n,
let x := a (r+1) (b+1)
let stop := (genuine (2*n) (r+1) (b+1)).stop
let step := a r (b+1) + a (r+1) b
stop ≤ x ∧ step ≤ x ∧ (x ≤ stop ∨ x ≤ step)
private theorem genuine_red (R r : Nat) (hr : r ≤ R) :
(genuine R r 0).ways = 1 ∧ (genuine R r 0).value = R := by
have hv := genuine_valid R 0
induction r with
| zero => rw [hv.start]; simp [origin]
| succ r ih =>
have hp := ih (by omega)
obtain ⟨hw,_,hl,hd,he⟩ := hv.redAxis r (by omega)
simp only [vacant,Nat.add_zero,hp.1,hp.2] at hw hd he
have hs : (genuine R (r+1) 0).stop = (R-(r+1))*(genuine R (r+1) 0).ways := by
rfl
rw [hw, Nat.mul_one] at hs
exact ⟨hw, by omega⟩
private theorem genuine_black (R b : Nat) :
(genuine R 0 b).ways = 1 ∧ (genuine R 0 b).value = R+b := by
induction b with
| zero => rw [(genuine_valid R 0).start]; simp [origin]
| succ b ih =>
obtain ⟨hw,_,hl,hd,he⟩ := (genuine_valid R (b+1)).blackAxis b (by omega)
simp only [vacant,Nat.zero_add,ih.1,ih.2] at hw hd he
have hs : (genuine R 0 (b+1)).stop = (R+(b+1))*(genuine R 0 (b+1)).ways := by
rfl
rw [hw, Nat.mul_one] at hs
exact ⟨hw, by omega⟩
theorem genuine_price_table (n : Nat) :
PriceTable n (fun r b => (genuine (2*n) r b).value) := by
constructor
· intro r hr
exact (genuine_red (2*n) r (by omega)).2
· intro b _
exact (genuine_black _ _).2
· intro r hr b hb
obtain ⟨_,_,hs,hc,he⟩ := (genuine_valid (2*n) n).interior r (by omega) b hb
exact ⟨hs,hc,by omega⟩
theorem price_table_unique (n : Nat) {a v : Nat → Nat → Nat} (ha : PriceTable n a)
(hv : PriceTable n v) (r b : Nat) (hr : r ≤ n) (hb : b ≤ n) :
a r b = v r b := by
induction r,b using deck.induct with
| case1 => rw [ha.redAxis 0 hr,hv.redAxis 0 hr]
| case2 r _ => rw [ha.redAxis _ hr,hv.redAxis _ hr]
| case3 b _ => rw [ha.blackAxis _ hb,hv.blackAxis _ hb]
| case4 r b ihl ihr =>
have h1 := ha.cell r (by omega) b (by omega)
have h2 := hv.cell r (by omega) b (by omega)
dsimp only at h1 h2
rw [ihl (by omega) hb, ihr hr (by omega)] at h1
change a (r+1) (b+1) = v (r+1) (b+1)
omega
/-- Unpacked semantics of the concrete straight-line construction: it uses
shift 2*n; closedNumerator uses shift n. -/
theorem packed_corner {n : Nat} {a : Nat → Nat → Nat} (h : PriceTable n a) :
a n n = closedNumerator n n + n * weight (deck n n) := by
rw [price_table_unique n h (genuine_price_table n) n n (by omega) (by omega),
closedNumerator_eq_bellman]
change bellman (2*n) (deck n n) = _
rw [show 2*n = n+n by omega]
exact shift n n (deck n n) (deck_inRange _ _ _ (by omega))
end Problem14.Tableau
~~~
#### `TaylorGap.lean`
~~~lean
import Std
/-!
Taylor coefficients of a differential operator of order k and polynomial
coefficient degree M have input bandwidth [q-M,q+k] at output index q.
This module proves the gap/truncation contradiction used for Problem 14.
It assumes the analytic order bound, as a hypothesis restricted to an
explicit class of admissible sequences (e.g., convergent Taylor series).
No analytic assertion about arbitrary formal solutions is needed.
Run: lean TaylorGap.lean (Lean 4.19.0, standard library only).
-/
namespace Problem14.TaylorGap
abbrev Series (α : Type u) := Nat → α
abbrev Operator (α : Type u) := Series α → Series α
/-- Knowing the indicated input coefficients determines output coefficient q. -/
def Local {α : Type u} (D : Operator α) (M k : Nat) : Prop :=
∀ q f g, (∀ i, q ≤ i+M → i ≤ q+k → f i = g i) → D f q = D g q
def Kernel {α : Type u} (z : α) (D : Operator α) (f : Series α) : Prop :=
∀ q, D f q = z
def truncation {α : Type u} (z : α) (N : Nat) (f : Series α) : Series α :=
fun i => if i < N then f i else z
def tail {α : Type u} (z : α) (N : Nat) (f : Series α) : Series α :=
fun i => if i < N then z else f i
private def finiteSum {α : Type u} (z : α) (add : α → α → α) (f : Nat → α) :
Nat → α
| 0 => z
| n+1 => add (finiteSum z add f n) (f n)
private theorem sum_congr {α : Type u} (z : α) (add : α → α → α)
(f g : Nat → α) (n : Nat) (h : ∀ i < n, f i = g i) :
finiteSum z add f n = finiteSum z add g n := by
induction n with
| zero => rfl
| succ n ih =>
rw [finiteSum,finiteSum,ih (fun i hi => h i (by omega)),h n (by omega)]
private theorem sum_zero {α : Type u} (z : α) (add : α → α → α)
(ha : add z z = z) (f : Nat → α) (n : Nat) (h : ∀ i < n, f i = z) :
finiteSum z add f n = z := by
induction n with
| zero => rfl
| succ n ih =>
rw [finiteSum,ih (fun i hi => h i (by omega)),h n (by omega),ha]
/-- Weighted coefficient sum for a polynomial differential operator.
The callback takes derivative degree j, polynomial degree p, derivative-series
coefficient index h=q-p, and input f(h+j). For a linear operator it multiplies
the last argument by c[j,p]*(h+1)...(h+j). Allowing any weighting also covers
coefficient fields without requiring an algebra library. -/
def differential {α : Type u} (z : α) (add : α → α → α)
(w : Nat → Nat → Nat → α → α) (M k : Nat) : Operator α :=
fun f q => finiteSum z add (fun j =>
finiteSum z add (fun p =>
if p ≤ q then w j p (q-p) (f (q-p+j)) else z) (M+1)) (k+1)
theorem differential_local {α : Type u} (z : α) (add : α → α → α)
(w : Nat → Nat → Nat → α → α) (M k : Nat) :
Local (differential z add w M k) M k := by
intro q f g h
apply sum_congr
intro j hj
apply sum_congr
intro p hp
split
· rw [h _ (by omega) (by omega)]
· rfl
theorem differential_zero {α : Type u} (z : α) (add : α → α → α)
(w : Nat → Nat → Nat → α → α) (M k : Nat)
(ha : add z z = z) (hw : ∀ j p h, w j p h z = z) :
Kernel z (differential z add w M k) (fun _ => z) := by
intro q
apply sum_zero _ _ ha
intro j _
apply sum_zero _ _ ha
intro p _
split <;> simp [hw]
/-- If the input has a sufficiently long zero block and solves the homogeneous
equation, cutting before that block leaves two homogeneous solutions.
A block of length M+k suffices, including the boundary case. -/
theorem split_at_gap {α : Type u} (z : α) (D : Operator α) (f : Series α)
(M k N s : Nat) (hD : Local D M k) (hzero : Kernel z D (fun _ => z))
(hf : Kernel z D f) (gap : ∀ i, N ≤ i → i < N+s → f i = z)
(hlen : M+k ≤ s) :
Kernel z D (truncation z N f) ∧ Kernel z D (tail z N f) := by
have both (q : Nat) : D (truncation z N f) q = z ∧ D (tail z N f) q = z := by
by_cases early : q+k < N+s
· have hp := hD q (truncation z N f) f (by
intro i _ hi
unfold truncation
split
· rfl
· exact (gap i (by omega) (by omega)).symm)
have ht := hD q (tail z N f) (fun _ => z) (by
intro i _ hi
unfold tail
split
· rfl
· exact gap i (by omega) (by omega))
exact ⟨hp.trans (hf q),ht.trans (hzero q)⟩
· have hp := hD q (truncation z N f) (fun _ => z) (by
intro i hi _
simp [truncation,show ¬ i < N by omega])
have ht := hD q (tail z N f) f (by
intro i hi _
simp [tail,show ¬ i < N by omega])
exact ⟨hp.trans (hzero q),ht.trans (hf q)⟩
exact ⟨fun q => (both q).1,fun q => (both q).2⟩
/-- Admissible may be the class of series converging near zero. The bound
says each nonzero admissible kernel element has a nonzero coefficient of
index at most B. Any gap as above beyond that bound must persist forever. -/
theorem gap_persists {α : Type u} (z : α) (D : Operator α) (f : Series α)
(M k N s B : Nat) (admissible : Series α → Prop)
(hD : Local D M k) (hzero : Kernel z D (fun _ => z))
(hf : Kernel z D f) (hadm : admissible (tail z N f))
(bound : ∀ g, admissible g → Kernel z D g → (∃ q, g q ≠ z) → ∃ i ≤ B, g i ≠ z)
(gap : ∀ i, N ≤ i → i < N+s → f i = z) (hlen : M+k ≤ s)
(late : B < N+s) : ∀ q ≥ N+s, f q = z := by
intro q hq
apply Classical.byContradiction
intro hn
have ht := (split_at_gap z D f M k N s hD hzero hf gap hlen).2
have witness : ∃ q, tail z N f q ≠ z :=
⟨q, by simpa [tail,show ¬q < N by omega] using hn⟩
obtain ⟨i,hi,hbad⟩ := bound _ hadm ht witness
by_cases h : i < N
· simp [tail,h] at hbad
· exact hbad (by simpa only [tail,if_neg h] using gap i (by omega) (by omega))
/-- Ordinary integration-free specialization with integer polynomial
coefficients. asc h j is the multiplier of f(h+j) in the jth derivative. -/
def asc (h : Nat) : Nat → Nat
| 0 => 1
| j+1 => (h+j+1) * asc h j
def intOperator (c : Nat → Nat → Int) (M k : Nat) : Operator Int :=
differential 0 (·+·) (fun j p h x => c j p*(asc h j : Int)*x) M k
theorem intOperator_local (c : Nat → Nat → Int) (M k : Nat) :
Local (intOperator c M k) M k := differential_local _ _ _ _ _
theorem intOperator_zero (c : Nat → Nat → Int) (M k : Nat) :
Kernel 0 (intOperator c M k) (fun _ => 0) :=
differential_zero _ _ _ _ _ rfl (by intros; simp)
end Problem14.TaylorGap
~~~
#### `asmproof/Brownian.lean`
~~~lean
import Coefficient
import Mathlib.MeasureTheory.Integral.Gamma
import Mathlib.MeasureTheory.Integral.DominatedConvergence
import Mathlib.Analysis.SpecialFunctions.Gaussian.GaussianIntegral
/-! The integral definition of the Brownian coefficient. Dominated
convergence, Gaussian moments, and the moment recurrence give the
power-series characterization used in Coefficient.lean. -/
namespace P14Quote.Coefficient
open MeasureTheory Real Set Filter
open scoped Topology
noncomputable def laplace (x : ℝ) : ℝ := ∫ u in Ioi (0:ℝ), exp (x*u-u^2/2)
noncomputable def moment (n : ℕ) : ℝ :=
∫ u in Ioi (0:ℝ), u^n * exp (-(1/2)*u^2)
noncomputable def integrand (x : ℝ) (n : ℕ) (u : ℝ) : ℝ :=
(x*u)^n/(n.factorial:ℝ)*exp (-(1/2)*u^2)
private theorem integrand_sum (x u : ℝ) :
HasSum (fun n => integrand x n u) (exp (x*u-u^2/2)) := by
have h := (NormedSpace.expSeries_div_hasSum_exp ℝ (x*u)).mul_right (exp (-(1/2)*u^2))
rw [← Real.exp_eq_exp_ℝ, ← Real.exp_add] at h
convert h using 2; ring
private theorem laplace_integrable (x : ℝ) :
Integrable (fun u : ℝ => exp (x*u-u^2/2)) := by
refine ((integrable_exp_neg_mul_sq (b:=(1/4:ℝ)) (by norm_num)).const_mul (exp (x^2))).mono'
(by apply Continuous.aestronglyMeasurable; fun_prop) (ae_of_all _ fun u => ?_)
rw [Real.norm_eq_abs, abs_of_pos (Real.exp_pos _), ←Real.exp_add, Real.exp_le_exp]
nlinarith [sq_nonneg (x-u/2)]
private theorem integrated_series {x : ℝ} (hx : 0 ≤ x) :
HasSum (fun n => x^n/(n.factorial:ℝ)*moment n) (laplace x) := by
have H := MeasureTheory.hasSum_integral_of_dominated_convergence
(μ := volume.restrict (Ioi (0:ℝ))) (F:=integrand x) (integrand x)
(fun i => by apply Continuous.aestronglyMeasurable; unfold integrand; fun_prop)
(fun n => by
filter_upwards [ae_restrict_mem (μ:=volume) (s:=Ioi (0:ℝ)) measurableSet_Ioi] with u hu
have upos : 0 < u := hu
unfold integrand
rw [Real.norm_eq_abs,abs_of_nonneg (by positivity)])
(ae_of_all _ fun u => (integrand_sum x u).summable)
((laplace_integrable x).integrableOn.congr (ae_of_all _ fun u => (integrand_sum x u).tsum_eq.symm))
(ae_of_all _ fun u => integrand_sum x u)
apply H.congr_fun
intro n
unfold integrand moment
rw [← integral_const_mul]
congr 1
funext u
rw [mul_pow]
ring
private theorem moment_gamma (n : ℕ) :
moment n = (1/2:ℝ)^(-((n:ℝ)+1)/2)*(1/2)*Gamma (((n:ℝ)+1)/2) := by
simpa only [Real.rpow_natCast,Real.rpow_two] using
(integral_rpow_mul_exp_neg_mul_rpow (p:=2) (q:=(n:ℝ)) (b:=1/2)
(by norm_num) (by linarith [Nat.cast_nonneg (α:=ℝ) n]) (by norm_num))
theorem moment_step (n : ℕ) :
moment (n+2) = ((n:ℝ)+1)*moment n := by
rw [moment_gamma, moment_gamma]
push_cast
rw [show ((n:ℝ)+2+1)/2=((n+1)/2)+1 by ring,
show -((n:ℝ)+2+1)/2=(-(n+1)/2)+(-1) by ring,
Real.rpow_add (by norm_num),Real.rpow_neg_one,Real.Gamma_add_one (by positivity)]
ring
theorem moment_zero : moment 0 = Real.sqrt (Real.pi/2) := by
unfold moment
simp only [pow_zero,one_mul,integral_gaussian_Ioi]
apply (sq_eq_sq₀ (by positivity) (by positivity)).mp
rw [div_pow, Real.sq_sqrt (by positivity), Real.sq_sqrt (by positivity)]
ring
private theorem moment_one : moment 1 = 1 := by
rw [moment_gamma]
norm_num
noncomputable def taylorCoeff (n : ℕ) := moment n / (n.factorial:ℝ)
private theorem coeff_step (n : ℕ) :
taylorCoeff (n+2) = taylorCoeff n/((n:ℝ)+2) := by
unfold taylorCoeff
rw [moment_step,Nat.factorial_succ,Nat.factorial_succ]
push_cast
have pos1 : (0:ℝ) < n+1 := by positivity
have pos2 : (0:ℝ) < n+1+1 := by positivity
field_simp
ring
private theorem coeff_pair (m : ℕ) :
taylorCoeff (2*m) = Real.sqrt (Real.pi/2)/(evenDen m:ℝ) ∧
taylorCoeff (2*m+1) = 1/(oddDen m:ℝ) := by
induction m with
| zero => simp [taylorCoeff, moment_zero, moment_one,evenDen,oddDen]
| succ m ih =>
rw [show 2*(m+1)=2*m+2 by omega,show 2*m+2+1=2*m+1+2 by omega,
coeff_step, coeff_step, ih.1,ih.2,evenDen.eq_2,oddDen.eq_2]
push_cast
constructor <;> rw [div_div] <;> congr 1 <;> ring
theorem laplace_taylor {x : ℝ} (hx : 0 ≤ x) :
HasSum (pair (Real.sqrt (Real.pi/2)) x) (laplace x) := by
let f (n : ℕ) := x^n/(n.factorial:ℝ)*moment n
have h : HasSum f (laplace x) := integrated_series hx
have he : Summable (fun m : ℕ => f (2*m)) :=
h.summable.comp_injective (i:=fun m : ℕ => 2*m) (by intro a b eq; dsimp at eq; omega)
have ho : Summable (fun m : ℕ => f (2*m+1)) :=
h.summable.comp_injective (i:=fun m : ℕ => 2*m+1) (by intro a b eq; dsimp at eq; omega)
have grouped := he.hasSum.add ho.hasSum
rw [tsum_even_add_odd he ho,h.tsum_eq] at grouped
apply grouped.congr_fun
intro m
have cast (n : ℕ) : f n = taylorCoeff n*x^n := by dsimp [f,taylorCoeff]; ring
rw [cast,cast,(coeff_pair m).1,(coeff_pair m).2]
unfold pair
ring
private theorem root_unit {x : ℝ} (root : (1-x^2)*laplace x = x) : x ≤ 1 := by
have pos : 0 ≤ laplace x := integral_nonneg (fun _ => (Real.exp_pos _).le)
have bound : x ≤ 1 := by
by_contra! contra
have : 1-x^2 ≤ 0 := by nlinarith [sq_nonneg (x-1)]
have q := mul_nonpos_of_nonpos_of_nonneg this pos
linarith
exact bound
theorem brownian_root_bounds {x : ℝ} (hx : 0 ≤ x) (root : (1-x^2)*laplace x = x) :
(xLo:ℝ) ≤ x ∧ x ≤ xHi :=
series_root_bounds hx (root_unit root) (taylor_root_equation (laplace_taylor hx) root)
/-- The coefficient bracket for every nonnegative solution of the actual
Gaussian integral equation defining the Brownian stopping threshold. -/
theorem brownian_coefficient {x : ℝ} (hx : 0 ≤ x)
(root : (1-x^2)*laplace x = x) :
(coefficient:ℝ)/10^18 ≤ (1-x^2)*Real.sqrt Real.pi ∧
(1-x^2)*Real.sqrt Real.pi ≤ ((coefficient:ℝ)+1)/10^18 := by
exact taylor_coefficient hx (root_unit root) (laplace_taylor hx) root
private theorem continuous_laplace_unit : ContinuousOn laplace (Icc 0 1) := by
intro x hx
apply continuousWithinAt_of_dominated (μ:=volume.restrict (Ioi (0:ℝ)))
(F:=fun y u:ℝ => exp (y*u-u^2/2)) (bound:=fun u:ℝ => exp (1*u-u^2/2))
· exact Eventually.of_forall (fun y => by apply Continuous.aestronglyMeasurable; fun_prop)
· filter_upwards [self_mem_nhdsWithin] with y hy
filter_upwards [ae_restrict_mem (μ:=volume) measurableSet_Ioi] with u hu
rw [Real.norm_eq_abs, abs_of_pos (exp_pos _), Real.exp_le_exp]
exact sub_le_sub_right (mul_le_mul_of_nonneg_right hy.2 (le_of_lt hu)) _
· exact (laplace_integrable 1).integrableOn
· exact ae_of_all _ (fun u => by apply Continuous.continuousWithinAt; fun_prop)
private theorem root_exists : ∃ x:ℝ, 0 ≤ x ∧ (1-x^2)*laplace x = x := by
let f := fun x:ℝ => (1-x^2)*laplace x-x
have hc : ContinuousOn f (Icc 0 1) :=
((continuousOn_const.sub (continuousOn_id.pow 2)).mul continuous_laplace_unit).sub continuousOn_id
have lo : f 1 ≤ 0 := by norm_num [f]
have hi : 0 ≤ f 0 := by
simpa [f] using (show 0 ≤ laplace 0 from integral_nonneg (fun _ => (exp_pos _).le))
obtain ⟨x,hx,hf⟩ := intermediate_value_Icc' zero_le_one hc ⟨lo,hi⟩
exact ⟨x,hx.1,sub_eq_zero.mp hf⟩
private theorem root_not_lt {x y : ℝ} (hx : 0 ≤ x) (hy : 0 ≤ y)
(rx : (1-x^2)*laplace x = x) (ry : (1-y^2)*laplace y = y) : ¬ x < y := by
intro hxy
let a := sqrt (π/2)
have ha : 0 < a := by dsimp [a]; positivity
have m (n:ℕ) : term a x n ≤ term a y n := by
unfold term
gcongr
have hzero : term a x 0 < term a y 0 := by
have p2 := pow_lt_pow_left₀ hxy hx (by decide : (2:ℕ) ≠ 0)
have p3 := pow_le_pow_left₀ hx hxy.le 3
norm_num [term,evenDen,oddDen]
nlinarith [mul_lt_mul_of_pos_left p2 ha]
have sx := taylor_root_equation (laplace_taylor hx) rx
have sy := taylor_root_equation (laplace_taylor hy) ry
exact lt_irrefl a (hasSum_lt m hzero sx sy)
theorem existsUnique_threshold : ∃! x:ℝ, 0 ≤ x ∧ (1-x^2)*laplace x = x := by
obtain ⟨x,hx,rx⟩ := root_exists
refine ⟨x,⟨hx,rx⟩,?_⟩
intro y hy
exact le_antisymm (le_of_not_gt (root_not_lt hx hy.1 rx hy.2))
(le_of_not_gt (root_not_lt hy.1 hx hy.2 rx))
noncomputable def threshold : ℝ := existsUnique_threshold.exists.choose
theorem threshold_spec : 0 ≤ threshold ∧ (1-threshold^2)*laplace threshold = threshold :=
existsUnique_threshold.exists.choose_spec
theorem threshold_coefficient :
(coefficient:ℝ)/10^18 ≤ (1-threshold^2)*Real.sqrt Real.pi ∧
(1-threshold^2)*Real.sqrt Real.pi ≤ ((coefficient:ℝ)+1)/10^18 :=
brownian_coefficient threshold_spec.1 threshold_spec.2
end P14Quote.Coefficient
~~~
#### `asmproof/CLIProof.lean`
~~~lean
import Std
/-! The complete decimal parser of cli.S. Bytes in an argv element exclude
NUL; the memory after its last byte contains a NUL. The model uses the
remaining byte suffix as its read-only pointer and records a compare's two
unsigned operands for the conditional jumps. -/
namespace Problem14.CLI
abbrev Byte := Fin 256
def W : Nat := 18446744073709551616
def cutoff : Nat := 1844674407370955161
/-- Unbounded, mathematical evaluation of the ASCII decimal expansion. -/
def decimal (a : Nat) : List Byte → Option Nat
| [] => some a
| b :: bs =>
if 48 ≤ b.val ∧ b.val ≤ 57 then decimal (10*a + (b.val-48)) bs else none
def admit : Option Nat → Nat
| some n => if 32768 ≤ n ∧ n < W then n else 0
| none => 0
private theorem above (bs : List Byte) (a : Nat) (ha : W ≤ a) :
admit (decimal a bs) = 0 := by
induction bs generalizing a with
| nil => simp [decimal, admit, Nat.not_lt_of_ge ha]
| cons b bs ih =>
simp only [decimal]
split
· apply ih; omega
· rfl
def digit (b : Nat) : Nat := (b + 4294967296 - 48) % 4294967296
private theorem digit_ok (b : Byte) :
digit b ≤ 9 ↔ 48 ≤ b.val ∧ b.val ≤ 57 := by
have := b.isLt
simp only [digit]
omega
private theorem digit_val (b : Byte) (h : digit b ≤ 9) : digit b = b.val - 48 := by
have := (digit_ok b).mp h
simp only [digit]; omega
private theorem guard (a d : Nat) (hd : d ≤ 9) :
(a < cutoff ∨ a = cutoff ∧ d ≤ 5) ↔ 10*a+d < W := by
dsimp [cutoff, W]; omega
private theorem leas (a d : Nat) (h : 10*a+d < W) :
(d + 2*((a + 4*a)%W))%W = 10*a+d := by
have h₁ : a+4*a < W := by omega
rw [Nat.mod_eq_of_lt h₁, Nat.mod_eq_of_lt (by omega)]
omega
/-- All 67 bytes of p14_parse_pairs, extracted before linking. -/
def parserBytes : List Nat := [
0x31,0xd2,0x49,0xb8,0x99,0x99,0x99,0x99,0x99,0x99,0x99,0x19,
0x0f,0xb6,0x07,0x83,0xe8,0x30,0x83,0xf8,0x09,0x77,0x29,
0x4c,0x39,0xc2,0x77,0x24,0x72,0x05,0x83,0xf8,0x05,0x77,0x1d,
0x48,0x8d,0x14,0x92,0x48,0x8d,0x14,0x50,0x48,0xff,0xc7,
0x80,0x3f,0x00,0x75,0xd9,0x48,0x81,0xfa,0x00,0x80,0x00,0x00,
0x72,0x04,0x48,0x89,0xd0,0xc3,0x31,0xc0,0xc3]
inductive Cc where | above | below | ne
deriving DecidableEq, Repr
inductive Op where
| zeroD | limit (n : Nat) | loadA | subA (n : Nat) | cmpA (n : Nat) | cmpDC
| jump (cc : Cc) (ip : Nat) | lea5 | lea2 | incPtr | cmpByte (n : Nat)
| cmpD (n : Nat) | movAD | zeroA | ret
deriving DecidableEq, Repr
private def rel (next b : Nat) := if b < 128 then next+b else next+b-256
private def le4 (a b c d : Nat) := a+256*b+65536*c+16777216*d
/-- Only the x86 encodings used by the parser. Immediate operands and jump
displacements are read from the instruction stream. -/
def decode (ip : Nat) : List Nat → Option (Op × Nat)
| 0x31::0xd2::_ => some (.zeroD, ip+2)
| 0x31::0xc0::_ => some (.zeroA, ip+2)
| 0x49::0xb8::a::b::c::d::e::f::g::h::_ =>
some (.limit (le4 a b c d + 4294967296*le4 e f g h), ip+10)
| 0x0f::0xb6::0x07::_ => some (.loadA, ip+3)
| 0x83::0xe8::n::_ => some (.subA n, ip+3)
| 0x83::0xf8::n::_ => some (.cmpA n, ip+3)
| 0x77::b::_ => some (.jump .above (rel (ip+2) b), ip+2)
| 0x72::b::_ => some (.jump .below (rel (ip+2) b), ip+2)
| 0x75::b::_ => some (.jump .ne (rel (ip+2) b), ip+2)
| 0x4c::0x39::0xc2::_ => some (.cmpDC, ip+3)
| 0x48::0x8d::0x14::0x92::_ => some (.lea5, ip+4)
| 0x48::0x8d::0x14::0x50::_ => some (.lea2, ip+4)
| 0x48::0xff::0xc7::_ => some (.incPtr, ip+3)
| 0x80::0x3f::n::_ => some (.cmpByte n, ip+3)
| 0x48::0x81::0xfa::a::b::c::d::_ => some (.cmpD (le4 a b c d), ip+7)
| 0x48::0x89::0xd0::_ => some (.movAD, ip+3)
| 0xc3::_ => some (.ret, ip+1)
| _ => none
def fetch (ip : Nat) := decode ip (parserBytes.drop ip)
structure CPU where
ip : Nat
memory : List Byte
ax : Nat := 0
dx : Nat := 0
r8 : Nat := 0
l : Nat := 0
r : Nat := 0
def byteAt : List Byte → Nat | [] => 0 | b::_ => b.val
def exec (s : CPU) (next : Nat) (op : Op) : CPU :=
let t := {s with ip := next}
match op with
| .zeroD => {t with dx := 0}
| .zeroA => {t with ax := 0}
| .limit n => {t with r8 := n}
| .loadA => {t with ax := byteAt s.memory}
| .subA n => {t with ax := (s.ax + 4294967296 - n)%4294967296}
| .cmpA n => {t with l := s.ax, r := n}
| .cmpD n => {t with l := s.dx, r := n}
| .cmpDC => {t with l := s.dx, r := s.r8}
| .cmpByte n => {t with l := byteAt s.memory, r := n}
| .jump cc target =>
let taken := match cc with
| .above => decide (s.r < s.l)
| .below => decide (s.l < s.r)
| .ne => decide (s.l ≠ s.r)
{t with ip := if taken then target else next}
| .lea5 => {t with dx := (s.dx+4*s.dx)%W}
| .lea2 => {t with dx := (s.ax+2*s.dx)%W}
| .incPtr => {t with memory := s.memory.tail}
| .movAD => {t with ax := s.dx}
| .ret => s
/-- Finite execution under the ABI; RET observes RAX and returns to the caller. -/
inductive Returns : CPU → Nat → Prop where
| done {s next} : fetch s.ip = some (.ret,next) → Returns s s.ax
| step {s op next v} : fetch s.ip = some (op,next) → op ≠ .ret →
Returns (exec s next op) v → Returns s v
/- Encode one decoded instruction per proof step. The simplifier reduces only
the current instruction's effects; the target address is computed by decode. -/
local macro "ins" : tactic => `(tactic|
(apply Returns.step (by rfl) (by intro h; cases h); dsimp only [exec]))
local macro "finishRet" : tactic => `(tactic| exact Returns.done (by rfl))
private theorem bad (m : List Byte) (a d c l r : Nat) :
Returns ⟨64,m,a,d,c,l,r⟩ 0 := by
ins; finishRet
private theorem tail (m : List Byte) (a d l r : Nat) (hd : d < W) :
Returns ⟨51,m,a,d,cutoff,l,r⟩ (admit (some d)) := by
ins; ins
by_cases h : d < 32768
· simp [le4, rel, h, admit, Nat.not_le_of_lt h]; apply bad
· simp [le4, rel, h, admit, Nat.le_of_not_gt h, hd]; ins; finishRet
private theorem consume (m : List Byte) (b : Byte) (a l r : Nat)
(h : 10*a+digit b < W)
(next : ∀ c cs, m = c::cs →
Returns ⟨12,m,digit b,10*a+digit b,cutoff,byteAt m,0⟩
(admit (decimal (10*a+digit b) m))) (hm : ∀ v ∈ m, v.val ≠ 0) :
Returns ⟨35,b::m,digit b,a,cutoff,l,r⟩ (admit (decimal (10*a+digit b) m)) := by
ins; ins; ins; ins; ins
rw [leas a (digit b) h]
cases m with
| nil =>
simp only [List.tail_cons, byteAt, ne_eq, not_true_eq_false, decide_false,
Bool.false_eq_true, ↓reduceIte, decimal]
apply tail _ _ _ _ _ h
| cons c cs =>
have hc : c.val ≠ 0 := hm c (by simp)
simp [byteAt, hc]
exact next c cs rfl
private theorem loop (m : List Byte) (a v l r : Nat) (hm : ∀ b ∈ m, b.val ≠ 0)
(empty : m = [] → a = 0) :
Returns ⟨12,m,v,a,cutoff,l,r⟩ (admit (decimal a m)) := by
induction m generalizing a v l r with
| nil =>
have ha := empty rfl
subst a
ins; ins; ins; ins
apply bad
| cons b m ih =>
ins; ins; ins; ins
change Returns ⟨if decide (9 < digit b) then 64 else 23, b::m, digit b,
a, cutoff, digit b, 9⟩ (admit (decimal a (b::m)))
by_cases hbad : 9 < digit b
· have hn : ¬(48 ≤ b.val ∧ b.val ≤ 57) := fun h => (Nat.not_le_of_gt hbad) ((digit_ok b).mpr h)
simp [hbad, decimal, hn, admit]
apply bad
· have hd : digit b ≤ 9 := by omega
have valid := (digit_ok b).mp hd
simp only [hbad, decide_false, Bool.false_eq_true, ↓reduceIte, decimal, valid, ↓reduceDIte]
rw [← digit_val b hd]
have step (h : 10*a+digit b < W) (ll rr : Nat) :
Returns ⟨35,b::m,digit b,a,cutoff,ll,rr⟩ (admit (decimal (10*a+digit b) m)) := by
apply consume m b a ll rr h
· intro c cs hs
apply ih
· intro v hv; exact hm v (by simp [hv])
· intro he; simp [he] at hs
· intro v hv; exact hm v (by simp [hv])
ins; ins
by_cases overflow : cutoff < a
· have big : W ≤ 10*a+digit b := by dsimp [W,cutoff] at *; omega
simp [overflow, rel, above m _ big]; apply bad
· simp [overflow, rel]; ins
by_cases small : a < cutoff
· simp [small, rel]
exact step ((guard _ _ hd).mp (Or.inl small)) _ _
· have heq : a = cutoff := by omega
simp [small, rel]; ins; ins
by_cases large : 5 < digit b
· have big : W ≤ 10*a+digit b := by dsimp [W,cutoff] at *; omega
simp [large, rel, above m _ big]; apply bad
· simp [large, rel]
exact step ((guard _ _ hd).mp (Or.inr ⟨heq, Nat.le_of_not_gt large⟩)) _ _
/-- Every call terminates. For any register contents on entry, it returns zero
for malformed, too-small, or overflowing strings, and their exact value for
every other ASCII decimal argv string. -/
theorem parser_correct (m : List Byte) (hm : ∀ b ∈ m, b.val ≠ 0) (ax dx r8 l r : Nat) :
Returns ⟨0,m,ax,dx,r8,l,r⟩ (admit (decimal 0 m)) := by
ins; ins
exact loop m 0 ax l r hm (fun _ => rfl)
theorem admission_iff (value : Option Nat) {n : Nat} (positive : n ≠ 0) :
admit value = n ↔ value = some n ∧ 32768 ≤ n ∧ n < W := by
cases value with
| none => simp [admit, Ne.symm positive]
| some x =>
by_cases hx : 32768 ≤ x ∧ x < W
· simp only [admit, hx, ↓reduceIte, Option.some.injEq]
constructor
· rintro rfl; exact ⟨rfl,hx⟩
· exact And.left
· simp only [admit, hx, ↓reduceIte, Option.some.injEq]
constructor
· intro h; exact False.elim (positive h.symm)
· rintro ⟨rfl,h⟩; exact False.elim (hx h)
def asciiBytes (s : String) : List Byte :=
s.toList.map fun c => ⟨c.toNat%256, Nat.mod_lt _ (by decide)⟩
example : admit (decimal 0 (asciiBytes "18446744073709551615")) = W-1 := by decide
example : admit (decimal 0 (asciiBytes "18446744073709551616")) = 0 := by decide
/-- MUL's unsigned high half and the two right shifts in the /100 loop. -/
theorem divide100 (n : Nat) (hw : n < W) :
(n/4*2951479051793528259/W)/4 = n/100 := by
dsimp [W] at *
omega
def two (n : Nat) := [48+n/10, 48+n%10]
def readDigits (a : Nat) : List Nat → Option Nat
| [] => some a
| b::bs => if 48 ≤ b ∧ b ≤ 57 then readDigits (10*a+(b-48)) bs else none
private theorem read_two (a n : Nat) (h : n < 100) :
readDigits a (two n) = some (100*a+n) := by
have h₁ : 48+n/10 ≤ 57 := by omega
have h₂ : 48+n%10 ≤ 57 := by omega
simp [two, readDigits, h₁, h₂]
omega
private theorem read_append (a : Nat) (xs ys : List Nat) :
readDigits a (xs++ys) = (readDigits a xs).bind (fun b => readDigits b ys) := by
induction xs generalizing a with
| nil => rfl
| cons b bs ih =>
simp only [List.cons_append, readDigits]
split
· exact ih _
· rfl
/-- The variable-width (left of the point) digit-pair loop. -/
def wholeDigits (n : Nat) : List Nat :=
if n < 10 then [48+n]
else if n < 100 then two n
else wholeDigits (n/100) ++ two (n%100)
termination_by n
decreasing_by omega
theorem whole_roundtrip (n : Nat) : readDigits 0 (wholeDigits n) = some n := by
induction n using Nat.strongRecOn with
| ind n ih =>
rw [wholeDigits]
split
· rename_i h
have hn : 48+n ≤ 57 := by omega
simp [readDigits,hn]; omega
· split
· rename_i h; simpa using read_two 0 n h
· rename_i h
have hn : n/100 < n := by omega
rw [read_append, ih _ hn, Option.some_bind, read_two _ _ (Nat.mod_lt _ (by decide))]
congr 1; omega
/-- The whole part has no redundant leading zeroes. -/
theorem whole_leading (n : Nat) : ∃ b rest, wholeDigits n = b::rest ∧
48 ≤ b ∧ b ≤ 57 ∧ (b = 48 ↔ n = 0) := by
induction n using Nat.strongRecOn with
| ind n ih =>
rw [wholeDigits]
split
· rename_i h
exact ⟨48+n, [], rfl, by omega, by omega, by omega⟩
· rename_i ha
split
· rename_i hb
exact ⟨48+n/10, [48+n%10], rfl, by omega, by omega, by omega⟩
· rename_i hb
obtain ⟨b, rest, eq, lo, hi, lead⟩ := ih (n/100) (by omega)
exact ⟨b, rest++two (n%100), by rw [eq]; rfl, lo, hi, by omega⟩
/-- Each pair emitted before the decimal point is inserted contributes
exactly two fractional digits, even when the pair begins with a zero. -/
def splitFraction (n : Nat) : Nat → Nat × List Nat
| 0 => (n, [])
| k+1 =>
let qr := splitFraction (n/100) k
(qr.1, qr.2 ++ two (n%100))
theorem fixed_roundtrip (n k : Nat) :
let qr := splitFraction n k
qr.2.length = 2*k ∧ readDigits 0 (wholeDigits qr.1 ++ qr.2) = some n := by
induction k generalizing n with
| zero => simp [splitFraction,whole_roundtrip]
| succ k ih =>
let qr := splitFraction (n/100) k
have ⟨len, val⟩ := ih (n/100)
change qr.2.length = _ at len
change readDigits _ (wholeDigits qr.1 ++ qr.2) = _ at val
change (qr.2 ++ two (n%100)).length = _ ∧ readDigits _ (wholeDigits qr.1 ++ (qr.2 ++ two (n%100))) = _
constructor
· simp [two, len]; omega
· rw [← List.append_assoc, read_append, val, Option.some_bind, read_two _ _ (Nat.mod_lt _ (by decide))]
congr 1; omega
end Problem14.CLI
~~~
#### `asmproof/CheckedOutput.lean`
~~~lean
import asmproof.GameMachinePrice
namespace P14CheckedOutput
open P14Quote
private theorem halfUp {v : ℝ} (hv : 0≤v) :
let c : ℕ := ⌊100*v+1/2⌋₊
(c:ℝ)-1/2 ≤ 100*v ∧ 100*v ≤ (c:ℝ)+1/2 := by
have h := Nat.floor_le (by positivity : (0:ℝ)≤100*v+1/2)
have h' := Nat.lt_floor_add_one (100*v+1/2)
dsimp only
constructor <;> linarith only [h,h']
def line0 : Record := ⟨133787000, 6038215406, 6038218246, 603822, 603822, true⟩
def hint0 : Witness := ⟨49678310653537, 49678310746368, 2827⟩
theorem verified0 : line0.Check hint0 := by decide
def endpoints0 := @Record.exactEndpoints _ _ verified0
def cents0 := @Record.encloses _ _ verified0
def realPrice0 := @Record.realPrice _ _ verified0
theorem gameDollars0 : (6038215406:ℝ)/10^6 ≤ Problem14.GameComparison.price 133787000 ∧
Problem14.GameComparison.price 133787000 ≤ (6038218246:ℝ)/10^6 := by
have h := P14Entry.printed_game verified0
exact ⟨h.1,h.2.1⟩
def allNearest0 := (P14Entry.printed_game verified0).2.2
theorem roundedCents0 : ⌊100*(Problem14.GameComparison.price 133787000)+1/2⌋₊ = 603822 := by
have lower := gameDollars0.1
have pos : 0 ≤ Problem14.GameComparison.price 133787000 := le_trans (by positivity) lower
obtain ⟨hl,hu⟩ := halfUp pos
have out := allNearest0 _ hl hu
exact out.2 rfl
def line1 : Record := ⟨500000000, 11673115131, 11673117310, 1167312, 1167312, true⟩
def hint1 : Witness := ⟨96038388349944, 96038388397963, 2172⟩
theorem verified1 : line1.Check hint1 := by decide
def endpoints1 := @Record.exactEndpoints _ _ verified1
def cents1 := @Record.encloses _ _ verified1
def realPrice1 := @Record.realPrice _ _ verified1
theorem gameDollars1 : (11673115131:ℝ)/10^6 ≤ Problem14.GameComparison.price 500000000 ∧
Problem14.GameComparison.price 500000000 ≤ (11673117310:ℝ)/10^6 := by
have h := P14Entry.printed_game verified1
exact ⟨h.1,h.2.1⟩
def allNearest1 := (P14Entry.printed_game verified1).2.2
theorem roundedCents1 : ⌊100*(Problem14.GameComparison.price 500000000)+1/2⌋₊ = 1167312 := by
have lower := gameDollars1.1
have pos : 0 ≤ Problem14.GameComparison.price 500000000 := le_trans (by positivity) lower
obtain ⟨hl,hu⟩ := halfUp pos
have out := allNearest1 _ hl hu
exact out.2 rfl
def line2 : Record := ⟨1000000000000, 522037675512, 522037675988, 52203768, 52203768, true⟩
def hint2 : Witness := ⟨4294967296000000, 4294967296001073, 475⟩
theorem verified2 : line2.Check hint2 := by decide
def endpoints2 := @Record.exactEndpoints _ _ verified2
def cents2 := @Record.encloses _ _ verified2
def realPrice2 := @Record.realPrice _ _ verified2
theorem gameDollars2 : (522037675512:ℝ)/10^6 ≤ Problem14.GameComparison.price 1000000000000 ∧
Problem14.GameComparison.price 1000000000000 ≤ (522037675988:ℝ)/10^6 := by
have h := P14Entry.printed_game verified2
exact ⟨h.1,h.2.1⟩
def allNearest2 := (P14Entry.printed_game verified2).2.2
theorem roundedCents2 : ⌊100*(Problem14.GameComparison.price 1000000000000)+1/2⌋₊ = 52203768 := by
have lower := gameDollars2.1
have pos : 0 ≤ Problem14.GameComparison.price 1000000000000 := le_trans (by positivity) lower
obtain ⟨hl,hu⟩ := halfUp pos
have out := allNearest2 _ hl hu
exact out.2 rfl
def line3 : Record := ⟨18446744073709551615, 2242134745644524, 2242134745644542, 224213474564, 224213474564, true⟩
def hint3 : Witness := ⟨18446744073709551615, 18446744073709551615, 17⟩
theorem verified3 : line3.Check hint3 := by decide
def endpoints3 := @Record.exactEndpoints _ _ verified3
def cents3 := @Record.encloses _ _ verified3
def realPrice3 := @Record.realPrice _ _ verified3
theorem gameDollars3 : (2242134745644524:ℝ)/10^6 ≤ Problem14.GameComparison.price 18446744073709551615 ∧
Problem14.GameComparison.price 18446744073709551615 ≤ (2242134745644542:ℝ)/10^6 := by
have h := P14Entry.printed_game verified3
exact ⟨h.1,h.2.1⟩
def allNearest3 := (P14Entry.printed_game verified3).2.2
theorem roundedCents3 : ⌊100*(Problem14.GameComparison.price 18446744073709551615)+1/2⌋₊ = 224213474564 := by
have lower := gameDollars3.1
have pos : 0 ≤ Problem14.GameComparison.price 18446744073709551615 := le_trans (by positivity) lower
obtain ⟨hl,hu⟩ := halfUp pos
have out := allNearest3 _ hl hu
exact out.2 rfl
def line4 : Record := ⟨32768, 94484004, 94499635, 9448, 9450, false⟩
def hint4 : Witness := ⟨777472127993, 777478059612, 14909⟩
theorem verified4 : line4.Check hint4 := by decide
def endpoints4 := @Record.exactEndpoints _ _ verified4
def cents4 := @Record.encloses _ _ verified4
def realPrice4 := @Record.realPrice _ _ verified4
theorem gameDollars4 : (94484004:ℝ)/10^6 ≤ Problem14.GameComparison.price 32768 ∧
Problem14.GameComparison.price 32768 ≤ (94499635:ℝ)/10^6 := by
have h := P14Entry.printed_game verified4
exact ⟨h.1,h.2.1⟩
def allNearest4 := (P14Entry.printed_game verified4).2.2
theorem roundedCents4 : 9448 ≤ ⌊100*(Problem14.GameComparison.price 32768)+1/2⌋₊ ∧ ⌊100*(Problem14.GameComparison.price 32768)+1/2⌋₊ ≤ 9450 := by
have lower := gameDollars4.1
have pos : 0 ≤ Problem14.GameComparison.price 32768 := le_trans (by positivity) lower
obtain ⟨hl,hu⟩ := halfUp pos
have out := allNearest4 _ hl hu
exact out.1
end P14CheckedOutput
~~~
#### `asmproof/Coefficient.lean`
~~~lean
import Quote
import Mathlib.Data.Real.Pi.Bounds
import Mathlib.Analysis.SpecificLimits.Normed
import Mathlib.Tactic.Linarith
import Mathlib.Tactic.NormNum
import Mathlib.Tactic.Positivity
import Mathlib.Tactic.FieldSimp
/-! A rational enclosure of the Brownian stopping coefficient from its
convergent power-series equation. Terms are grouped in consecutive even/odd
pairs. All finite numerical comparisons are checked by the Lean kernel. -/
namespace P14Quote.Coefficient
open Finset
def evenDen : ℕ → ℕ
| 0 => 1
| m+1 => (2*m+2)*evenDen m
def oddDen : ℕ → ℕ
| 0 => 1
| m+1 => (2*m+3)*oddDen m
private theorem den_bounds (m : ℕ) : 0 < evenDen m ∧ evenDen m ≤ oddDen m := by
induction m with
| zero => decide
| succ m ih => exact ⟨Nat.mul_pos (by omega) ih.1, Nat.mul_le_mul (by omega) ih.2⟩
def term {R : Type*} [Field R] (a x : R) (m : ℕ) : R :=
(2*(m:R)+1)*a*x^(2*m+2) / (evenDen (m+1):R) +
(2*(m:R)+2)*x^(2*m+3) / (oddDen (m+1):R)
def partialRat (a x : ℚ) (N : ℕ) : ℚ := ∑ m ∈ range N, term a x m
private theorem partial_cast (a x : ℚ) (N : ℕ) :
(partialRat a x N : ℝ) = ∑ m ∈ range N, term (a:ℝ) (x:ℝ) m := by
simp [partialRat,term]
noncomputable def envelope (m : ℕ) : ℝ := (6*(m:ℝ)+4)/(evenDen (m+1):ℝ)
private theorem envelope_step {m : ℕ} (hm : 1 ≤ m) :
envelope (m+1) ≤ envelope m / 2 := by
have hd : (0:ℝ) < evenDen (m+1) := by exact_mod_cast (den_bounds (m+1)).1
have hm' : (1:ℝ) ≤ m := by exact_mod_cast hm
unfold envelope
rw [evenDen.eq_2 (m+1)]
push_cast
have hm2 : (0:ℝ) < 2*((m:ℝ)+1)+2 := by positivity
rw [div_div, div_le_div_iff₀ (mul_pos hm2 hd) (mul_pos hd (by norm_num))]
have h : (6*((m:ℝ)+1)+4)*2 ≤ (6*m+4)*(2*(m+1)+2) := by
nlinarith [sq_nonneg ((m:ℝ)-1)]
nlinarith only [mul_le_mul_of_nonneg_right h hd.le]
private theorem tail_point {a x : ℝ} (ha : 0 ≤ a) (ha' : a ≤ 2) (hx : 0 ≤ x)
(hx' : x ≤ 1) (m : ℕ) : term a x m ≤ envelope m := by
have hd : (0:ℝ) < evenDen (m+1) := by exact_mod_cast (den_bounds (m+1)).1
have hdo : (evenDen (m+1):ℝ) ≤ oddDen (m+1) := by exact_mod_cast (den_bounds (m+1)).2
have h1 : x^(2*m+2) ≤ 1 := pow_le_one₀ hx hx'
have h2 : x^(2*m+3) ≤ 1 := pow_le_one₀ hx hx'
unfold term envelope
have c1 : (2*(m:ℝ)+1)*a*x^(2*m+2) ≤ (2*m+1)*2 := by
calc
_ ≤ (2*(m:ℝ)+1)*a*1 := mul_le_mul_of_nonneg_left h1 (by positivity)
_ ≤ _ := by simpa using (mul_le_mul_of_nonneg_left ha' (by positivity : 0 ≤ 2*(m:ℝ)+1))
have c2 : (2*(m:ℝ)+2)*x^(2*m+3) ≤ 2*m+2 := by simpa using
(mul_le_mul_of_nonneg_left h2 (by positivity : 0 ≤ 2*(m:ℝ)+2))
calc
_ ≤ ((2*(m:ℝ)+1)*2)/(evenDen (m+1):ℝ) +
(2*m+2)/(evenDen (m+1):ℝ) :=
add_le_add (div_le_div_of_nonneg_right c1 hd.le) (div_le_div₀ (by positivity) c2 hd hdo)
_ = _ := by rw [←add_div]; ring
private theorem tail_geom {a x : ℝ} (ha : 0 ≤ a) (ha' : a ≤ 2) (hx : 0 ≤ x)
(hx' : x ≤ 1) (M : ℕ) (hM : 1 ≤ M) (k : ℕ) :
term a x (k+M) ≤ envelope M * (1/2:ℝ)^k := by
apply (tail_point ha ha' hx hx' _).trans
induction k with
| zero => simp
| succ k ih =>
rw [show k+1+M=k+M+1 by omega, pow_succ]
linarith [envelope_step (m:=k+M) (by omega)]
private theorem term_mono {a b x y : ℝ} (ha : 0 ≤ a) (hx : 0 ≤ x)
(hab : a ≤ b) (hxy : x ≤ y) (m : ℕ) : term a x m ≤ term b y m := by
have hb := ha.trans hab
unfold term
gcongr
def aLo : ℚ := 125331413731550025120 / 10^20
def aHi : ℚ := 125331413731550025122 / 10^20
def xLo : ℚ := 83992367569237268955 / 10^20
def xHi : ℚ := 83992367569237268965 / 10^20
def sLo : ℚ := 177245385090551602729 / 10^20
def sHi : ℚ := 177245385090551602731 / 10^20
private theorem pi_bounds :
(aLo:ℝ) ≤ Real.sqrt (Real.pi/2) ∧ Real.sqrt (Real.pi/2) ≤ aHi ∧
(sLo:ℝ) ≤ Real.sqrt Real.pi ∧ Real.sqrt Real.pi ≤ sHi := by
have p := Real.pi_gt_d20
have q := Real.pi_lt_d20
refine ⟨Real.le_sqrt_of_sq_le ?_, Real.sqrt_le_iff.mpr ⟨by norm_num [aHi],?_⟩,
Real.le_sqrt_of_sq_le ?_, Real.sqrt_le_iff.mpr ⟨by norm_num [sHi],?_⟩⟩
all_goals norm_num [aLo,aHi,sLo,sHi]; linarith
private theorem tail_bound {a x : ℝ} (h : Summable (term a x)) (ha : 0 ≤ a)
(ha' : a ≤ 2) (hx : 0 ≤ x) (hx' : x ≤ 1) :
∑' k, term a x (k+22) ≤ 2*envelope 22 := by
have series := (hasSum_geometric_of_lt_one (by norm_num : (0:ℝ) ≤ 1/2)
(by norm_num : (1/2:ℝ) < 1)).mul_left (envelope 22)
have u := Summable.tsum_le_tsum (tail_geom ha ha' hx hx' 22 (by decide))
((summable_nat_add_iff 22).mpr h) series.summable
rw [series.tsum_eq] at u
nlinarith
set_option maxRecDepth 10000 in
private theorem low_sign :
partialRat aHi xLo 22 + 2*((6*22+4)/(evenDen 23:ℚ)) < aLo := by decide +kernel
set_option maxRecDepth 10000 in
private theorem high_sign : aHi < partialRat aLo xHi 22 := by decide +kernel
/-- Every root of the positive grouped series lies in this rational bracket. -/
theorem series_root_bounds {x : ℝ} (hx : 0 ≤ x) (hx' : x ≤ 1)
(root : HasSum (term (Real.sqrt (Real.pi/2)) x) (Real.sqrt (Real.pi/2))) :
(xLo:ℝ) ≤ x ∧ x ≤ xHi := by
obtain ⟨al,au,_,_⟩ := pi_bounds
let a := Real.sqrt (Real.pi/2)
have ha : 0 ≤ a := Real.sqrt_nonneg _
have ha' : a ≤ 2 := au.trans (by norm_num [aHi])
have lower : (xLo:ℝ) ≤ x := by
by_contra! small
have cmp := sum_le_sum (s:=range 22) (f:=term a x)
(g:=term (aHi:ℝ) (xLo:ℝ)) (fun i _ => term_mono ha hx au small.le i)
rw [←partial_cast] at cmp
have tail := tail_bound root.summable ha ha' hx hx'
have split := root.summable.sum_add_tsum_nat_add 22
rw [root.tsum_eq] at split
have cert : (partialRat aHi xLo 22 : ℝ) +
2*((6*22+4)/(evenDen 23:ℝ)) < aLo := by
have h := (Rat.cast_lt (K:=ℝ)).mpr low_sign
push_cast at h
norm_num at h ⊢
exact h
change ∑ i ∈ range 22, term a x i + ∑' k, term a x (k+22) = a at split
change (aLo:ℝ) ≤ a at al
unfold envelope at tail
linarith
have upper : x ≤ xHi := by
by_contra hsmall
have big := lt_of_not_ge hsmall
have cmp := sum_le_sum (s:=range 22) (f:=term (aLo:ℝ) (xHi:ℝ)) (g:=term a x)
(fun i _ => term_mono (by norm_num [aLo]) (by norm_num [xHi]) al big.le i)
rw [←partial_cast] at cmp
have finite := sum_le_hasSum (range 22) (fun i _ => by unfold term; positivity) root
have cert : (aHi:ℝ) < partialRat aLo xHi 22 := by exact_mod_cast high_sign
change a ≤ (aHi:ℝ) at au
change ∑ i ∈ range 22, term a x i ≤ a at finite
linarith
exact ⟨lower,upper⟩
/-- Multiplying the classical Taylor expansion of A by (1−x²), removing
the constant term and the canceled linear term, gives this positive
series equation at the Brownian root. It uniquely brackets the root and
certifies the integer coefficient used in quote.S. -/
theorem series_coefficient {x : ℝ} (hx : 0 ≤ x) (hx' : x ≤ 1)
(root : HasSum (term (Real.sqrt (Real.pi/2)) x) (Real.sqrt (Real.pi/2))) :
(coefficient:ℝ)/10^18 ≤ (1-x^2)*Real.sqrt Real.pi ∧
(1-x^2)*Real.sqrt Real.pi ≤ ((coefficient:ℝ)+1)/10^18 := by
obtain ⟨_,_,sl,su⟩ := pi_bounds
obtain ⟨lower,upper⟩ := series_root_bounds hx hx' root
have hxhi : x^2 ≤ (xHi:ℝ)^2 := pow_le_pow_left₀ hx upper _
have hxlo : (xLo:ℝ)^2 ≤ x^2 := pow_le_pow_left₀ (by norm_num [xLo]) lower _
have nonneg : 0 ≤ 1-x^2 := by nlinarith [mul_nonneg hx (sub_nonneg.mpr hx')]
have lowproduct := mul_le_mul (sub_le_sub_left hxhi 1) sl (by norm_num [sLo]) nonneg
have hiproduct := mul_le_mul (sub_le_sub_left hxlo 1) su (Real.sqrt_nonneg _) (by norm_num [xLo])
constructor
· exact (show (coefficient:ℝ)/10^18 ≤ (1-(xHi:ℝ)^2)*sLo by norm_num [coefficient,xHi,sLo]).trans lowproduct
· exact hiproduct.trans (by norm_num [coefficient,xLo,sHi])
/-- The even and odd Taylor terms of the classical function A. -/
noncomputable def pair (a x : ℝ) (m : ℕ) :=
a*x^(2*m)/(evenDen m:ℝ) + x^(2*m+1)/(oddDen m:ℝ)
private theorem pair_shift (a x : ℝ) (m : ℕ) :
x^2*pair a x m - pair a x (m+1) = term a x m := by
have he : (0:ℝ) < evenDen m := by exact_mod_cast (den_bounds m).1
have ho : (0:ℝ) < oddDen m := by exact_mod_cast (den_bounds m).1.trans_le (den_bounds m).2
unfold pair term
rw [evenDen.eq_2,oddDen.eq_2]
push_cast
rw [show 2*(m+1)=2*m+2 by omega, show 2*m+2+1=2*m+3 by omega]
rw [pow_add x (2*m) 2, pow_add x (2*m) 1, pow_add x (2*m) 3]
field_simp [ne_of_gt (by positivity : 0 < 2*(m:ℝ)+2),
ne_of_gt (by positivity : 0 < 2*(m:ℝ)+3)]
ring
theorem taylor_root_equation {x A : ℝ}
(taylor : HasSum (pair (Real.sqrt (Real.pi/2)) x) A)
(root : (1-x^2)*A = x) :
HasSum (term (Real.sqrt (Real.pi/2)) x) (Real.sqrt (Real.pi/2)) := by
have tail := (hasSum_nat_add_iff' 1).mpr taylor
have diff := (taylor.mul_left (x^2)).sub tail
simp only [pair_shift] at diff
convert diff using 1
simp [pair,evenDen,oddDen]
linarith
/-- The standard Brownian root equation, with A given by its even/odd Taylor
series, implies the bracket without presupposing any digits of alpha. -/
theorem taylor_coefficient {x A : ℝ} (hx : 0 ≤ x) (hx' : x ≤ 1)
(taylor : HasSum (pair (Real.sqrt (Real.pi/2)) x) A)
(root : (1-x^2)*A = x) :
(coefficient:ℝ)/10^18 ≤ (1-x^2)*Real.sqrt Real.pi ∧
(1-x^2)*Real.sqrt Real.pi ≤ ((coefficient:ℝ)+1)/10^18 := by
exact series_coefficient hx hx' (taylor_root_equation taylor root)
end P14Quote.Coefficient
~~~
#### `asmproof/DebitBytes.lean`
~~~lean
import X86Debit
/-! Decoder and execution of the whole linked threshold lookup. The linker
resolves the four bytes of the RIP-relative LEA. check_debit.py verifies
that its effective address is the first threshold address minus 17*8. -/
namespace P14Debit.X86
set_option maxRecDepth 16384
set_option maxHeartbeats 3000000
def codeHead : List Nat := [184,17,0,0,0,57,198,15,67,198,186,61,58,0,0,57,208,15,71,194,72,141,13]
def codeTail : List Nat := [72,59,60,193,115,9,255,192,72,59,60,193,114,248,195,131,248,17,
116,11,72,59,124,193,248,114,4,255,200,235,240,195]
def code (a b c d : Nat) := codeHead ++ [a,b,c,d] ++ codeTail
inductive Op where
| minVal | cmpMin | cmovae | maxVal | cmpMax | cmova | lea | cmpHere | jae | inc
| jbUp | ret | cmp17 | je | cmpPrev | jbDone | dec | jmp
deriving DecidableEq
def readOp : List Nat → Option Op
| 184::17::0::0::0::_ => some .minVal
| 57::198::_ => some .cmpMin
| 15::67::198::_ => some .cmovae
| 186::61::58::0::0::_ => some .maxVal
| 57::208::_ => some .cmpMax
| 15::71::194::_ => some .cmova
| 72::141::13::_::_::_::_::_ => some .lea
| 72::59::60::193::_ => some .cmpHere
| 115::9::_ => some .jae
| 255::192::_ => some .inc
| 114::248::_ => some .jbUp
| 195::_ => some .ret
| 131::248::17::_ => some .cmp17
| 116::11::_ => some .je
| 72::59::124::193::248::_ => some .cmpPrev
| 114::4::_ => some .jbDone
| 255::200::_ => some .dec
| 235::240::_ => some .jmp
| _ => none
def starts : List Nat := [0,5,7,10,15,17,20,27,31,33,35,39,41,42,45,47,52,54,56,58]
def execOp (n hint : Nat) (mem : Table) (s : State) : Op → State
| .minVal => {s with ax:=17, pc:=s.pc+5}
| .cmpMin => {s with cf:=decide (hint {s with ax:=if !s.cf then hint else s.ax, pc:=s.pc+3}
| .maxVal => {s with dx:=14909, pc:=s.pc+5}
| .cmpMax => {s with cf:=decide (s.ax {s with ax:=if !s.cf && !s.zf then s.dx else s.ax, pc:=s.pc+3}
| .lea => {s with ptr:=true,pc:=s.pc+7}
| .cmpHere => if s.ptr then {s with cf:=decide (n {s with pc:=if s.cf then s.pc+2 else s.pc+2+9}
| .inc => {s with ax:=(s.ax+1)%2^32, pc:=s.pc+2}
| .jbUp => {s with pc:=if s.cf then s.pc+2-8 else s.pc+2}
| .ret => s
| .cmp17 => {s with cf:=decide (s.ax<17), zf:=decide (s.ax=17),pc:=s.pc+3}
| .je => {s with pc:=if s.zf then s.pc+2+11 else s.pc+2}
| .cmpPrev => if s.ptr then
{s with cf:=decide (n {s with pc:=if s.cf then s.pc+2+4 else s.pc+2}
| .dec => {s with ax:=(s.ax+2^32-1)%2^32,pc:=s.pc+2}
| .jmp => {s with pc:=s.pc+2-16}
def fetched (bin : List Nat) (n hint : Nat) (mem : Table) (s : State) :=
if s.pc ∈ starts then
match readOp (bin.drop s.pc) with
| some op => execOp n hint mem s op
| none => {s with pc:=255}
else s
private theorem read0 (a b c d : Nat) : readOp ((code a b c d).drop 0) = some .minVal := rfl
private theorem read5 (a b c d : Nat) : readOp ((code a b c d).drop 5) = some .cmpMin := rfl
private theorem read7 (a b c d : Nat) : readOp ((code a b c d).drop 7) = some .cmovae := rfl
private theorem read10 (a b c d : Nat) : readOp ((code a b c d).drop 10) = some .maxVal := rfl
private theorem read15 (a b c d : Nat) : readOp ((code a b c d).drop 15) = some .cmpMax := rfl
private theorem read17 (a b c d : Nat) : readOp ((code a b c d).drop 17) = some .cmova := rfl
private theorem read20 (a b c d : Nat) : readOp ((code a b c d).drop 20) = some .lea := rfl
private theorem read27 (a b c d : Nat) : readOp ((code a b c d).drop 27) = some .cmpHere := rfl
private theorem read31 (a b c d : Nat) : readOp ((code a b c d).drop 31) = some .jae := rfl
private theorem read33 (a b c d : Nat) : readOp ((code a b c d).drop 33) = some .inc := rfl
private theorem read35 (a b c d : Nat) : readOp ((code a b c d).drop 35) = some .cmpHere := rfl
private theorem read39 (a b c d : Nat) : readOp ((code a b c d).drop 39) = some .jbUp := rfl
private theorem read41 (a b c d : Nat) : readOp ((code a b c d).drop 41) = some .ret := rfl
private theorem read42 (a b c d : Nat) : readOp ((code a b c d).drop 42) = some .cmp17 := rfl
private theorem read45 (a b c d : Nat) : readOp ((code a b c d).drop 45) = some .je := rfl
private theorem read47 (a b c d : Nat) : readOp ((code a b c d).drop 47) = some .cmpPrev := rfl
private theorem read52 (a b c d : Nat) : readOp ((code a b c d).drop 52) = some .jbDone := rfl
private theorem read54 (a b c d : Nat) : readOp ((code a b c d).drop 54) = some .dec := rfl
private theorem read56 (a b c d : Nat) : readOp ((code a b c d).drop 56) = some .jmp := rfl
private theorem read58 (a b c d : Nat) : readOp ((code a b c d).drop 58) = some .ret := rfl
theorem fetch_agrees (a b c d n hint : Nat) (m : Table) :
fetched (code a b c d) n hint m = step n hint m := by
funext s
by_cases h : s.pc ∈ starts
· rw [fetched,if_pos h]
simp [starts] at h
rcases h with h|h|h|h|h|h|h|h|h|h|h|h|h|h|h|h|h|h|h|h
· rw [h,read0]; simp only [step,execOp,h] <;> rfl
· rw [h,read5]; simp only [step,execOp,h] <;> rfl
· rw [h,read7]; simp only [step,execOp,h] <;> rfl
· rw [h,read10]; simp only [step,execOp,h] <;> rfl
· rw [h,read15]; simp only [step,execOp,h] <;> rfl
· rw [h,read17]; simp only [step,execOp,h] <;> rfl
· rw [h,read20]; simp only [step,execOp,h] <;> rfl
· rw [h,read27]; simp only [step,execOp,h] <;> rfl
· rw [h,read31]; simp only [step,execOp,h] <;> rfl
· rw [h,read33]; simp only [step,execOp,h] <;> rfl
· rw [h,read35]; simp only [step,execOp,h] <;> rfl
· rw [h,read39]; simp only [step,execOp,h] <;> rfl
· rw [h,read41]; simp only [step,execOp,h] <;> rfl
· rw [h,read42]; simp only [step,execOp,h] <;> rfl
· rw [h,read45]; simp only [step,execOp,h] <;> rfl
· rw [h,read47]; simp only [step,execOp,h] <;> rfl
· rw [h,read52]; simp only [step,execOp,h] <;> rfl
· rw [h,read54]; simp only [step,execOp,h] <;> rfl
· rw [h,read56]; simp only [step,execOp,h] <;> rfl
· rw [h,read58]; simp only [step,execOp,h] <;> rfl
· rw [fetched,if_neg h]
simp [starts] at h
unfold step
split <;> first | rfl | omega
theorem fetched_correct (a b c d n hint : Nat) (mem : Table) (hm : tableOK mem)
(lo : 32768 ≤ n) (hi : n < 2^64) (s : State) (start : s.pc=0) :
∃ t, Reaches (fetched (code a b c d) n hint mem) s t ∧ success n t := by
rw [fetch_agrees]
exact correct hm lo hi s start
end P14Debit.X86
~~~
#### `asmproof/DebitTable.lean`
~~~lean
import Quote
namespace P14Debit
open P14Quote
def threshold (d : Nat) : Nat := ((debitPower-1) / d^5 + 1) / 2
theorem threshold_iff {d n : Nat} (hd : 0 < d) :
threshold d ≤ n ↔ debitPower ≤ d^5 * divisor n := by
have pos : 0 < d^5 := Nat.pow_pos hd
have powpos : 0 < debitPower := by decide
unfold threshold divisor
have h := Nat.div_lt_iff_lt_mul pos (x := debitPower-1) (y := 2*n+1)
rw [Nat.mul_comm (2*n+1) _] at h
omega
theorem threshold_anti {a b : Nat} (ha : 0 < a) (hab : a ≤ b) :
threshold b ≤ threshold a := by
apply (threshold_iff (Nat.lt_of_lt_of_le ha hab)).2
have hx := (threshold_iff (n := threshold a) ha).1 (Nat.le_refl _)
exact Nat.le_trans hx (Nat.mul_le_mul_right _ (Nat.pow_le_pow_left hab 5))
theorem last_fits {n : Nat} (h : 32768 ≤ n) : threshold 14909 ≤ n :=
Nat.le_trans (by decide : threshold 14909 ≤ 32768) h
theorem before_first_fails {n : Nat} (h : n < 2^64) : n < threshold 16 :=
Nat.lt_of_lt_of_le h (by decide)
theorem fits_word {i : Nat} (h : 17 ≤ i) : threshold i < 2^64 :=
Nat.lt_of_le_of_lt (threshold_anti (by decide : 0 < 17) h) (by decide)
theorem neighbors {n d : Nat} (h : 17 ≤ d) (yes : threshold d ≤ n)
(no : n < threshold (d-1)) : DebitSpec n d := by
apply debit_of_neighbors (by omega)
· exact (threshold_iff (by omega)).1 yes
· apply Nat.lt_of_not_ge
intro contra
exact (Nat.not_le_of_gt no) ((threshold_iff (by omega)).2 contra)
theorem first_success {n : Nat} (yes : threshold 17 ≤ n) (hn : n < 2^64) :
DebitSpec n 17 := neighbors (by decide) yes (before_first_fails hn)
end P14Debit
~~~
#### `asmproof/Game65536.lean`
~~~lean
import asmproof.GameLowerPrice
import asmproof.GameLayer
/-! Replay the full, attainable finite layer and exact signed comparison.
The theorem 'verified' uses Lean's native_decide (compiler trust); all
symbolic identities and the soundness of its test are kernel proofs. -/
namespace Problem14.Game65536
open GameCalibration GameLowerPrice
open P14Quote.Coefficient
def check := let row := GameLayer.finalRow
test (GameLayer.lookup row)
theorem verified : check = true := by native_decide
theorem attainable : Attainable GameLayer.finalPrice := by
intro n r b h hr _; exact GameLayer.finalPrice_lower n r b h hr
theorem tested : test GameLayer.finalPrice = true := verified
/-- At every balanced deck from 65,536 total cards onwards, the finite
cutoff is fully checked. GameExercise.threshold_contact supplies the
exercise inequality at the unique Brownian threshold. -/
theorem lower_price (a : ℝ) (ha : 0≤a) (hu : a≤1)
(root : HasSum (term (Real.sqrt (Real.pi/2)) a) (Real.sqrt (Real.pi/2)))
(contact : Contact a) (n : ℕ) (hn : 32768≤n) :
(1-a^2)*Real.sqrt Real.pi*Real.sqrt n -
(137/1000)/(2*(n:ℝ)+1)^((1:ℝ)/5) ≤ GameComparison.price n :=
lower_from_table GameLayer.finalPrice attainable tested a ha hu root contact n hn
end Problem14.Game65536
~~~
#### `asmproof/GameBeta.lean`
~~~lean
import Mathlib.MeasureTheory.Integral.IntervalIntegral.FundThmCalculus
import Mathlib.Analysis.Calculus.Deriv.Pow
import Mathlib.Data.Nat.Choose.Basic
import Mathlib.MeasureTheory.Function.Jacobian
import Mathlib.Analysis.SpecialFunctions.Trigonometric.Deriv
import Mathlib.Analysis.SpecialFunctions.Log.Basic
import Mathlib.Tactic.Ring
import Mathlib.Tactic.Linarith
import Mathlib.Tactic.FieldSimp
import Mathlib.Tactic.FunProp
/-! The binomial mid-CDF divided by the mass at the same site, as a
polynomial beta integral. The half-weight is on the site k itself. -/
namespace Problem14.BinomialBeta
open MeasureTheory
open scoped BigOperators Interval
noncomputable def kernel (a b : ℕ) (u : ℝ) := (1-u)^a * (1+u)^b
noncomputable def beta (a b : ℕ) : ℝ := ∫ u in (0:ℝ)..1, kernel a b u
private theorem kernel_continuous (a b : ℕ) : Continuous (kernel a b) := by
unfold kernel
fun_prop
private theorem beta_base (a : ℕ) : ((a:ℝ)+1)*beta a 0 = 1 := by
have deriv (u : ℝ) : HasDerivAt (fun v : ℝ => (1-v)^(a+1))
(-((a:ℝ)+1) * kernel a 0 u) u := by
convert (((hasDerivAt_const u (1:ℝ)).sub (hasDerivAt_id u)).pow (a+1)) using 1;
simp [kernel]; ring
have h := intervalIntegral.integral_eq_sub_of_hasDerivAt
(a := (0:ℝ)) (b := 1) (fun u _ => deriv u)
((continuous_const.mul (kernel_continuous a 0)).intervalIntegrable _ _)
rw [intervalIntegral.integral_const_mul] at h
change (-((a:ℝ)+1))*beta a 0 = _ at h
simp at h
linarith
private theorem beta_step (a b : ℕ) :
((a:ℝ)+1)*beta a (b+1) = 1 + ((b:ℝ)+1)*beta (a+1) b := by
have deriv (u : ℝ) : HasDerivAt (kernel (a+1) (b+1))
(((b:ℝ)+1)*kernel (a+1) b u - ((a:ℝ)+1)*kernel a (b+1) u) u := by
convert ((((hasDerivAt_const u (1:ℝ)).sub (hasDerivAt_id u)).pow (a+1)).mul
(((hasDerivAt_const u (1:ℝ)).add (hasDerivAt_id u)).pow (b+1))) using 1;
simp [kernel]; ring
have c₁ : Continuous (fun u => ((b:ℝ)+1)*kernel (a+1) b u) :=
continuous_const.mul (kernel_continuous _ _)
have c₂ : Continuous (fun u => ((a:ℝ)+1)*kernel a (b+1) u) :=
continuous_const.mul (kernel_continuous _ _)
have h := intervalIntegral.integral_eq_sub_of_hasDerivAt
(a := (0:ℝ)) (b := 1) (fun u _ => deriv u) ((c₁.sub c₂).intervalIntegrable _ _)
rw [intervalIntegral.integral_sub (c₁.intervalIntegrable _ _) (c₂.intervalIntegrable _ _),
intervalIntegral.integral_const_mul, intervalIntegral.integral_const_mul] at h
change _ * beta (a+1) b - _ * beta a (b+1) = _ at h
simp [kernel] at h
linarith
private theorem weighted (t b : ℕ) (h : b
simp only [Nat.cast_zero, zero_add, mul_one, Nat.choose_one_right,
Finset.sum_range_one, Nat.choose_zero_right, Nat.cast_one]
have h' : t-1+1=t := by omega
have eq : ((t-1:ℕ):ℝ)+1 = t := by exact_mod_cast h'
rw [← eq]
exact beta_base _
| succ b ih =>
let a := t-(b+2)
have ha : a+1=t-(b+1) := by dsimp [a]; omega
have shift : (t.choose (b+2):ℝ)*((b:ℝ)+1+1) =
(t.choose (b+1):ℝ)*((a:ℝ)+1) := by
have e := Nat.choose_succ_right_eq t (b+1)
rw [← ha] at e
exact_mod_cast e
rw [Finset.sum_range_succ (n := b+1), Nat.cast_succ, shift, mul_assoc, beta_step, mul_add, mul_one,
← mul_assoc, ha, ih (by omega)]
ring
noncomputable def mass (t k : ℕ) : ℝ := (t.choose k : ℝ) / 2^t
noncomputable def midCDF (t k : ℕ) : ℝ :=
(∑ i ∈ Finset.range k, (t.choose i : ℝ))/2^t + mass t k/2
/-- For one through t black signs, the mid-binomial CDF divided by the mass
equals one half plus k times the polynomial integral on [0,1]. -/
theorem midCDF_div_mass (t k : ℕ) (hk : 1 ≤ k) (ht : k ≤ t) :
midCDF t k / mass t k =
1/2 + k * ∫ u in (0:ℝ)..1, (1-u)^(t-k) * (1+u)^(k-1) := by
obtain ⟨b,rfl⟩ := Nat.exists_eq_succ_of_ne_zero (by omega : k≠0)
have w := weighted t b (by omega)
have pos : (0:ℝ) < t.choose (b+1) := by exact_mod_cast Nat.choose_pos ht
simp only [midCDF, mass, Nat.succ_eq_add_one, Nat.add_sub_cancel]
rw [← w]
change _ = 1/2 + _ * beta _ _
push_cast
field_simp [ne_of_gt pos]
ring
private theorem d_tanh (v : ℝ) : HasDerivAt Real.tanh (1/(Real.cosh v)^2) v := by
have d := (Real.hasDerivAt_sinh v).div (Real.hasDerivAt_cosh v) (Real.cosh_pos v).ne'
convert d using 1
· funext z; exact Real.tanh_eq_sinh_div_cosh z
· rw [← Real.cosh_sq_sub_sinh_sq v]; ring
private theorem mono_tanh : StrictMono Real.tanh := strictMono_of_deriv_pos (fun v => by
rw [(d_tanh v).deriv]; positivity)
private theorem tanh_factors (v : ℝ) :
1-Real.tanh v = Real.exp (-v) / Real.cosh v ∧
1+Real.tanh v = Real.exp v / Real.cosh v := by
rw [Real.tanh_eq_sinh_div_cosh]
have hc := (Real.cosh_pos v).ne'
constructor
· rw [← Real.cosh_sub_sinh]; field_simp
· rw [← Real.cosh_add_sinh]; field_simp
private theorem tanh_image : Real.tanh '' Set.Ioi (0:ℝ) = Set.Ioo 0 1 := by
ext y
constructor
· rintro ⟨v,hv,rfl⟩
have h := (tanh_factors v).1
have hpos : 0 < Real.exp (-v) / Real.cosh v := by positivity
exact ⟨by simpa using mono_tanh (Set.mem_Ioi.mp hv), by linarith⟩
· rintro ⟨hy,h1⟩
let q := (1+y)/(1-y)
have hq : 1 (d_tanh v).hasDerivWithinAt) mono_tanh.injective.injOn (kernel a b)]
apply setIntegral_congr_fun measurableSet_Ioi
intro v _
dsimp only
rw [abs_of_nonneg (by positivity : 0 ≤ 1/(Real.cosh v)^2), smul_eq_mul]
exact transformed a b v
/-- Writing x=2k−t, the right-hand side has the form used in the
Gaussian comparison, exp((x−1)v−(t+1) log(cosh v)). -/
theorem midCDF_div_mass_laplace (t k : ℕ) (hk : 1 ≤ k) (ht : k ≤ t) :
midCDF t k / mass t k = 1/2 + k *
∫ v in Set.Ioi (0:ℝ), Real.exp ((2*(k:ℝ)-t-1)*v-((t:ℝ)+1)*Real.log (Real.cosh v)) := by
rw [midCDF_div_mass t k hk ht]
change 1/2 + (k:ℝ)*beta (t-k) (k-1) = _
have total : t-k+(k-1)+2 = t+1 := by omega
have exponent : ((k-1:ℕ):ℝ)-((t-k:ℕ):ℝ)=2*(k:ℝ)-t-1 := by
rw [Nat.cast_sub hk,Nat.cast_sub ht]; push_cast; ring
have h := beta_eq_laplace (t-k) (k-1)
rw [total, exponent, Nat.cast_add_one] at h
rw [h]
end Problem14.BinomialBeta
~~~
#### `asmproof/GameCalibration.lean`
~~~lean
import asmproof.GameMoments
/-! An exact integer test for the entire lower cutoff. Multiplication by
5^m m! clears every denominator in the p=2/5 coefficient. This lets a
one-pass integer scan check the signed comparison without floating point
or interval approximations. The 0.58905643803 rational bounds c from above.
-/
namespace Problem14.GameCalibration
open GameComparison GameFractional GameMoments
structure Acc where
mass : ℤ
mid : ℤ
frac : ℤ
prev : ℤ
deriving Repr
def start : Acc := ⟨1,1,1,0⟩
def advance (t m : ℕ) (s : Acc) : Acc :=
let p : ℤ := 5*((t:ℤ)-m)*s.mass
⟨p, 5*((m:ℤ)+1)*(s.mid+s.mass)+p,
(5*(t:ℤ)-4)*s.frac - 25*m*((t:ℤ)-m+1)*s.prev, s.frac⟩
noncomputable def den (m : ℕ) : ℝ := 5^m*(m.factorial : ℝ)
private theorem den_succ (m : ℕ) : den (m+1) = 5*((m:ℝ)+1)*den m := by
simp only [den,pow_succ,Nat.factorial_succ,Nat.cast_mul,Nat.cast_succ]; ring
structure Accurate (t m : ℕ) (s : Acc) : Prop where
mass : (s.mass : ℝ) = den m*(t.choose m : ℝ)
mid : (s.mid : ℝ) = den m*(2*(below t m : ℝ) + (t.choose m : ℝ))
frac : (s.frac : ℝ) = den m*C t m
prev : ∀ j, m=j+1 → (s.prev : ℝ) = den j*C t j
private theorem initial (t : ℕ) : Accurate t 0 start := by
constructor <;> simp [start,den,below,C]
private theorem accurate_next (t m : ℕ) (s : Acc) (h : m≤t) (ok : Accurate t m s) :
Accurate t (m+1) (advance t m s) := by
have bin : ((m:ℝ)+1)*(t.choose (m+1) : ℝ) = ((t:ℝ)-m)*(t.choose m : ℝ) := by
have a := Nat.choose_succ_right_eq t m
rw [←Nat.cast_sub h]
exact_mod_cast (show (m+1)*t.choose (m+1)=(t-m)*t.choose m by rw [Nat.mul_comm, a, Nat.mul_comm])
have pm : ((advance t m s).mass : ℝ) = den (m+1)*(t.choose (m+1) : ℝ) := by
unfold advance; push_cast; rw [ok.mass,den_succ]
linear_combination -5*den m*bin
refine ⟨pm, ?_, ?_, ?_⟩
· change ((5*((m:ℤ)+1)*(s.mid+s.mass)+(advance t m s).mass : ℤ):ℝ) = _
push_cast
rw [pm,ok.mid,ok.mass,den_succ,below.eq_2]
push_cast
ring
· unfold advance
push_cast
cases m with
| zero =>
rw [ok.frac,den_succ]
norm_num [C]
ring
| succ j =>
rw [ok.frac,ok.prev j rfl,den_succ (j+1),den_succ j]
push_cast
have e := coefficient_rec t j
linear_combination -25*((j:ℝ)+1)*den j*e
· intro j hj; have : j=m := by omega
subst j; exact ok.frac
def time : ℕ := 65536
def scale : ℕ := 2^30
def hi : ℤ := 58905643803
def divisor : ℤ := 100000000000
noncomputable def cHi : ℝ := (hi:ℝ)/(divisor:ℝ)
def accepted (low : ℕ) (m : ℕ) (s : Acc) : Bool :=
let t : ℤ := time
let x : ℤ := 2*m-t
let d := t*(t-1)*(t-2)
let odd := -x*(t-1)*(t-2) + 9000*(x^3-(3*t-2)*x)
decide (5*(scale:ℤ)*(hi*d*s.mid + 2*divisor*odd*s.mass) ≤
2*divisor*d*((scale:ℤ)*s.frac + 5*(low:ℤ)*s.mass))
private theorem accepted_sound (m low : ℕ) (s : Acc) (ok : Accurate time m s)
(h : accepted low m s = true) :
H cHi time m ≤ (low:ℝ)*(time.choose m : ℝ)/(scale:ℝ) := by
simp only [accepted, decide_eq_true_eq] at h
have hreal := (Int.cast_le (R:=ℝ)).mpr h
push_cast at hreal
rw [ok.mass,ok.mid,ok.frac] at hreal
rw [formula cHi time m (by decide)]
unfold tilt cHi
have size : 0 < den m := by unfold den; positivity
apply le_of_mul_le_mul_left (a:=den m) _ size
norm_num [time,scale,hi,divisor] at hreal ⊢
linarith only [hreal]
/-- The array lookup must be closed over an already computed terminal row.
Each iteration tests one physical survivor and advances to the next column. -/
def scan (lower : ℕ → ℕ) (m : ℕ) (s : Acc) : ℕ → Bool
| 0 => true
| n+1 => if accepted (lower m) m s then scan lower (m+1) (advance time m s) n else false
private theorem scan_sound (lower : ℕ → ℕ) (m : ℕ) (s : Acc) (q : ℕ) :
Accurate time m s → m+q≤time+1 → scan lower m s q=true →
∀ i, m ≤ i → i < m+q → H cHi time i ≤ (lower i : ℝ)*(time.choose i : ℝ)/(scale : ℝ) := by
induction q generalizing m s with
| zero => intros; omega
| succ q ih =>
intro ok hsz hc i hm he
simp only [scan] at hc
split at hc
next h =>
by_cases hi : i=m
· subst i; exact accepted_sound m _ s ok h
· exact ih _ _ (accurate_next time m s (by omega) ok) (by omega) hc i (by omega) (by omega)
next => contradiction
def test (lower : ℕ → ℕ) := scan lower 0 start 32876
theorem test_sound (lower : ℕ → ℕ) (pass : test lower=true) (m : ℕ) (hm : m≤32875) :
H cHi time m ≤ (lower m : ℝ)*(time.choose m : ℝ)/(scale : ℝ) :=
scan_sound lower 0 start 32876 (initial _) (by decide) pass m (by omega) (by omega)
end Problem14.GameCalibration
~~~
#### `asmproof/GameCentral.lean`
~~~lean
import Std
/-! The central fractional correction and the certified price debit, in
integer arithmetic. At t=2n the beta/coefficent diagonal ratio is
(10n+3)/(10n+5). An exact product through t=38 suffices for the 0.137
constant at every subsequent balanced time. -/
namespace Problem14.GameCentral
def product (k : Nat) : Nat → Nat
| 0 => 1
| n+1 => (10*n+k)*product k n
private theorem bernoulli (a b k : Nat) :
a^k*(a+(k+1)*b) ≤ (a+b)^(k+1) := by
induction k with
| zero => simp
| succ k ih =>
rw [Nat.pow_succ (a+b) (k+1)]
apply Nat.le_trans _ (Nat.mul_le_mul_right (a+b) ih)
rw [Nat.pow_succ a k, Nat.mul_assoc, Nat.mul_assoc]
apply Nat.mul_le_mul_left
simp only [Nat.succ_mul, Nat.mul_add, Nat.add_mul, Nat.mul_one, Nat.zero_mul]
rw [Nat.mul_comm b a, Nat.mul_comm (k*b) a]
omega
private theorem one_step (n : Nat) :
(2*n+3)*(10*n+3)^5 ≤ (2*n+1)*(10*n+5)^5 := by
let a := 10*n+3
have h := bernoulli a 2 4
have hc : (2*n+3)*a ≤ (2*n+1)*(a+5*2) := by
dsimp [a]
simp only [Nat.mul_add, Nat.add_mul, Nat.mul_one, Nat.one_mul, Nat.mul_assoc,
Nat.mul_comm, Nat.mul_left_comm]
omega
calc
(2*n+3)*(10*n+3)^5 = ((2*n+3)*a)*a^4 := by rw [Nat.pow_succ]; dsimp [a]; ac_rfl
_ ≤ ((2*n+1)*(a+5*2))*a^4 := Nat.mul_le_mul_right _ hc
_ = (2*n+1)*(a^4*(a+5*2)) := by ac_rfl
_ ≤ (2*n+1)*(10*n+5)^5 := Nat.mul_le_mul_left _ h
/-- Clearing denominators and taking fifth powers, the expression being
bounded is R_(2n)(0)*(2n+1)^(1/5)/5. Price units are exact (0.137=137/1000). -/
theorem central_debit (n : Nat) (hn : 19 ≤ n) :
200^5 * ((2*n+1)*(product 3 n)^5) ≤ 137^5*(product 5 n)^5 := by
obtain ⟨k, rfl⟩ := Nat.exists_eq_add_of_le hn
induction k with
| zero => decide
| succ k ih =>
let j := 19+k
change 200^5*((2*(j+1)+1)*(product 3 (j+1))^5) ≤ 137^5*(product 5 (j+1))^5
rw [product.eq_2, product.eq_2, Nat.mul_pow, Nat.mul_pow]
have grow := Nat.mul_le_mul_right (200^5*(product 3 j)^5) (one_step j)
have old := Nat.mul_le_mul_right ((10*j+5)^5) (ih (by omega))
calc
_ = ((2*j+3)*(10*j+3)^5)*(200^5*(product 3 j)^5) := by
rw [show 2*(j+1)+1=2*j+3 by omega]; ac_rfl
_ ≤ _ := grow
_ = (200^5*((2*j+1)*(product 3 j)^5))*(10*j+5)^5 := by ac_rfl
_ ≤ _ := old
_ = _ := by change (137^5*(product 5 j)^5)*(10*j+5)^5 = _; ac_rfl
end Problem14.GameCentral
~~~
#### `asmproof/GameComparison.lean`
~~~lean
import asmproof.GameFractional
import asmproof.GameCutoff
import asmproof.GameWallis
import asmproof.UpperCentral
import Mathlib.Data.Real.Sqrt
/-! The concrete lower comparator in signed aggregate dollars. Only two
analytic/numerical inequalities enter the comparison: its obstacle value
on the moving frontier and its dominance by an attainable cutoff price. -/
namespace Problem14.GameComparison
open GameLower GameFractional
/-- This is the binomial column of the nearest parity-compatible score to
a*sqrt(t+1). Ties go to the larger score. -/
noncomputable def column (a : ℝ) (t : ℕ) : ℕ :=
⌊((t:ℝ) + a*Real.sqrt ((t:ℝ)+1) + 1)/2⌋₊
noncomputable def frontier (a : ℝ) (ha : 0 ≤ a) (hb : a ≤ 1)
(T : ℕ) (hT : 3 ≤ T) : Frontier T where
column := column a
advance t _ := by
unfold column
rw [← Nat.floor_add_one (by positivity)]
apply Nat.floor_mono
push_cast
have h : Real.sqrt ((t:ℝ)+1+1) ≤ Real.sqrt ((t:ℝ)+1)+1 := by
apply (Real.sqrt_le_left (by positivity)).2
nlinarith only [Real.sq_sqrt (show (0:ℝ)≤t+1 by positivity), Real.sqrt_nonneg ((t:ℝ)+1)]
linarith only [mul_le_mul_of_nonneg_left h ha, hb]
physical t ht := by
unfold column
apply (Nat.floor_lt (by positivity)).mpr
have h₄ : (4:ℝ) ≤ t := by exact_mod_cast (show 4≤t by omega)
have hs : Real.sqrt ((t:ℝ)+1) < t-1 := by
apply (Real.sqrt_lt' (by linarith)).mpr
nlinarith only [h₄, mul_nonneg (by linarith : (0:ℝ)≤t-4) (by linarith : (0:ℝ)≤t)]
linarith only [hs, mul_le_mul_of_nonneg_right hb (Real.sqrt_nonneg ((t:ℝ)+1))]
theorem center_inside (a : ℝ) (ha : 0 ≤ a) (n : ℕ) : n ≤ column a (2*n) := by
apply Nat.le_floor
push_cast
linarith only [mul_nonneg ha (Real.sqrt_nonneg (2*(n:ℝ)+1))]
/-- Coefficients at t=3 of
−(z−1)(1+z)^2 + 9000(z−1)^3. Each subsequent row multiplies by 1+z. -/
def oddSeed (i : ℤ) : ℤ :=
if i=0 then -8999 else if i=1 then 27001 else if i=2 then -27001 else if i=3 then 8999 else 0
private theorem odd_reflect (k : ℕ) (j : ℤ) :
Upper.heat oddSeed k ((k:ℤ)+3-j) = -Upper.heat oddSeed k j := by
induction k generalizing j with
| zero => simp only [Upper.heat, oddSeed, Int.natCast_zero]; omega
| succ k ih =>
simp only [Upper.heat, Int.natCast_succ]
rw [show (k:ℤ)+1+3-j=k+3-(j-1) by omega,
show (k:ℤ)+3-(j-1)-1=k+3-j by omega, ih j, ih (j-1)]
omega
theorem odd_center (n : ℕ) (h : 3 ≤ 2*n) : Upper.heat oddSeed (2*n-3) n = 0 := by
have e := odd_reflect (2*n-3) n
rw [show ((2*n-3:ℕ):ℤ)+3-n=n by omega] at e
omega
private theorem left_ghost (f : ℤ → ℤ) (hf : ∀ j<0, f j=0) (k : ℕ) (j : ℤ) (h : j<0) :
Upper.heat f k j = 0 := by
induction k generalizing j with
| zero => exact hf j h
| succ k ih => rw [Upper.heat, ih j h, ih (j-1) (by omega)]; rfl
noncomputable def H (c : ℝ) (t m : ℕ) : ℝ :=
c*(Upper.heat Upper.mid t m : ℝ)/2 + (Upper.heat oddSeed (t-3) m : ℝ) - C t m / 5
theorem comparator_heat (c : ℝ) (T : ℕ) (hT : 3 ≤ T) (k m : ℕ) :
H c (T+k) m = heat (H c T) k m := by
apply heat_unique (H c T) (fun i => H c (T+i))
· intro j; simp
· intro i
have hm := left_ghost Upper.mid (by intro j h; simp [Upper.mid, h]) (T+i) (-1) (by decide)
have ho := left_ghost oddSeed (by intro j h; unfold oddSeed; omega)
(T+i-3) (-1) (by decide)
unfold H
rw [show T+(i+1)-3=(T+i-3)+1 by omega, show T+(i+1)=T+i+1 by omega, Upper.heat.eq_2, Upper.heat.eq_2]
simp only [Int.natCast_zero, Int.zero_sub, Int.cast_add, C.eq_1] at *
rw [hm,ho]
push_cast; ring
· intro i j
unfold H
rw [show T+(i+1)-3=(T+i-3)+1 by omega, show T+(i+1)=T+i+1 by omega, Upper.heat.eq_2, Upper.heat.eq_2, coefficient_pascal]
simp only [Int.natCast_succ, Int.add_sub_cancel, Int.cast_add]
ring
noncomputable def money : OrderedEmbedding ℝ where
embed := Int.cast
trans := le_trans
mono := by intro x y h; exact_mod_cast h
add := Int.cast_add
addMono := add_le_add
theorem deck_count (r b : ℕ) : weight (deck r b) = (r+b).choose b := by
change GameCutoff.ways r b = _
induction r, b using deck.induct with
| case1 => simp [GameCutoff.ways_red]
| case2 r _ => simp [GameCutoff.ways_red]
| case3 b _ => simp [GameCutoff.ways_black]
| case4 r b hl hr =>
rw [GameCutoff.ways_step, hl, hr, show r+1+(b+1)=(r+b+1)+1 by omega, Nat.choose_succ_succ]
rw [show r+1+b=r+b+1 by omega, show r+(b+1)=r+b+1 by omega, Nat.add_comm]
/-- The exact price of the balanced game expressed in real dollars. -/
noncomputable def price (n : ℕ) : ℝ :=
((closedNumerator n n : ℝ)-n*(weight (deck n n) : ℝ))/(weight (deck n n) : ℝ)
/-- All remaining obligations are local: exercise contact, the terminal
cutoff layer. The lower Wallis bound is supplied by GameWallis.
The explicit lower estimate then holds for every n above the cutoff. -/
theorem lower_price (a c : ℝ) (ha : 0 ≤ a) (hb : a ≤ 1) (hc : 0 ≤ c)
(T n : ℕ) (hT : 3 ≤ T) (hsize : T ≤ 2*n) (hn : 19 ≤ n)
(cut : ∀ r b, r+b=T → r≤n → b
#### `asmproof/GameContactError.lean`
~~~lean
import asmproof.GameContactIntegral
import asmproof.GameLowerKernel
import asmproof.GameContactTail
import asmproof.GameLowerMoment
/-! Uniform lower-contact error bound for the Gaussian approximation. -/
namespace Problem14.LowerIntegral
open Set MeasureTheory Real Problem14.UpperReal
theorem contact_error {a y s : ℝ} (al : 8399/10000≤a) (ah : a≤84/100)
(y0 : 0≤y) (ya : y≤a) (hs : 256≤s) :
s*(1-a^2)*(s+y)*(discreteIntegral s y-profile y) ≤ 751/1000 := by
have a0 : 0≤a := by linarith
have sp : 0 LowerKernel.near_bound hs hu.1.le hu.2)
· apply middle_tail a0 ah y0 ya hs
intro u hu
have e := LowerKernel.middle_bound (y:=y) sp (show 0≤u by linarith [hu.1]) hu.2
convert e using 1; ring
· exact far_tail a0 ah y0 ya hs
end Problem14.LowerIntegral
~~~
#### `asmproof/GameContactIntegral.lean`
~~~lean
import asmproof.UpperGaussian
/-! The lower-contact Laplace comparison. Separate 0s. The near Gaussian moment extends to the full positive axis,
and the other two regions carry their own certified tails. -/
namespace Problem14.LowerIntegral
open Set MeasureTheory Real Problem14.UpperReal
theorem gauss_int (y : ℝ) : Integrable (fun u : ℝ => exp (y*u-u^2/2)) := by
refine ((integrable_exp_neg_mul_sq (b:=(1/4:ℝ)) (by norm_num)).const_mul (exp (y^2))).mono'
(by apply Continuous.aestronglyMeasurable; fun_prop) (ae_of_all _ fun u => ?_)
rw [Real.norm_eq_abs, abs_of_pos (exp_pos _), ← exp_add, exp_le_exp]
nlinarith [sq_nonneg (y-u/2)]
theorem fourth_integrable (a : ℝ) :
IntegrableOn (fun u:ℝ => u^4*exp (a*u-u^2/2)) (Ioi (0:ℝ)) := by
have base := integrableOn_rpow_mul_exp_neg_mul_sq (b:=(1/4:ℝ)) (by norm_num)
(s:=(4:ℝ)) (by norm_num)
rw [show (4:ℝ)=(↑(4:ℕ):ℝ) by norm_num] at base
simp only [Real.rpow_natCast] at base
refine (base.const_mul (exp (a^2))).mono' (by apply Continuous.aestronglyMeasurable; fun_prop)
(ae_of_all _ fun u => ?_)
rw [Real.norm_eq_abs, abs_of_nonneg (by positivity)]
have e : exp (a*u-u^2/2) ≤ exp (a^2)*exp (-(1/4:ℝ)*u^2) := by
rw [← exp_add, Real.exp_le_exp]; nlinarith [sq_nonneg (a-u/2)]
nlinarith only [mul_le_mul_of_nonneg_left e (show 0≤u^4 by positivity)]
private theorem part {f : ℝ→ℝ} {a b:ℝ} (hab : a≤b) (hf : IntegrableOn f (Ioi a)) :
(∫ u in Ioi a, f u) = (∫ u in Ioc a b, f u)+(∫ u in Ioi b, f u) := by
have h := setIntegral_union (f:=f) (μ:=volume) (show Disjoint (Ioc a b) (Ioi b) by
apply Set.disjoint_left.mpr; intro z hz hz'; exact (not_lt_of_ge hz.2) hz') measurableSet_Ioi
(hf.mono_set Ioc_subset_Ioi_self) (hf.mono_set (Ioi_subset_Ioi hab))
rwa [Ioc_union_Ioi (by simp), min_eq_left hab] at h
/-- The fourth-moment estimate pays for the entire near interval. -/
theorem near {a y s:ℝ} (a0 : 0≤a) (a1 : a≤1) (y0 : 0≤y) (ya : y≤a) (hs : 256≤s)
(moment : (1-a^2)*(∫ u in Ioi (0:ℝ), u^4*exp (a*u-u^2/2)) ≤ 17/2)
(bound : ∀ u∈Ioc (0:ℝ) 12, lapKernel s y u-exp (y*u-u^2/2) ≤
(103/100)*u^4*exp (y*u-u^2/2)/(12*s^2)) :
s*(1-a^2)*(s+y)*(∫ u in Ioc (0:ℝ) 12, lapKernel s y u-exp (y*u-u^2/2)) ≤ 3/4 := by
let M : ℝ→ℝ := fun u => u^4*exp (a*u-u^2/2)
let k := (103:ℝ)/(100*12*s^2)
have spos : 0by dsimp [M]; positivity))
(ae_of_all _ (fun _=>fun h=>h.1))
have coeff : s*(s+y)*k ≤ (3:ℝ)/34 := by
dsimp [k]
rw [mul_div_assoc', le_div_iff₀ (by norm_num : (0:ℝ)<34)]
rw [div_mul_eq_mul_div, div_le_iff₀ (by positivity : (0:ℝ)<100*12*s^2)]
nlinarith only [mul_nonneg spos.le (sub_nonneg.mpr (ya.trans a1)),
mul_nonneg spos.le (sub_nonneg.mpr hs)]
have positive : 0 ≤ s*(1-a^2)*(s+y) := by positivity
have mid := mul_le_mul_of_nonneg_left (near'.trans (mul_le_mul_of_nonneg_left extend kpos)) positive
have Mpos : 0≤(∫ u in Ioi (0:ℝ), M u) := integral_nonneg (by intro; dsimp [M]; positivity)
have end' := mul_le_mul coeff moment (mul_nonneg apos Mpos) (by norm_num)
dsimp [M] at mid end'
linarith only [mid,end']
/-- A uniform 0.751 bound, tighter than the 0.78 needed for contact. -/
theorem combine {a y s:ℝ} (ha : 0≤a) (a1 : a≤1) (y0 : 0≤y) (ya : y≤a) (hs : 256≤s)
(moment : (1-a^2)*(∫ u in Ioi (0:ℝ), u^4*exp (a*u-u^2/2)) ≤ 17/2)
(nb : ∀ u∈Ioc (0:ℝ) 12, lapKernel s y u-exp (y*u-u^2/2) ≤
(103/100)*u^4*exp (y*u-u^2/2)/(12*s^2))
(mb : s*(1-a^2)*(s+y)*(∫ u in Ioc 12 s, lapKernel s y u-exp (y*u-u^2/2)) ≤ 1/2000)
(fb : s*(1-a^2)*(s+y)*(∫ u in Ioi s, lapKernel s y u-exp (y*u-u^2/2)) ≤ 1/2000) :
s*(1-a^2)*(s+y)*(discreteIntegral s y-profile y) ≤ 751/1000 := by
have n := near ha a1 y0 ya hs moment nb
rw [discreteIntegral,profile_eq_laplace y0,←integral_sub (kernel_integrable (by linarith) (by linarith : y lapKernel s y u-exp (y*u-u^2/2)
have fi : IntegrableOn f (Ioi (0:ℝ)) :=
(kernel_integrable (by linarith) (by linarith : y
#### `asmproof/GameContactTail.lean`
~~~lean
import asmproof.UpperGaussian
import Mathlib.Data.Complex.ExponentialBounds
/-! Uniform bounds for the two tails of the discrete Laplace error.
Constants are dollars after multiplication by s(1−a²)(s+y), s ≥ 256.
The far tail uses only cosh z ≥ exp(z)/2 and log 2 < 7/10. -/
namespace Problem14.UpperReal
open Set MeasureTheory Real
noncomputable section
theorem excess_integrable {s y : ℝ} (hs : 0 lapKernel s y u-exp (y*u-u^2/2)) (Ioi (0:ℝ)) := by
have h := kernel_integrable hs hy
apply h.sub
apply h.mono'
· exact (show Continuous (fun u : ℝ => exp (y*u-u^2/2)) by fun_prop).aestronglyMeasurable
· exact .of_forall fun u => by rw [Real.norm_eq_abs, abs_of_pos (exp_pos _)]; exact kernel_lower hs y u
private theorem weight_bounds {a s y : ℝ} (ha0 : 0≤a) (ha : a≤84/100)
(hy : 0≤y) (hya : y≤a) (hs : 256≤s) :
0≤s*(1-a^2)*(s+y) ∧ s*(1-a^2)*(s+y)≤2*s^2 := by
have h0 : 0≤1-a^2 := by nlinarith [mul_nonneg (show 0≤1-a by linarith) (show 0≤1+a by linarith)]
refine ⟨by positivity,?_⟩
nlinarith [mul_nonneg (mul_nonneg (show 0≤s by linarith) (sq_nonneg a)) (show 0≤s+y by linarith),
mul_nonneg (show 0≤s by linarith) (show 0≤s-y by linarith)]
theorem middle_exponential {u y : ℝ} (hu : 12≤u) (hy : y≤84/100) :
u^4*exp (y*u-5*u^2/12) ≤ exp (-3*u) := by
have up : 0 h.1
have inc0 : Ioc (12:ℝ) s ⊆ Ioi 0 := fun _ h => by have := h.1; exact lt_trans (by norm_num) this
have scaled : IntegrableOn (fun u : ℝ => 1/(12*s^2)*exp (-3*u)) (Ioi 12) := hm.const_mul _
have h := setIntegral_mono_on ((excess_integrable s0 (by linarith : y by
have e := middle_exponential hu.1.le (le_trans hya ha)
calc
_ ≤ _ := middlePoint u hu
_ = (1/(12*s^2))*(u^4*exp (y*u-5*u^2/12)) := by ring
_ ≤ _ := mul_le_mul_of_nonneg_left e (by positivity))
rw [integral_const_mul] at h
have big := setIntegral_mono_set hm (.of_forall (fun _ => (exp_pos _).le)) (.of_forall inc)
rw [integral_exp_mul_Ioi (by norm_num : (-3:ℝ)<0)] at big
have W := weight_bounds ha0 ha hy hya hs
have e36 : 360 ≤ exp (36:ℝ) := by
have k := exp_sq_lower 18 (by norm_num)
norm_num at k ⊢
linarith
have step := mul_le_mul_of_nonneg_right W.2 (show 0≤(1/(12*s^2))*(-exp ((-3:ℝ)*12)/(-3)) by rw [neg_div_neg_eq]; positivity)
have total := mul_le_mul_of_nonneg_left (h.trans (mul_le_mul_of_nonneg_left big (by positivity))) W.1
apply total.trans (step.trans ?_)
rw [show (-3:ℝ)*12= -36 by norm_num, exp_neg]
field_simp [s0.ne', (exp_pos (36:ℝ)).ne']
rw [div_le_div_iff₀ (by positivity) (by norm_num)]
nlinarith [mul_nonneg (sq_nonneg s) (show 0≤exp (36:ℝ)-360 by linarith)]
theorem far_exponential {s y u : ℝ} (hs : 256≤s) (hy : y≤84/100) (hu : s≤u) :
lapKernel s y u ≤ exp ((-s/4)*u) := by
have sp : 0 lt_trans s0 h
have h := setIntegral_mono_on ((excess_integrable s0 (by linarith : y
le_trans (sub_le_self _ (exp_pos _).le) (far_exponential hs (le_trans hya ha) hu.le))
rw [integral_exp_mul_Ioi neg] at h
have W := weight_bounds ha0 ha hy hya hs
have step := mul_le_mul_of_nonneg_right W.2 (show 0≤ -exp ((-s/4)*s)/(-s/4) by
rw [show -s/4= -(s/4) by ring, neg_div_neg_eq]; positivity)
apply (mul_le_mul_of_nonneg_left h W.1).trans (step.trans ?_)
rw [show (-s/4)*s = -(s^2/4) by ring, exp_neg]
have ek := exp_sq_lower (s^2/8) (by positivity)
rw [show 2*(s^2/8)=s^2/4 by ring] at ek
have uu : 32*s ≤ 1+s^2/8 := by nlinarith [mul_nonneg s0.le (show 0≤s-256 by linarith)]
have ev : 16000*s ≤ exp (s^2/4) := by
nlinarith [mul_le_mul uu (show 500 ≤ 1+s^2/8 by linarith) (by norm_num : (0:ℝ)≤500)
(by positivity : 0≤1+s^2/8)]
field_simp [s0.ne', (exp_pos (s^2/4)).ne']
rw [div_le_div_iff₀ (by positivity) (by norm_num)]
nlinarith [mul_le_mul_of_nonneg_left ev s0.le]
end
end Problem14.UpperReal
~~~
#### `asmproof/GameCutoff.lean`
~~~lean
import asmproof.GameLower
/-! Correctness of fixed-point lower Bellman tables. A cell holds a conditional
price in units 1/S. Negative values can be replaced with zero because exhausting
the deck is feasible. A wall may exercise early, and the reciprocal multiply
used by shrinking_layer.c may round down. All comparisons below are integral.
-/
namespace Problem14.GameCutoff
open Excursions GameLower
def ways (r b : Nat) := weight (deck r b)
theorem ways_red (r : Nat) : ways r 0 = 1 := by
induction r with
| zero => simp [ways, deck, weight, paths]
| succ r ih => simpa [ways, deck.eq_2, weight, paths] using ih
theorem ways_black (b : Nat) : ways 0 b = 1 := by
induction b with
| zero => simp [ways, deck, weight, paths]
| succ b ih => simpa [ways, deck.eq_3, weight, paths] using ih
theorem ways_step (r b : Nat) : ways (r+1) (b+1) = ways r (b+1) + ways (r+1) b := by
simp [ways, deck.eq_4, weight, paths]
/-- A bijective count of a marked red or black card, in Pascal form. -/
theorem swap_mark (r b : Nat) : (b+1)*ways r (b+1) = (r+1)*ways (r+1) b := by
induction r, b using deck.induct with
| case1 => simp [ways_red, ways_black]
| case2 r ih =>
rw [ways_step, ways_red, ways_red]
rw [ways_red] at ih
simp at *; omega
| case3 b ih =>
rw [ways_step, ways_black, ways_black]
rw [ways_black] at ih
simp at *; omega
| case4 r b ih₁ ih₂ =>
rw [ways_step r (b+1), ways_step (r+1) b, Nat.mul_add, Nat.mul_add, ih₁, ← ih₂]
simp only [Nat.succ_mul]
omega
theorem draw_counts (r b : Nat) :
((r+1)+(b+1))*ways r (b+1) = (r+1)*ways (r+1) (b+1) ∧
((r+1)+(b+1))*ways (r+1) b = (b+1)*ways (r+1) (b+1) := by
constructor
· rw [ways_step r b, Nat.add_mul, Nat.mul_add, swap_mark r b]
· rw [ways_step r b, Nat.add_mul, Nat.mul_add, swap_mark r b]
theorem exhaust (R : Nat) (tree : Tree) : R * weight tree ≤ bellman R tree := by
induction tree with
| empty => simp [bellman, weight, paths]
| leaf => simp [bellman, weight, paths]
| branch s l r hl hr =>
apply Nat.le_trans _ (Nat.le_max_right _ _)
simpa only [weight, paths, List.length_map, List.length_append, Nat.mul_add]
using Nat.add_le_add hl hr
theorem mass_nonneg (R r b : Nat) : 0 ≤ mass R r b := by
have h := Int.ofNat_le.mpr (exhaust R (deck r b))
rw [Int.natCast_mul] at h
unfold mass; omega
/-- The nonnegative aggregate price. -/
def total (R r b : Nat) := (mass R r b).toNat
theorem cast_total (R r b : Nat) : (total R r b : Int) = mass R r b :=
Int.toNat_of_nonneg (mass_nonneg R r b)
theorem stop_total (R r b : Nat) (hr : r ≤ R) : (b-r)*ways r b ≤ total R r b := by
by_cases h : r ≤ b
· apply Int.ofNat_le.mp
rw [Int.natCast_mul, Int.ofNat_sub h, cast_total]
exact stop_le_mass R r b hr
· rw [Nat.sub_eq_zero_of_le (by omega), Nat.zero_mul]
exact Nat.zero_le _
theorem draw_total (R r b : Nat) :
total R r (b+1)+total R (r+1) b ≤ total R (r+1) (b+1) := by
apply Int.ofNat_le.mp
rw [Int.natCast_add, cast_total, cast_total, cast_total]
exact draw_both R r b
/-- Every table satisfying these one-sided conditions is a certified lower
price. On either axis the supplied policy may take the positive score or play
to zero. In the interior it may take either of these or a rounded draw. -/
structure Table (scale : Nat) where
cell : Nat → Nat → Nat
reds : ∀ r, cell r 0 = 0
blacks : ∀ b, cell 0 b ≤ scale*b
interior : ∀ r b, cell (r+1) (b+1) ≤
max (scale*((b+1)-(r+1)))
(((r+1)*cell r (b+1)+(b+1)*cell (r+1) b)/((r+1)+(b+1)))
private theorem draw_valid (scale R r b l h : Nat)
(hl : l*ways r (b+1) ≤ scale*total R r (b+1))
(hr : h*ways (r+1) b ≤ scale*total R (r+1) b) :
(((r+1)*l+(b+1)*h)/((r+1)+(b+1))) * ways (r+1) (b+1)
≤ scale*total R (r+1) (b+1) := by
let t := (r+1)+(b+1)
let v := ((r+1)*l+(b+1)*h)/t
change v*_ ≤ _
apply Nat.le_of_mul_le_mul_left (c:=t) _ (by dsimp [t]; omega)
have hdiv : t*v ≤ (r+1)*l+(b+1)*h := by
rw [Nat.mul_comm]; exact Nat.div_mul_le_self _ _
have hswap := draw_counts r b
have hleft : t*(l*ways r (b+1)) = ((r+1)*l)*ways (r+1) (b+1) := by
rw [Nat.mul_left_comm, hswap.1]; ac_rfl
have hright : t*(h*ways (r+1) b) = ((b+1)*h)*ways (r+1) (b+1) := by
rw [Nat.mul_left_comm, hswap.2]; ac_rfl
calc
t*(v*ways (r+1) (b+1)) = (t*v)*ways (r+1) (b+1) := (Nat.mul_assoc ..).symm
_ ≤ ((r+1)*l+(b+1)*h)*ways (r+1) (b+1) := Nat.mul_le_mul_right _ hdiv
_ = t*(l*ways r (b+1) + h*ways (r+1) b) := by rw [Nat.add_mul, Nat.mul_add, hleft, hright]
_ ≤ t*(scale*total R (r+1) (b+1)) := by
apply Nat.mul_le_mul_left
apply Nat.le_trans (Nat.add_le_add hl hr)
rw [← Nat.mul_add]
exact Nat.mul_le_mul_left scale (draw_total R r b)
theorem table_lower (scale R : Nat) (q : Table scale) :
∀ r b, r ≤ R → q.cell r b * ways r b ≤ scale * total R r b := by
intro r b
induction r, b using deck.induct with
| case1 => intro; rw [q.reds, Nat.zero_mul]; omega
| case2 r _ => intro; rw [q.reds, Nat.zero_mul]; omega
| case3 b _ =>
intro hr
apply Nat.le_trans (Nat.mul_le_mul_right _ (q.blacks (b+1)))
rw [Nat.mul_assoc]
exact Nat.mul_le_mul_left scale (stop_total R 0 (b+1) hr)
| case4 r b ihr ihb =>
intro hr
apply Nat.le_trans (Nat.mul_le_mul_right _ (q.interior r b))
rcases Nat.le_total (scale*((b+1)-(r+1)))
(((r+1)*q.cell r (b+1)+(b+1)*q.cell (r+1) b)/((r+1)+(b+1))) with h | h
· rw [Nat.max_eq_right h]
exact draw_valid scale R r b _ _ (ihr (by omega)) (ihb hr)
· rw [Nat.max_eq_left h, Nat.mul_assoc]
exact Nat.mul_le_mul_left scale (stop_total R (r+1) (b+1) hr)
/-- The downward reciprocal used by shrinking_layer.c. The proof is valid for
every word size and has no condition on the dividend. -/
theorem reciprocal_lower (n t word : Nat) (ht : 0 < t) (hw : 0 < word) :
(n*((word-1)/t))/word ≤ n/t := by
apply (Nat.le_div_iff_mul_le ht).mpr
apply Nat.le_of_mul_le_mul_left (c:=word) _ hw
have d := Nat.div_mul_le_self (n*((word-1)/t)) word
have small := Nat.div_mul_le_self (word-1) t
calc
word * (n*((word-1)/t)/word*t) = (n*((word-1)/t)/word * word)*t := by ac_rfl
_ ≤ (n*((word-1)/t))*t := Nat.mul_le_mul_right _ d
_ = n*(((word-1)/t)*t) := Nat.mul_assoc ..
_ ≤ n*(word-1) := Nat.mul_le_mul_left n small
_ ≤ word*n := by rw [Nat.mul_comm word n]; exact Nat.mul_le_mul_left n (by omega)
/-- Mathematical specification of the integer policy in shrinking_layer.c.
The wall is measured in score units. A boundary child outside the computed
band can never be read by a strict continuation, since one draw moves the
score by only one. -/
def cutoffCell (scale wall word : Nat) : Nat → Nat → Nat
| _, 0 => 0
| 0, b+1 => scale*(b+1)
| r+1, b+1 =>
let s := scale*((b+1)-(r+1))
if r+1+wall ≤ b+1 then s else
let children := (r+1)*cutoffCell scale wall word r (b+1) +
(b+1)*cutoffCell scale wall word (r+1) b
max s ((children*((word-1)/((r+1)+(b+1))))/word)
theorem cutoffCell_lower (scale wall word R r b : Nat) (hw : 0 < word) (hr : r ≤ R) :
cutoffCell scale wall word r b * ways r b ≤ scale * total R r b := by
let q : Table scale := {
cell := cutoffCell scale wall word
reds := fun r => by rw [cutoffCell]
blacks := fun b => by cases b <;> simp [cutoffCell]
interior := fun r b => by
rw [cutoffCell]
split
· exact Nat.le_max_left _ _
· apply Nat.max_le.mpr
constructor
· exact Nat.le_max_left _ _
· exact Nat.le_trans (reciprocal_lower _ _ word (by omega) hw) (Nat.le_max_right _ _) }
exact table_lower scale R q r b hr
theorem reference_cutoff_lower (R r b : Nat) (hr : r ≤ R) :
cutoffCell (2^30) 512 (2^64) r b * ways r b ≤ 2^30 * total R r b :=
cutoffCell_lower _ _ _ _ _ _ (by decide) hr
end Problem14.GameCutoff
~~~
#### `asmproof/GameExercise.lean`
~~~lean
import asmproof.GameLowerPrice
import asmproof.GameContactError
import asmproof.GameLowerTaylor
import asmproof.GamePositivity
import asmproof.UpperBinomial
/-! Exercise contact for the actual binomial card-game comparator. -/
namespace Problem14.GameExercise
open GameMoments GameComparison GameFractional GameLowerPrice UpperReal
open MeasureTheory Set Real
private theorem tilt_le {t x : ℝ} (ht : 65536≤t) (hx : 0≤x) (bound : x^2≤3*t-2) :
tilt t x ≤ -x/t := by
have neg := mul_nonpos_of_nonpos_of_nonneg (sub_nonpos.mpr bound) hx
have den : 0≤t*(t-1)*(t-2) := mul_nonneg (mul_nonneg (by linarith) (by linarith)) (by linarith)
have cub : (x^3-(3*t-2)*x)/(t*(t-1)*(t-2))≤0 :=
div_nonpos_of_nonpos_of_nonneg (by linarith only [neg]) den
unfold tilt; rw [mul_div_assoc]; linarith only [cub]
/-- The unscaled beta integral gives exactly the discrete profile used in
the stopping-boundary residual, with its complete Jacobian factor. -/
private theorem mid_price {t m : ℕ} {x s y a : ℝ} (hm : 1≤m) (hmt : m≤t)
(eqx : x=2*(m:ℝ)-t) (hs : 0
#### `asmproof/GameFractional.lean`
~~~lean
import asmproof.GameLower
import asmproof.GameCentral
import Mathlib.Analysis.SpecialFunctions.Pow.Real
import Mathlib.Tactic.LinearCombination
import Mathlib.Tactic.FieldSimp
import Mathlib.Tactic.Positivity
import Mathlib.Tactic.NormNum
import Mathlib.Tactic.Linarith
/-! The fractional Pascal comparator for p = 2/5. These coefficients are
uniquely specified by C(0)=1 and
(1-z^2)C'(z)=((t-4/5)-t*z)C(z), the formal logarithmic derivative of
(1-z)^(2/5)(1+z)^(t-2/5). No transcendental evaluation is used for
their Pascal harmonicity, their diagonal or their fifth-root debit. -/
namespace Problem14.GameFractional
open GameCentral GameLower
noncomputable def C (t : ℕ) : ℕ → ℝ
| 0 => 1
| 1 => t-4/5
| m+2 => ((t-4/5)*C t (m+1) - ((t:ℝ)-m)*C t m)/(m+2)
theorem coefficient_rec (t m : ℕ) : ((m:ℝ)+2)*C t (m+2) =
((t:ℝ)-4/5)*C t (m+1) - ((t:ℝ)-m)*C t m := by
rw [C.eq_3]
field_simp
ring
/-- Multiplication by 1+z increments t. At m=0 the initial coefficient
remains one. This proves the claimed martingale even at the all-red edge. -/
theorem coefficient_pascal (t m : ℕ) : C (t+1) (m+1) = C t (m+1) + C t m := by
induction m using Nat.twoStepInduction with
| zero => change (↑(t+1):ℝ)-4/5 = (t:ℝ)-4/5+1; push_cast; ring
| one =>
norm_num [C]
ring
| more m h₀ h₁ =>
have h := coefficient_rec t (m+1)
have g := coefficient_rec (t+1) (m+1)
have j := coefficient_rec t m
rw [h₀,h₁] at g
push_cast at h g
apply (mul_left_cancel₀ (show (m:ℝ)+3 ≠ 0 by positivity))
linear_combination g-h-j
theorem coefficient_heat (T k m : ℕ) : C (T+k) m = heat (C T) k m := by
apply heat_unique (C T) (fun i => C (T+i))
· intro j; simp
· intro i; simp [C.eq_1]
· intro i j; exact coefficient_pascal (T+i) j
/-- The two Pascal steps at the center collapse using the horizontal
coefficient recurrence. This gives a finite algebraic proof of the beta
diagonal identity. -/
theorem diagonal_step (n : ℕ) : ((n:ℝ)+1)*C (2*(n+1)) (n+1)
= (4*n+6/5)*C (2*n) n := by
cases n with
| zero => norm_num [C]
| succ k =>
let t := 2*(k+1)
change ((↑(k+1):ℝ)+1)*C (2*(k+1+1)) (k+1+1) = (4*↑(k+1)+6/5)*C t (k+1)
rw [show 2*(k+1+1)=t+1+1 by dsimp [t]; omega,
coefficient_pascal (t+1) (k+1), coefficient_pascal t (k+1), coefficient_pascal t k]
have h := coefficient_rec t k
dsimp [t] at h ⊢
push_cast at h ⊢
linear_combination h
/-- The unperturbed binomial coefficient satisfies the corresponding
ordinary Pascal diagonal relation. -/
theorem binomial_step (n : ℕ) : (n+1)*(2*(n+1)).choose (n+1) =
(4*n+2)*(2*n).choose n := by
have h₁ := Nat.succ_mul_choose_eq (2*n) n
have h₂ := Nat.choose_mul_succ_eq (2*n+1) (n+1)
have h₃ : 2*n+1+1-(n+1)=n+1 := by omega
rw [h₃] at h₂
have h : 2*(n+1) = 2*n+1+1 := by omega
rw [h, Nat.mul_comm, ← h₂]
have he : (2*n+1+1) = 2*(n+1) := by omega
rw [he]
calc
_ = 2*(((2*n+1).choose (n+1))*(n+1)) := by ring
_ = _ := by rw [←h₁, Nat.succ_eq_add_one]; ring
private theorem product_pos (a n : ℕ) (ha : 0 < a) : 0 < product a n := by
induction n with
| zero => simp [product]
| succ n ih => rw [product]; positivity
/-- The normalized central coefficient is the rational product exactly. -/
theorem central_ratio (n : ℕ) : C (2*n) n / ((2*n).choose n : ℝ) =
(product 3 n : ℝ)/(product 5 n : ℝ) := by
induction n with
| zero => norm_num [C, product]
| succ n ih =>
have hd := diagonal_step n
have hb : ((n:ℝ)+1) * ((2*(n+1)).choose (n+1) : ℝ) =
(4*(n:ℝ)+2)*((2*n).choose n : ℝ) := by exact_mod_cast binomial_step n
have hbp := Nat.choose_pos (show n ≤ 2*n by omega)
have hbsp := Nat.choose_pos (show n+1 ≤ 2*(n+1) by omega)
have hq := product_pos 5 n (by decide)
have hq' : ((product 5 n : ℕ):ℝ) ≠ 0 := by exact_mod_cast hq.ne'
rw [product.eq_2, product.eq_2]
push_cast
apply (div_eq_div_iff (by exact_mod_cast hbsp.ne') (by positivity)).mpr
have hi := (div_eq_div_iff (by exact_mod_cast hbp.ne') hq').mp ih
apply (mul_left_cancel₀ (show (n:ℝ)+1 ≠ 0 by positivity))
linear_combination (10*n+5)*(product 5 n)*hd -
(10*n+3)*(product 3 n)*hb + (4*n+2)*(10*n+3)*hi
/-- The full central debit inequality for the actual fractional coefficient,
proved without logarithms, special-function integrals or numerical quadrature.
It already holds for every total deck size 2n at least 38. -/
theorem fractional_debit (n : ℕ) (hn : 19 ≤ n) :
(C (2*n) n / ((2*n).choose n : ℝ))/5 ≤
(137/1000) / (2*(n:ℝ)+1)^((1:ℝ)/5) := by
rw [central_ratio]
let root := (2*(n:ℝ)+1)^((1:ℝ)/5)
have hroot : 0 < root := Real.rpow_pos_of_pos (by positivity) _
have fifth : root^5 = 2*(n:ℝ)+1 := by
dsimp [root]
rw [← Real.rpow_natCast _ 5, ← Real.rpow_mul (by positivity)]
norm_num
have hp : 0 < ((product 5 n : ℕ):ℝ) := by exact_mod_cast product_pos 5 n (by decide)
have h : (200:ℝ)^5*((2*(n:ℝ)+1)*(product 3 n : ℝ)^5) ≤ 137^5*(product 5 n : ℝ)^5 :=
by exact_mod_cast central_debit n hn
have bound : 200*root*(product 3 n : ℝ) ≤ 137*(product 5 n : ℝ) := by
apply (pow_le_pow_iff_left₀ (by positivity) (by positivity) (by decide : (5:ℕ)≠0)).mp
rw [mul_pow, mul_pow, mul_pow, fifth]
linarith only [h]
apply (le_div_iff₀ hroot).mpr
rw [div_div, div_mul_eq_mul_div]
apply (div_le_div_iff₀ (by positivity) (by norm_num)).mpr
linarith only [bound]
end Problem14.GameFractional
~~~
#### `asmproof/GameLayer.lean`
~~~lean
import asmproof.GameCutoff
import Std
/-! A 3,184-lane integer Bellman layer. Lane i has centered score
2*i−6144+(t%2). The cutoff policy stops at score 222 or above and takes
the guaranteed zero below −6142. Rounding a continuation down preserves
the lower bound. All operations use Lean's unbounded binary naturals. -/
namespace Problem14.GameLayer
open GameCutoff
abbrev width := 3184
abbrev scale := 1073741824
@[inline] def readLane (row : Array Nat) (i : Nat) : Nat := row[i]?.getD 0
/-- A physical column projected into the lane window; omitted lanes have
the feasible lower payoff zero. -/
def atColumn (row : Array Nat) (t m : Nat) : Nat :=
if (t+1)/2 ≤ m+3072 then readLane row (m+3072-(t+1)/2) else 0
@[inline] def update (old : Array Nat) (t half odd i : Nat) : Nat :=
let shifted := 2*i+odd
let m := i+half-3072
let stop := (shifted-6144)*scale
if 0 update old t half odd i.val
private def history {α : Type} (step : α → Nat → α) (seed : α) : Nat → α
| 0 => seed
| t+1 => step (history step seed t) (t+1)
private def forward {α : Type} (step : α → Nat → α) (t : Nat) : Nat → α → α
| 0, previous => previous
| n+1, previous => forward step (t+1) n (step previous (t+1))
private theorem forward_history {α : Type} (step : α → Nat → α) (seed : α) (t n : Nat) :
forward step t n (history step seed t) = history step seed (t+n) := by
induction n generalizing t with
| zero => rfl
| succ n ih =>
change forward step (t+1) n (history step seed (t+1)) = history step seed (t+(n+1))
rw [ih, show t+1+n=t+(n+1) by omega]
def rows := history next (Array.replicate width 0)
def run := forward next
theorem rows_zero : rows 0 = Array.replicate width 0 := rfl
theorem rows_succ (t : Nat) : rows (t+1) = next (rows t) (t+1) := rfl
theorem run_rows (t n : Nat) : run t n (rows t) = rows (t+n) :=
forward_history next (Array.replicate width 0) _ _
def finalRow : Array Nat := run 0 65536 (rows 0)
def lookup (row : Array Nat) (m : Nat) := atColumn row 65536 m
def finalPrice (m : Nat) := lookup finalRow m
theorem finalRow_eq : finalRow = rows 65536 := by
unfold finalRow
exact run_rows 0 65536
private theorem read_build {n} (f : Fin n→Nat) (i : Nat) :
readLane (Array.ofFn f) i = if h : i simp [value, atColumn, rows_zero, readLane, width]
| succ r =>
unfold value
simp only [Nat.add_zero, rows_succ, at_next]
split
· rename_i h
simp only [update]
have eq : 3072-(r+1+1)/2 + (r+1+1)/2-3072=0 := by omega
have eq' : 2*(3072-(r+1+1)/2)+(r+1)%2-6144=0 := by omega
simp [eq,eq']
· rfl
private theorem axis_black (b : Nat) : value 0 b ≤ scale*b := by
cases b with
| zero => simp [value, atColumn, rows_zero, readLane, width]
| succ b =>
unfold value
simp only [Nat.zero_add, rows_succ, at_next]
split
· rename_i h
simp only [update]
have eq : (b+1+3072-(b+1+1)/2) + (b+1+1)/2 -3072 = b+1 := by omega
have eq' : 2*(b+1+3072-(b+1+1)/2)+(b+1)%2-6144=b+1 := by omega
simp [eq,eq',Nat.mul_comm]
· exact Nat.zero_le _
private theorem interior (r b : Nat) : value (r+1) (b+1) ≤
max (scale*((b+1)-(r+1)))
(((r+1)*value r (b+1)+(b+1)*value (r+1) b)/((r+1)+(b+1))) := by
let t := (r+1)+(b+1)
let old := rows (t-1)
let i := b+1+3072-(t+1)/2
have ht : rows t = next old t := by rfl
change atColumn (rows t) t (b+1) ≤ _
rw [ht,at_next]
split
· rename_i h
change update old t ((t+1)/2) (t%2) i ≤ _
simp only [update]
have hm : i+(t+1)/2-3072 = b+1 := by dsimp [i]; omega
have score : 2*i+t%2-6144 = (b+1)-(r+1) := by
dsimp [i,t] at *; omega
rw [hm, score, Nat.mul_comm _ scale]
split
· rename_i guard
have a : r+(b+1) = t-1 := by dsimp [t]; omega
have b' : r+1+b = t-1 := by dsimp [t]; omega
have c : t-(b+1) = r+1 := by dsimp [t]; omega
have left : value r (b+1) = readLane old (i+t%2) := by
unfold value atColumn; rw [a]; change (if _ then readLane old _ else _) = _
split
· apply congrArg (readLane old); dsimp only [t,i] at h guard ⊢; omega
· dsimp only [t,i] at *; omega
have right : value (r+1) b = readLane old (i+t%2-1) := by
unfold value atColumn; rw [b']; change (if _ then readLane old _ else _) = _
split
· apply congrArg (readLane old); dsimp only [t,i] at h guard ⊢; omega
· dsimp only [t,i] at *; omega
rw [c, left, right]; exact Nat.le_refl _
· exact Nat.le_max_left _ _
· exact Nat.zero_le _
theorem finalPrice_lower (R r b : Nat) (ht : r+b=65536) (hr : r≤R) :
finalPrice b * ways r b ≤ scale * total R r b := by
let q : Table scale := ⟨value,axis_red,axis_black,interior⟩
have h := table_lower scale R q r b hr
change value r b * ways r b ≤ _ at h
simpa [value,ht,finalPrice,lookup,finalRow_eq] using h
end Problem14.GameLayer
~~~
#### `asmproof/GameLower.lean`
~~~lean
import Excursions
/-! Discrete verification of lower bounds for the balanced stopping game.
The state (r,b) counts remaining cards and m=b indexes a row of length t+1.
Work in totals over all equally likely completions. These totals obey the
ordinary Pascal relation; no division or probability axiom is required.
The value being bounded is the actual Bellman numerator, with shift removed.
-/
namespace Problem14.GameLower
open Excursions
def stopMass (r b : Nat) : Int :=
((b : Int) - r) * (weight (deck r b) : Int)
private theorem branchWeight (s : State) (l h : Tree) :
weight (.branch s l h) = weight l + weight h := by simp [weight, paths]
private theorem stopBranch (R r b : Nat) (l h : Tree) (hr : r ≤ R) :
((b : Int)-r)*(weight (.branch (r,b) l h) : Int) ≤
(bellman R (.branch (r,b) l h) : Int) - R*(weight (.branch (r,b) l h) : Int) := by
have hstop := Nat.le_max_left (reward R (r,b)*(weight l+weight h))
(bellman R l + bellman R h)
have hn : reward R (r,b) = R-r+b := rfl
have hs : ((reward R (r,b) : Nat) : Int) = (R : Int) + ((b : Int)-r) := by
rw [hn, Int.natCast_add, Int.ofNat_sub hr]; omega
have hi := Int.ofNat_le.mpr hstop
rw [Int.natCast_mul, hs, Int.add_mul] at hi
simp only [bellman, branchWeight]
omega
theorem stop_le_mass (R r b : Nat) (hr : r ≤ R) : stopMass r b ≤ mass R r b := by
cases r <;> cases b
· simp [stopMass, mass, deck, weight, paths, bellman]
all_goals simpa only [stopMass, mass, deck.eq_2, deck.eq_3, deck.eq_4] using
stopBranch R _ _ _ _ hr
private theorem drawBranch (R : Nat) (s : State) (l h : Tree) :
((bellman R l : Int) - R*(weight l : Int)) +
((bellman R h : Int) - R*(weight h : Int)) ≤
(bellman R (.branch s l h) : Int) - R*(weight (.branch s l h) : Int) := by
have hi := Int.ofNat_le.mpr (Nat.le_max_right (reward R s*(weight l+weight h))
(bellman R l + bellman R h))
simp only [Int.natCast_add] at hi
simp only [bellman, branchWeight, Int.natCast_add, Int.mul_add]
omega
theorem draw_red (R r : Nat) : mass R r 0 ≤ mass R (r+1) 0 := by
simpa only [mass, deck.eq_2, bellman.eq_1, weight, paths.eq_1, List.length_nil,
Int.natCast_zero, Int.mul_zero, Int.sub_zero, Int.add_zero] using
drawBranch R (r+1,0) (deck r 0) .empty
theorem draw_both (R r b : Nat) :
mass R r (b+1) + mass R (r+1) b ≤ mass R (r+1) (b+1) := by
simpa only [mass, deck.eq_4] using drawBranch R (r+1,b+1) (deck r (b+1)) (deck (r+1) b)
/-- The comparison works with real or rational lower bounds. These four laws
are the entire ordered-additive interface needed in the induction. Taking
`embed k = scale * k` also allows integer fixed-point certificates. -/
structure OrderedEmbedding (A : Type) [LE A] [Add A] where
embed : Int → A
trans : ∀ {x y z : A}, x ≤ y → y ≤ z → x ≤ z
mono : ∀ {x y : Int}, x ≤ y → embed x ≤ embed y
add : ∀ x y : Int, embed (x+y) = embed x + embed y
addMono : ∀ {x y u v : A}, x ≤ y → u ≤ v → x+u ≤ y+v
/-- Integer column of the first stopping state. With the fixed parity of the
score, a frontier moving one score unit per step advances by at most one
column. Only the upper bound on its increments is needed. -/
structure Frontier (T : Nat) where
column : Nat → Nat
advance : ∀ t, T ≤ t → column (t+1) ≤ column t + 1
physical : ∀ t, T < t → column t < t
/-- Coefficients after multiplication by (1+z)^k. Their initial series may
be infinite, signed and nonintegral. At the negative physical edge the
missing coefficient is zero, so the coefficient in column zero is fixed. -/
def heat {A : Type} [Add A] (initial : Nat → A) : Nat → Nat → A
| 0, m => initial m
| k+1, 0 => heat initial k 0
| k+1, m+1 => heat initial k (m+1) + heat initial k m
variable {A : Type} [LE A] [Add A]
/-- Discrete free-boundary comparison with an actual optimal stopping
value. The input series is the comparator at cutoff. Its coefficients
at every later contact must lie below immediate exercise. No assumption
is needed on the far negative tail at later times or on the positive
physical edge, which the continuation region cannot reach. -/
theorem lower_from_cutoff (core : OrderedEmbedding A) (T R : Nat) (wall : Frontier T)
(initial : Nat → A)
(cut : ∀ r b, r+b = T → r ≤ R → b < wall.column T →
initial b ≤ core.embed (mass R r b))
(contact : ∀ k r b, r+b = T+k → r ≤ R → b = wall.column (T+k) →
heat initial k b ≤ core.embed (stopMass r b)) :
∀ k r b, r+b = T+k → r ≤ R → b ≤ wall.column (T+k) →
heat initial k b ≤ core.embed (mass R r b) := by
intro k
induction k with
| zero =>
intro r b ht hr hb
by_cases heq : b = wall.column (T+0)
· exact core.trans (contact 0 r b ht hr heq) (core.mono (stop_le_mass R r b hr))
· simp only [Nat.add_zero] at heq hb
exact cut r b ht hr (by omega)
| succ k ih =>
intro r b ht hr hb
by_cases heq : b = wall.column (T+(k+1))
· exact core.trans (contact (k+1) r b ht hr heq) (core.mono (stop_le_mass R r b hr))
have hw := wall.advance (T+k) (by omega)
have hp := wall.physical (T+(k+1)) (by omega)
have hprev : b ≤ wall.column (T+k) := by
have h : T+k+1 = T+(k+1) := by omega
rw [h] at hw
omega
cases r with
| zero => omega
| succ r =>
cases b with
| zero =>
exact core.trans (ih r 0 (by omega) (by omega) hprev) (core.mono (draw_red R r))
| succ b =>
apply core.trans (core.addMono (ih r (b+1) (by omega) (by omega) hprev)
(ih (r+1) b (by omega) hr (by omega)))
rw [← core.add]
exact core.mono (draw_both R r b)
/-- The conclusion uses the closed-form numerator of the original game. -/
theorem balanced_lower (core : OrderedEmbedding A) (T n k : Nat) (wall : Frontier T)
(initial : Nat → A)
(cut : ∀ r b, r+b = T → r ≤ n → b < wall.column T →
initial b ≤ core.embed (mass n r b))
(contact : ∀ i r b, r+b = T+i → r ≤ n → b = wall.column (T+i) →
heat initial i b ≤ core.embed (stopMass r b))
(size : n+n = T+k) (inside : n ≤ wall.column (T+k)) :
heat initial k n ≤ core.embed
((closedNumerator n n : Int) - n * (weight (deck n n) : Int)) := by
rw [closedNumerator_eq_bellman]
exact lower_from_cutoff core T n wall initial cut contact k n n size (by omega) inside
omit [LE A] in
/-- The usual physical tail convention and interior Pascal recurrence already
identify any proposed analytic formula with the heat comparator. -/
theorem heat_unique (initial : Nat → A) (candidate : Nat → Nat → A)
(base : ∀ m, candidate 0 m = initial m)
(edge : ∀ k, candidate (k+1) 0 = candidate k 0)
(pascal : ∀ k m, candidate (k+1) (m+1) = candidate k (m+1) + candidate k m) :
∀ k m, candidate k m = heat initial k m := by
intro k
induction k with
| zero => exact base
| succ k ih => intro m; cases m <;> simp [edge, pascal, ih, heat]
end Problem14.GameLower
~~~
#### `asmproof/GameLowerKernel.lean`
~~~lean
import asmproof.GameLowerTaylor
/-! Pointwise upper-error controls for the scaled binomial Laplace integral. -/
namespace Problem14.LowerKernel
open Real Problem14.UpperReal Problem14.LowerTaylor
private theorem tanh_d (v : ℝ) : HasDerivAt tanh (1-tanh v^2) v := by
have d := (Real.hasDerivAt_sinh v).div (Real.hasDerivAt_cosh v) (Real.cosh_pos v).ne'
convert d using 1
· funext z; exact Real.tanh_eq_sinh_div_cosh z
· rw [Real.tanh_eq_sinh_div_cosh]
field_simp [(cosh_pos v).ne']; nlinarith only [Real.cosh_sq_sub_sinh_sq v]
theorem logcosh_bounds (v : ℝ) (hv : 0≤v) :
v^2/2-v^4/12 ≤ log (cosh v) ∧ log (cosh v) ≤ v^2/2 := by
have tx (x : ℝ) (hx : 0≤x) : tanh x ≤ x := by
have hh := advance (f:=fun z => z-tanh z) (d:=fun z=>tanh z^2) hx
(fun z=>by convert (hasDerivAt_id z).sub (tanh_d z) using 1 <;> simp <;> ring)
(fun z _ _=>sq_nonneg _)
simpa using hh
have tl (x : ℝ) (hx : 0≤x) : x-x^3/3 ≤ tanh x := by
have hh := advance (f:=fun z=>tanh z-z+z^3/3) (d:=fun z=>z^2-tanh z^2) hx
(fun z=>by convert ((tanh_d z).sub (hasDerivAt_id z)).add (((hasDerivAt_id z).pow 3).div_const 3) using 1 <;> simp <;> ring)
(fun z hz _=>by
have hn : 0≤tanh z := by rw [tanh_eq_sinh_div_cosh]; positivity
exact sub_nonneg.mpr ((sq_le_sq₀ hn hz.le).mpr (tx z hz.le)))
simp at hh; linarith
have hh := advance (f:=fun z=>log (cosh z)-z^2/2+z^4/12)
(d:=fun z=>tanh z-z+z^3/3) hv (fun z=>by
convert (((hasDerivAt_cosh z).log (cosh_pos z).ne').sub (((hasDerivAt_id z).pow 2).div_const 2)).add
(((hasDerivAt_id z).pow 4).div_const 12) using 1 <;> simp [tanh_eq_sinh_div_cosh] <;> ring)
(fun z hz _=>by dsimp; linarith [tl z hz.le])
simp at hh
have hi := log_le_log (cosh_pos v) (cosh_le_exp_half_sq v)
rw [log_exp] at hi
exact ⟨by linarith,hi⟩
noncomputable def excess (s u : ℝ) := u^2/2-s^2*log (cosh (u/s))
theorem quartic {s u : ℝ} (hs : 0 linarith
private theorem delta (s y u : ℝ) : lapKernel s y u-exp (y*u-u^2/2)
= (1-exp (-excess s u))*lapKernel s y u := by
have e : exp (-excess s u) * lapKernel s y u = exp (y*u-u^2/2) := by
unfold lapKernel; rw [←exp_add]; congr 1; dsimp [excess]; ring
rw [sub_mul,one_mul,e]
private theorem less {s y u : ℝ} (hs : 0 ring
theorem middle_bound {s y u : ℝ} (hs : 0.2 ht) (sq_nonneg u)]
have h : lapKernel s y u≤exp (y*u-5*u^2/12) := by
unfold lapKernel; apply exp_le_exp.mpr; dsimp [excess] at b; linarith
apply (less hs hu).trans
convert mul_le_mul_of_nonneg_left h (show 0≤u^4/(12*s^2) by positivity) using 1
ring
end Problem14.LowerKernel
~~~
#### `asmproof/GameLowerMoment.lean`
~~~lean
import Brownian
/-! A fourth-moment bound uniform throughout the possible alpha interval.
Translation and parity evaluate the full-line shifted Gaussian moment. -/
namespace Problem14.LowerMoment
open Real MeasureTheory Set
open P14Quote.Coefficient
private noncomputable def g (u : ℝ) := exp (-(1/2)*u^2)
private noncomputable def mon (k : ℕ) (u : ℝ) := u^k*g u
private theorem int_mon (k : ℕ) : Integrable (mon k) := by
simpa only [mon,g,Real.rpow_natCast] using
(integrable_rpow_mul_exp_neg_mul_sq (b:=(1/2:ℝ)) (by norm_num)
(s:=(k:ℝ)) (by linarith [Nat.cast_nonneg (α:=ℝ) k]))
private theorem even_mon (k : ℕ) : (∫ u, mon (2*k) u) = 2*moment (2*k) := by
simpa only [moment,mon,g,pow_mul,sq_abs] using
(integral_comp_abs (f:=fun u:ℝ => mon (2*k) u))
private theorem odd_mon (k : ℕ) : (∫ u, mon (2*k+1) u) = 0 := by
let f := mon (2*k+1)
have reflection := integral_neg_eq_self f volume
have eqn : (fun u:ℝ => f (-u)) = fun u => -(f u) := by
funext u
dsimp [f,mon,g]
simp only [pow_succ _ (2*k),pow_mul,neg_sq]
ring
rw [eqn,integral_neg] at reflection
change - (∫ u, mon (2*k+1) u) = ∫ u, mon (2*k+1) u at reflection
linarith
private theorem translated (a : ℝ) :
(∫ u, (u+a)^4*g u) = 2*sqrt (π/2)*(a^4+6*a^2+3) := by
have funcs : (fun u => (u+a)^4*g u) = fun u =>
mon 4 u + (4*a)*mon 3 u + (6*a^2)*mon 2 u + (4*a^3)*mon 1 u + (a^4)*mon 0 u := by
funext u; unfold mon; ring
rw [funcs]
have h4 := int_mon 4
have h3 := (int_mon 3).const_mul (4*a)
have h2 := (int_mon 2).const_mul (6*a^2)
have h1 := (int_mon 1).const_mul (4*a^3)
have h0 := (int_mon 0).const_mul (a^4)
have e1 := integral_add h4 h3
have e2 := integral_add (h4.add h3) h2
have e3 := integral_add ((h4.add h3).add h2) h1
have e4 := integral_add (((h4.add h3).add h2).add h1) h0
simp only [Pi.add_apply] at e1 e2 e3 e4
rw [e4,e3,e2,e1]
simp only [integral_const_mul]
have m4 : (∫ u, mon 4 u)=2*moment 4 := even_mon 2
have m3 : (∫ u, mon 3 u)=0 := odd_mon 1
have m2 : (∫ u, mon 2 u)=2*moment 2 := even_mon 1
have m1 : (∫ u, mon 1 u)=0 := odd_mon 0
have m0 : (∫ u, mon 0 u)=2*moment 0 := even_mon 0
have t4 : moment 4 = ((2:ℝ)+1)*moment 2 := moment_step 2
have t2 : moment 2 = ((0:ℝ)+1)*moment 0 := by simpa using moment_step 0
rw [m4,m3,m2,m1,m0,t4,t2,moment_zero]
norm_num
ring
private theorem full (a : ℝ) :
(∫ u:ℝ, u^4*exp (a*u-u^2/2)) = exp (a^2/2)*(2*sqrt (π/2)*(a^4+6*a^2+3)) := by
rw [←translated,←integral_const_mul, ←integral_add_right_eq_self
(fun u:ℝ => u^4*exp (a*u-u^2/2)) a]
congr 1
funext u
unfold g
rw [show a*(u+a)-(u+a)^2/2 = a^2/2+(-(1/2)*u^2) by ring,exp_add]
ring
private theorem int_full (a : ℝ) : Integrable (fun u:ℝ => u^4*exp (a*u-u^2/2)) := by
have h : Integrable (fun u:ℝ => u^4*exp (-(1/4)*u^2)) := by
simpa only [Real.rpow_natCast] using
(integrable_rpow_mul_exp_neg_mul_sq (b:=(1/4:ℝ)) (by norm_num)
(s:=((4:ℕ):ℝ)) (by norm_num))
refine (h.const_mul (exp (a^2))).mono' (by apply Continuous.aestronglyMeasurable; fun_prop)
(ae_of_all _ fun u => ?_)
rw [Real.norm_eq_abs,abs_of_nonneg (by positivity),←mul_assoc,mul_comm (exp _) (u^4),
mul_assoc,←exp_add]
exact mul_le_mul_of_nonneg_left (exp_le_exp.mpr (by nlinarith [sq_nonneg (a-u/2)])) (by positivity)
/-- The numerical constants 0.8399 and 0.84 only localize the parameter.
No boundary equation or derivative estimates are needed. -/
theorem fourth_bound {a : ℝ} (lo : 0.8399 ≤ a) (hi : a ≤ 0.84) :
(1-a^2)*(∫ u in Ioi (0:ℝ), u^4*Real.exp (a*u-u^2/2)) ≤ 17/2 := by
have a0 : 0 ≤ a := by linarith
have asq : a^2 ≤ (0.84:ℝ)^2 := pow_le_pow_left₀ a0 hi _
have a4 : a^4 ≤ (0.84:ℝ)^4 := pow_le_pow_left₀ a0 hi _
have bsq : (0.8399:ℝ)^2 ≤ a^2 := pow_le_pow_left₀ (by norm_num) lo _
have nn : 0 ≤ 1-a^2 := by linarith
have reduced := setIntegral_le_integral (s:=Ioi (0:ℝ)) (int_full a)
(ae_of_all _ fun u => by positivity)
rw [full] at reduced
have ep : exp (a^2/2) ≤ 1.44 := by
apply (exp_le_exp.mpr (show a^2/2 ≤ 0.36 by linarith)).trans
have q := Real.exp_bound' (x:=0.36) (by norm_num) (by norm_num) (n:=4) (by decide)
norm_num [Finset.sum_range_succ,Nat.factorial_succ] at q ⊢
linarith
have s : sqrt (π/2) ≤ 1.26 := by
apply Real.sqrt_le_iff.mpr
constructor
· norm_num
· linarith [Real.pi_lt_d2]
have poly : a^4 + 6*a^2+3 ≤ (0.84:ℝ)^4+6*0.84^2+3 := by linarith
calc
_ ≤ (1-a^2)*(exp (a^2/2)*(2*sqrt (π/2)*(a^4+6*a^2+3))) := mul_le_mul_of_nonneg_left reduced nn
_ ≤ (1-(0.8399:ℝ)^2)*(1.44*(2*1.26*(0.84^4+6*0.84^2+3))) := by gcongr
_ ≤ _ := by norm_num
end Problem14.LowerMoment
~~~
#### `asmproof/GameLowerPrice.lean`
~~~lean
import asmproof.GameCalibration
import Coefficient
/-! Real-valued specialization of the certified cutoff to its exact coefficient,
physical frontier and cash price. All ordinary finite-table computation is
encapsulated in 'test', whose one-pass soundness is proved in GameCalibration. -/
namespace Problem14.GameLowerPrice
open GameComparison GameMoments GameFractional GameCalibration GameCutoff
theorem column_cut (a : ℝ) (hu : a≤21/25) : column a time ≤ 32876 := by
apply Nat.le_of_lt_succ
unfold column
apply (Nat.floor_lt' (by decide)).mpr
have hs : Real.sqrt ((time:ℝ)+1) ≤ 257 := by apply (Real.sqrt_le_left (by norm_num)).mpr; norm_num [time]
have mul := mul_le_mul hu hs (Real.sqrt_nonneg _) (by norm_num)
norm_num [time] at mul ⊢
linarith only [mul]
theorem coefficient_mono (t m : ℕ) (ht : 3≤t) {c : ℝ} (h : c≤cHi) : H c t m≤H cHi t m := by
rw [formula c t m ht, formula cHi t m ht]
linarith only [mul_le_mul_of_nonneg_right h
(show 0 ≤ (below t m : ℝ) + (t.choose m : ℝ)/2 by positivity)]
/-- State the residual analytic obstacle in aggregate units. All terms are
explicit functions of the number of remaining cards t and black cards m. -/
def Contact (a : ℝ) : Prop :=
∀ t : ℕ, time ≤ t → let m := column a t
H (2*(1-a^2)) t m ≤ (2*(m:ℝ)-t) * (t.choose m : ℝ)
/-- Layer assumption supplied by the proved finite lower policy. -/
def Attainable (low : ℕ→ℕ) : Prop := ∀ n r b : ℕ, r+b=time → r≤n → b≤32875 →
low b * ways r b ≤ scale * total n r b
theorem lower_from_table (low : ℕ→ℕ) (valid : Attainable low) (pass : test low = true)
(a : ℝ) (ha : 0≤a) (hu : a≤1)
(root : HasSum (P14Quote.Coefficient.term (Real.sqrt (Real.pi/2)) a) (Real.sqrt (Real.pi/2)))
(contact : Contact a) (n : ℕ) (hn : 32768≤n) :
(1-a^2)*Real.sqrt Real.pi*Real.sqrt n -
(137/1000)/(2*(n:ℝ)+1)^((1:ℝ)/5) ≤ price n := by
obtain ⟨lo,hi⟩ := P14Quote.Coefficient.series_root_bounds ha hu root
have ah : a≤21/25 := hi.trans (by norm_num [P14Quote.Coefficient.xHi])
have ch : 2*(1-a^2) ≤ cHi := by
have lowSq := pow_le_pow_left₀ (by norm_num [P14Quote.Coefficient.xLo] : (0:ℝ)≤P14Quote.Coefficient.xLo) lo 2
calc
_ ≤ 2*(1-(P14Quote.Coefficient.xLo:ℝ)^2) := by linarith
_ ≤ cHi := by norm_num [P14Quote.Coefficient.xLo,cHi,hi,GameCalibration.hi,divisor]
have cc : 0≤2*(1-a^2) := by nlinarith [mul_nonneg (sub_nonneg.mpr hu) (add_nonneg ha zero_le_one)]
have cut (r b : ℕ) (h : r+b=time) (hr : r≤n) (inside : b
#### `asmproof/GameLowerTaylor.lean`
~~~lean
import asmproof.UpperGaussian
/-! The second-order cancellation at the lower stopping boundary; valid
uniformly on its entire parity strip 0 ≤ a-y ≤ 2/s. -/
namespace Problem14.LowerTaylor
open Set Real Problem14.UpperReal
theorem advance {f d : ℝ → ℝ} {a b : ℝ} (ab : a≤b)
(hf : ∀ x, HasDerivAt f (d x) x) (hd : ∀ x, a (hf x).continuousAt)).continuousOn
(fun x _ => hf x)
have p := hd z hz.1 hz.2
rw [h] at p
apply sub_nonneg.mp
have q := (le_div_iff₀ (sub_pos.mpr lt)).mp p
simpa using q
theorem cancellation {f d e g : ℝ → ℝ} {a y s : ℝ}
(fd : ∀ x, HasDerivAt f (d x) x) (dd : ∀ x, HasDerivAt d (e x) x)
(ed : ∀ x, HasDerivAt e (g x) x)
(zero : f a=0) (flat : d a=0) (curv : e a=2*a)
(bound : ∀ x, y≤x → x≤a → 0≤g x ∧ g x≤4)
(ya : y≤a) (spos : 04*z-e z) (d:=fun z=>4-g z) xa (fun z=> by
convert ((hasDerivAt_id z).const_mul 4).sub (ed z) using 1 <;> simp)
(by intro z xz za; dsimp; linarith [(bound z (by linarith) za.le).2])
have high := advance xa ed (by intro z xz za; exact (bound z (by linarith) za.le).1)
dsimp at low
rw [curv] at low high
constructor <;> linarith
have db (x : ℝ) (yx : y≤x) (xa : x≤a) : -2*a*(a-x)≤d x ∧ d x≤ -2*a*(a-x)+2*(a-x)^2 := by
have lo := advance (f:=fun z=>2*a*z-d z) (d:=fun z=>2*a-e z) xa (fun z=> by
convert ((hasDerivAt_id z).const_mul (2*a)).sub (dd z) using 1 <;> simp)
(by intro z xz za; dsimp; linarith [(eb z (by linarith) za.le).2])
have hi := advance (f:=fun z=>d z+2*a*(a-z)-2*(a-z)^2)
(d:=fun z=>e z-2*a+4*(a-z)) xa (fun z=> by
have dz := (hasDerivAt_const z a).sub (hasDerivAt_id z)
convert ((dd z).add (dz.const_mul (2*a))).sub ((dz.pow 2).const_mul 2) using 1 <;> simp <;> ring)
(by intro z xz za; dsimp; linarith [(eb z (by linarith) za.le).1])
dsimp at hi lo
rw [flat] at hi lo
constructor <;> nlinarith
have hi := advance (f:=fun z=>f z-a*(a-z)^2) (d:=fun z=>d z+2*a*(a-z)) ya (fun z=> by
have dz := (hasDerivAt_const z a).sub (hasDerivAt_id z)
convert (fd z).sub ((dz.pow 2).const_mul a) using 1 <;> simp <;> ring)
(by intro z yz za; dsimp; nlinarith [(db z yz.le za.le).1])
dsimp at hi
rw [zero] at hi
have jf : f y ≤ a*(a-y)^2 := by linarith
have h := add_le_add (mul_le_mul_of_nonneg_left jf spos.le) (db y le_rfl ya).2
have harmless := mul_nonpos_of_nonneg_of_nonpos (mul_nonneg a0 (sub_nonneg.mpr ya))
(sub_nonpos.mpr strip)
have t : s*f y + d y ≤ 2*(a-y)^2 := by nlinarith only [h,harmless]
apply t.trans
apply (le_div_iff₀ (sq_pos_of_pos spos)).2
nlinarith only [sq_le_sq₀ (mul_nonneg spos.le (sub_nonneg.mpr ya)) (by norm_num : (0:ℝ)≤2) |>.2 strip]
theorem profile_cancellation {a y s : ℝ} (a0 : 0≤a) (a1 : a≤1)
(root : (1-a^2)*profile a=a) (lo : 0≤y) (ya : y≤a) (hs : 0.2 a1]
have fd (x : ℝ) : HasDerivAt f (d x) x := by
convert (profile_deriv x).const_mul k using 1; dsimp [d,f]; ring
have dd (x : ℝ) : HasDerivAt d (e x) x := by
convert (hasDerivAt_const x k).add ((hasDerivAt_id x).mul (fd x)) using 1 <;> simp [e]
have ed (x : ℝ) : HasDerivAt e (g x) x := by
convert (fd x).add ((hasDerivAt_id x).mul (dd x)) using 1 <;> simp [g] <;> ring
have fa : f a=a := root
have da : d a=1 := by dsimp only [d]; rw [fa]; dsimp [k]; ring
have ea : e a=2*a := by dsimp only [e]; rw [fa,da]; ring
have fp (x : ℝ) (hx : 0≤x) : 0≤f x := mul_nonneg pos (profile_nonneg hx)
have dp (x : ℝ) (hx : 0≤x) : 0≤d x := add_nonneg pos (mul_nonneg hx (fp x hx))
have ep (x : ℝ) (hx : 0≤x) : 0≤e x := add_nonneg (fp x hx) (mul_nonneg hx (dp x hx))
apply cancellation (f:=fun x=>f x-x) (d:=fun x=>d x-1) (e:=e) (g:=g)
(fun x=>(fd x).sub (hasDerivAt_id x))
(fun x=>by simpa using (dd x).sub_const 1) ed (by simp [fa]) (by simp [da]) ea _ ya hs strip a0
intro x yx xa
have x0 := lo.trans yx
have dtop : d x ≤ 1 := da ▸ advance xa dd (by intro z xz _; exact ep z (x0.trans xz.le))
have etop : e x ≤ 2*a := ea ▸ advance xa ed (by
intro z xz _
have hz := x0.trans xz.le
exact add_nonneg (mul_nonneg (by norm_num) (dp z hz)) (mul_nonneg hz (ep z hz)))
have prod := mul_le_mul xa etop (ep x x0) a0
dsimp [g]; constructor
· exact add_nonneg (by linarith [dp x x0]) (mul_nonneg x0 (ep x x0))
· nlinarith [sq_le_sq₀ a0 (by norm_num : (0:ℝ)≤1) |>.2 a1]
end Problem14.LowerTaylor
~~~
#### `asmproof/GameMachinePrice.lean`
~~~lean
import QuoteEntry
import QuoteReal
import OutputCertificateReal
import VectorBatch
import asmproof.Game65536
import asmproof.GameExercise
import asmproof.UpperGame
/-! The literal-instruction scalar quote, the vector lane specification, and
the rendered-output certificate enclose the same finite optimal-stopping game.
The two finite Bellman certificates use Lean native evaluation. -/
namespace P14Entry
open P14Quote Problem14
open P14Quote.Coefficient (threshold)
noncomputable def K : ℝ := (1-threshold^2)*Real.sqrt Real.pi
private theorem weak {n fl fh h a b c d m s l u ds P Q}
(run : EntryReturns n fl fh h a b c d m s l u ds P) (implies : ∀ z, P z → Q z) :
EntryReturns n fl fh h a b c d m s l u ds Q := by
apply run.weaken
rintro l ⟨a,low,rest⟩
refine ⟨a,low,rest.weaken ?_⟩
rintro u ⟨b,high,d,dr,ret,z,final,out⟩
exact ⟨b,high,d,dr,ret,z,final,implies z out⟩
/-- No analytic hypotheses or numerical root oracles. This statement also
holds for mathematical natural numbers beyond the 64-bit machine domain. -/
theorem game_bounds (n : ℕ) (hn : 32768≤n) :
K*Real.sqrt n-(137/1000)/(2*(n:ℝ)+1)^((1:ℝ)/5) ≤ GameComparison.price n ∧
GameComparison.price n ≤ K*Real.sqrt ((n:ℝ)+1/2) := by
have root := Coefficient.threshold_spec
have a1 : threshold ≤ 1 := (Coefficient.brownian_root_bounds root.1 root.2).2.trans
(by norm_num [Coefficient.xHi])
have lower := Game65536.lower_price threshold root.1 a1
(Coefficient.taylor_root_equation (Coefficient.laplace_taylor root.1) root.2)
GameExercise.threshold_contact n hn
have upper := UpperReal.gaussian_game_upper n (by omega)
rw [Real.sqrt_mul Real.pi_pos.le] at upper
exact ⟨lower,by dsimp [K]; linarith only [upper]⟩
theorem cash_endpoints {n : ℕ} (hn : 32768≤n) (hu : n<2^64) :
(lowerMicro n (floorSqrt (inputLo n)) (debit n) : ℝ)/10^6 ≤ GameComparison.price n ∧
GameComparison.price n ≤ (upperMicro n (floorSqrt (inputHi n)) : ℝ)/10^6 := by
have fit := radicands_fit128 hu
have v := game_bounds n hn
have k := Coefficient.threshold_coefficient
exact real_enclosure hn (floorSqrt_spec _ fit.1) (floorSqrt_spec _ fit.2)
(debit_spec n (by omega)) k.1 k.2 v.1 v.2
theorem machine_encloses_game {n f g hint : ℕ} (hn : 32768≤n) (hu : n<2^64)
(d0 d1 d2 d3 : ℕ) (fl : f<2^64) (fh : g<2^64) {mem : D.Table} (table : D.tableOK mem)
(s : M.State) (sl sh : R.CPU) (sd : D.State) :
EntryReturns n f g hint d0 d1 d2 d3 mem s sl sh sd (fun z =>
(z.outLo:ℝ)/10^6 ≤ GameComparison.price n ∧ GameComparison.price n ≤ (z.outHi:ℝ)/10^6) := by
apply weak (quote_entry_correct (hint:=hint) hn hu d0 d1 d2 d3 fl fh table s sl sh sd)
intro z hz
rw [hz.1,hz.2]
exact cash_endpoints hn hu
theorem vector_encloses_game {mem : Nat → Nat} (hm : P14VectorLane.tableOK mem)
(n jl jh seed : ℕ) (hn : 32768≤n) (hu : n<2^64) :
let p := P14VectorEntry.lane mem n jl jh seed
(p.1:ℝ)/10^6 ≤ GameComparison.price n ∧ GameComparison.price n ≤ (p.2:ℝ)/10^6 := by
rw [P14VectorEntry.lane_correct hm n jl jh seed hn hu]
exact cash_endpoints hn hu
/-- Includes both actual eight-lane mask repair loops and the exact threshold
table. Each of the eight outputs bounds the value of its own original game. -/
theorem batch_encloses_games (n jl jh seed : Fin 8 → ℕ)
(domain : ∀ i, 32768 ≤ n i ∧ n i < 2^64) (i : Fin 8) :
let p := P14VectorBatch.run (fun j=>P14Debit.threshold (j+17)) n jl jh seed i
(p.1:ℝ)/10^6 ≤ GameComparison.price (n i) ∧ GameComparison.price (n i) ≤ (p.2:ℝ)/10^6 := by
rw [P14VectorBatch.exact_table n jl jh seed domain]
exact cash_endpoints (domain i).1 (domain i).2
/-- Any rendered record accepted by the independent verifier certifies the
true game price and every nearest cent, including either convention at a tie. -/
theorem printed_game {o : Record} {w : Witness} (h : o.Check w) :
let V := GameComparison.price o.pairs
(o.lo:ℝ)/10^6 ≤ V ∧ V ≤ (o.hi:ℝ)/10^6 ∧
∀ c : ℕ, (c:ℝ)-1/2 ≤ 100*V → 100*V ≤ (c:ℝ)+1/2 →
(o.lowCent ≤ c ∧ c ≤ o.highCent) ∧ (o.single = true → c = o.lowCent) := by
have v := game_bounds o.pairs h.1
have k := Coefficient.threshold_coefficient
exact o.realPrice h k.1 k.2 v.1 v.2
#print axioms machine_encloses_game
#print axioms printed_game
end P14Entry
~~~
#### `asmproof/GameMoments.lean`
~~~lean
import asmproof.GameComparison
/-! Identification of the comparator in GameComparison with the conditional
price formulas used by the numerical and analysis certificates. -/
namespace Problem14.GameMoments
open GameComparison GameFractional
def below (t : ℕ) : ℕ → ℕ
| 0 => 0
| m+1 => below t m + t.choose m
private theorem below_step (t m : ℕ) :
below (t+1) (m+1) = below t (m+1) + below t m := by
induction m with
| zero => simp [below]
| succ m ih =>
rw [below.eq_2 (t+1), ih, below.eq_2 t (m+1), Nat.choose_succ_succ]
simp only [Nat.succ_eq_add_one, below.eq_2 t m]
omega
private theorem initial_below (m : ℕ) : below 0 (m+1)=1 := by
induction m with
| zero => simp [below]
| succ m ih => simp [below.eq_2 0 (m+1), ih]
theorem mid_cdf (t m : ℕ) : Upper.heat Upper.mid t m = 2*(below t m : ℤ)+(t.choose m : ℤ) := by
induction t generalizing m with
| zero => cases m with
| zero => simp [below, Upper.mid, Upper.heat]
| succ m => simp [Upper.heat, Upper.mid, initial_below]; omega
| succ t ih =>
cases m with
| zero =>
have hm : ∀ t j, j<0 → Upper.heat Upper.mid t j=0 := by
intro i; induction i with
| zero => intro j h; simp [Upper.heat, Upper.mid, h]
| succ i ih' => intro j h; rw [Upper.heat, ih' j h, ih' (j-1) (by omega)]; rfl
simpa [Upper.heat, hm t (-1) (by decide), below] using ih 0
| succ m =>
rw [Upper.heat, Int.natCast_succ, Int.add_sub_cancel, ← Int.natCast_succ, ih, ih, below_step,
Nat.choose_succ_succ]
simp only [Nat.succ_eq_add_one]; push_cast; omega
noncomputable def tilt (t x : ℝ) : ℝ :=
-x/t + 9000*(x^3-(3*t-2)*x)/(t*(t-1)*(t-2))
private theorem tilt_step (t m : ℝ) (h : 3 ≤ t) :
(t+1)*tilt (t+1) (2*(m+1)-(t+1)) =
(t-m)*tilt t (2*(m+1)-t) + (m+1)*tilt t (2*m-t) := by
unfold tilt
field_simp [show t≠0 by linarith, show t-1≠0 by linarith, show t-2≠0 by linarith,
show t+1≠0 by linarith, show t+1-1≠0 by linarith, show t+1-2≠0 by linarith]
ring
private theorem left_tilt (t : ℝ) (h : 3 ≤ t) : tilt t (-t) = -8999 := by
unfold tilt
field_simp [show t≠0 by linarith, show t-1≠0 by linarith, show t-2≠0 by linarith]
ring
private theorem binomial_children (t m : ℕ) :
((t:ℝ)+1)*(t.choose (m+1) : ℝ) = ((t:ℝ)-m)*((t+1).choose (m+1) : ℝ) ∧
((t:ℝ)+1)*(t.choose m : ℝ) = ((m:ℝ)+1)*((t+1).choose (m+1) : ℝ) := by
constructor
· by_cases h : m≤t
· have a := Nat.choose_mul_succ_eq t (m+1)
rw [show t+1-(m+1)=t-m by omega] at a
obtain e : (t.choose (m+1) : ℝ)*(t+1) = ((t+1).choose (m+1) : ℝ)*((t:ℝ)-m) := by
rw [← Nat.cast_sub h]; exact_mod_cast a
linarith only [e]
· simp [Nat.choose_eq_zero_of_lt (show t intro j hj; unfold Upper.heat oddSeed; omega
| succ i ih => intro j h; rw [Upper.heat, ih j h, ih (j-1) (by omega)]; rfl
induction k with
| zero => decide
| succ k ih => simp [Upper.heat, ih, ghost k (-1) (by decide)]
theorem odd_moment (k m : ℕ) : (Upper.heat oddSeed k m : ℝ) =
((3+k).choose m : ℝ) * tilt (3+k) (2*m-(3+k)) := by
induction k generalizing m with
| zero =>
by_cases h : m<4
· interval_cases m <;> norm_num [tilt, Upper.heat, oddSeed, Nat.choose]
· rw [Nat.choose_eq_zero_of_lt (by omega)]; simp only [Upper.heat, oddSeed, Nat.cast_zero, zero_mul, Int.cast_eq_zero]
omega
| succ k ih =>
let t := 3+k
have ht : (3:ℝ)≤(t:ℝ) := by dsimp [t]; exact_mod_cast (show 3≤3+k by omega)
have htp : (t:ℝ)+1≠0 := by positivity
rw [show (3:ℝ)+(↑(k+1):ℝ)=(↑(t+1):ℝ) by simp [t]; ring]
change _ = ((t+1).choose m : ℝ)*tilt (t+1:ℕ) (2*m-(t+1:ℕ))
cases m with
| zero =>
rw [Int.natCast_zero, odd_at_zero]
simp only [Nat.cast_zero,Nat.choose_zero_right,Nat.cast_one,one_mul,mul_zero,zero_sub]
rw [left_tilt _ (by push_cast; linarith)]
norm_num
| succ m =>
rw [Upper.heat, Int.natCast_succ, Int.add_sub_cancel, ← Int.natCast_succ, Int.cast_add,
ih, ih]
change (t.choose (m+1):ℝ)*tilt (3+k) _ + (t.choose m:ℝ)*tilt (3+k) _ = _
have htc : (3:ℝ)+k=(t:ℝ) := by simp [t]
rw [htc]
push_cast
apply (mul_left_cancel₀ htp)
obtain ⟨h₁,h₂⟩ := binomial_children t m
rw [mul_add, ←mul_assoc, h₁, ←mul_assoc, h₂]
have id := tilt_step t m ht
linear_combination - (((t+1).choose (m+1) : ℝ))*id
theorem formula (c : ℝ) (t m : ℕ) (h : 3≤t) : H c t m =
c*((below t m : ℝ) + (t.choose m : ℝ)/2) +
(t.choose m : ℝ)*tilt t (2*m-t) - C t m/5 := by
rw [H, mid_cdf, odd_moment, show 3+(t-3)=t by omega]
have e : (3:ℝ)+((t-3:ℕ):ℝ)=t := by exact_mod_cast (show 3+(t-3)=t by omega)
rw [e]; push_cast; ring
end Problem14.GameMoments
~~~
#### `asmproof/GamePositivity.lean`
~~~lean
import asmproof.GameComparison
import Brownian
import Mathlib.Tactic.Positivity
import Mathlib.Tactic.Linarith
import Mathlib.Tactic.FieldSimp
import Mathlib.Tactic.Ring
/-! A discrete Sturm comparison for the fractional exercise coefficient.
The quintic and all its certificates have rational coefficients. This
proof uses neither Fourier inversion nor asymptotic error bounds. -/
namespace Problem14.GamePositivity
open GameFractional GameComparison
private noncomputable def edge : ℝ := 169/200
private noncomputable def testFn (z : ℝ) := 3861*z^5 - 38022*z^4 + 167353*z^3 - 422618*z^2 + 1000000*z^1 + 169
private noncomputable def q0 (z : ℝ) := (-88803/5)*z^5 + (6127677/40)*z^4 + (-12160304/25)*z^3 + (128832931/200)*z^2 + (-15505321/50)*z^1 + (-842/5)
private noncomputable def q1 (z : ℝ) := -154440*z^3 + (3694269/5)*z^2 + (-25725736/25)*z^1 + (13073857/50)
private noncomputable def q2 (z : ℝ) := -61776*z^1 + (1305018/25)
private theorem test_pos (z : ℝ) (hz : 0≤z) : 1 ≤ testFn z := by
by_cases hb1 : z≤1
· have hy : 0≤(1-z) := by linarith only [hb1]
have h : 0 ≤ 168*(1-z)^5 + 1000840*z*(1-z)^4 + 3579062*z^2*(1-z)^3 + 4901179*z^3*(1-z)^2 + 3029670*z^4*(1-z) + 710742*z^5 := by positivity
unfold testFn; linarith only [h]
by_cases hb2 : z≤2
· have hx : 0≤(z-1) := by linarith only [hb1]
have hy : 0≤(2-z) := by linarith only [hb2]
have h : 0 ≤ 710742*(2-z)^5 + 4077750*(z-1)*(2-z)^4 + 9093499*(z-1)^2*(2-z)^3 + 9975292*(z-1)^3*(2-z)^2 + 5408660*(z-1)^4*(2-z) + 1163720*(z-1)^5 := by positivity
unfold testFn; linarith only [h]
by_cases hb3 : z≤3
· have hx : 0≤(z-2) := by linarith only [hb2]
have hy : 0≤(3-z) := by linarith only [hb3]
have h : 0 ≤ 1163720*(3-z)^5 + 6228540*(z-2)*(3-z)^4 + 13254812*(z-2)^2*(3-z)^3 + 14048013*(z-2)^3*(3-z)^2 + 7427738*(z-2)^4*(3-z) + 1573578*(z-2)^5 := by positivity
unfold testFn; linarith only [h]
· have hx : 0≤(z-3) := by linarith only [hb3]
have h : 0 ≤ 1573578 + 440152*(z-3) + 72841*(z-3)^2 + 58579*(z-3)^3 + 19893*(z-3)^4 + 3861*(z-3)^5 := by positivity
unfold testFn; linarith only [h]
private theorem margin (z : ℝ) (hz : 0≤z) : q0 z+12*z^2+5 ≤ 0 := by
by_cases hb1 : z≤1
· have hy : 0≤(1-z) := by linarith only [hb1]
have h : 0 ≤ (817/5)*(1-z)^5 + (15546171/50)*z*(1-z)^4 + (23915321/40)*z^2*(1-z)^3 + (83230943/200)*z^3*(1-z)^2 + (12834511/100)*z^4*(1-z) + 17074*z^5 := by positivity
unfold q0; linarith only [h]
by_cases hb2 : z≤2
· have hx : 0≤(z-1) := by linarith only [hb1]
have hy : 0≤(2-z) := by linarith only [hb2]
have h : 0 ≤ 17074*(2-z)^5 + (4239489/100)*(z-1)*(2-z)^4 + (14470767/200)*(z-1)^2*(2-z)^3 + (1477461/8)*(z-1)^3*(2-z)^2 + (8606219/50)*(z-1)^4*(2-z) + (522353/10)*(z-1)^5 := by positivity
unfold q0; linarith only [h]
by_cases hb3 : z≤3
· have hx : 0≤(z-2) := by linarith only [hb2]
have hy : 0≤(3-z) := by linarith only [hb3]
have h : 0 ≤ (522353/10)*(3-z)^5 + (17511431/50)*(z-2)*(3-z)^4 + (179419917/200)*(z-2)^2*(3-z)^3 + (216716159/200)*(z-2)^3*(3-z)^2 + (64001489/100)*(z-2)^4*(3-z) + (4332524/25)*(z-2)^5 := by positivity
unfold q0; linarith only [h]
· have hx : 0≤(z-3) := by linarith only [hb3]
have h : 0 ≤ (4332524/25) + (22648991/100)*(z-3) + (51306167/200)*(z-3)^2 + (12328153/50)*(z-3)^3 + (4528683/40)*(z-3)^4 + (88803/5)*(z-3)^5 := by positivity
unfold q0; linarith only [h]
private theorem residual (z e : ℝ) (hz : 0≤z) (he : 0≤e) (hcap : e≤1/65536) :
q0 z + e*q1 z + e^2*q2 z ≤ 0 := by
have q₁ : q1 z ≤ 740000*z^2+262000 := by
unfold q1
nlinarith only [hz, sq_nonneg z, pow_nonneg hz 3]
have q₂ : q2 z ≤ 53000 := by unfold q2; linarith
have e₁ := mul_le_mul_of_nonneg_left q₁ he
have e₂ := mul_le_mul_of_nonneg_left q₂ (sq_nonneg e)
have a := mul_le_mul_of_nonneg_right hcap (sq_nonneg z)
have b : e^2 ≤ e := by nlinarith only [mul_nonneg he (sub_nonneg.mpr (show e≤1 by linarith))]
linarith only [margin z hz, e₁, e₂, a, b, hcap, sq_nonneg z]
private theorem weighted_shift (s z : ℝ) (hs : 0
refine ⟨by norm_num [C],?_⟩
intro _
have h := super ht 0 (by simpa using hz (j:=0) (by omega))
simpa [massB,C.eq_1,C.eq_2] using h
| succ m ih =>
obtain ⟨p,w⟩ := ih (by omega)
have w' := w hm
have p' : 0
#### `asmproof/GameSmallObstacle.lean`
~~~lean
import asmproof.UpperCentral
import Mathlib.Data.Nat.Choose.Basic
import Mathlib.Tactic.Linarith
import Mathlib.Algebra.Order.Ring.Int
/-! Small-score stopping obstacle for the exact, unnormalised card-game
Pascal recurrence. The maximal atom bound at row 256 propagates forever. -/
namespace Problem14.Upper
set_option maxRecDepth 6000
private theorem delta_left (t : Nat) (j : Int) (hj : j<0) : heat delta t j=0 := by
induction t generalizing j with
| zero => simp [heat, delta, show j ≠ 0 by omega]
| succ t ih => simp [heat, ih j hj, ih (j-1) (by omega)]
theorem delta_choose (t j : Nat) : heat delta t j=(t.choose j:Int) := by
induction t generalizing j with
| zero =>
cases j <;> simp [heat, delta, Nat.choose]
omega
| succ t ih =>
cases j with
| zero =>
change heat delta t (0:Nat) + heat delta t (-1) = _
rw [ih 0, delta_left t (-1) (by decide)]
simp
| succ j =>
simp only [Nat.choose_succ_succ, Int.natCast_add, Int.natCast_succ, heat,
Int.add_sub_cancel]
rw [← ih (j+1), ← ih j]
simp [Int.add_comm]
theorem cell_count_as_delta (t : Nat) (j : Int) : ((cell t j).1:Int) = heat delta t j := by
induction t generalizing j with
| zero => by_cases h : j=0 <;> simp [cell, heat, delta, h, empty]
| succ t ih => simp only [cell, advance, heat, Int.natCast_add, ih]
theorem atom_bound_sixteenth (t : Nat) (ht : 256 ≤ t) (j : Int) :
16 * heat delta t j ≤ 2^t := by
induction t, ht using Nat.le_induction generalizing j with
| base =>
by_cases hj : j<0
· rw [delta_left _ j hj]; decide
· obtain ⟨k,rfl⟩ := Int.eq_ofNat_of_zero_le (by omega : 0≤j)
have middle : Nat.choose 256 k ≤ Nat.choose 256 128 := Nat.choose_le_middle k 256
have base : 16*Nat.choose 256 128 ≤ 2^256 := by
rw [Nat.choose_eq_factorial_div_factorial (by decide : 128≤256)]
decide
rw [delta_choose]
omega
| succ t _ ih =>
rw [heat, pow_succ]
have h := ih j
have h' := ih (j-1)
omega
private theorem mid_increasing (t : Nat) {i j : Int} (h : i≤j) :
heat mid t i ≤ heat mid t j := by
induction t generalizing i j with
| zero =>
simp only [heat,mid]
omega
| succ t ih => exact Int.add_le_add (ih h) (ih (by omega : i-1≤j-1))
theorem mid_positive_half (t : Nat) (j : Int) (hj : (t:Int)≤2*j) :
2^t ≤ heat mid t j := by
let n := t / 2
by_cases he : t=2*n
· rw [he]
exact (mid_center n).symm.le.trans (mid_increasing _ (by dsimp [n] at *; omega))
· have ho : t=2*n+1 := by dsimp [n] at *; omega
rw [ho,heat,pow_succ]
have h₁ := mid_increasing (2*n) (by dsimp [n] at *; omega : (n:Int)≤j)
have h₂ := mid_increasing (2*n) (by dsimp [n] at *; omega : (n:Int)≤j-1)
rw [mid_center] at h₁ h₂
omega
/-- The entire nonpositive half and scores 1, 2, 3 satisfy the obstacle,
for every row from 256 on, including the physical card-deck boundaries. -/
theorem small_obstacle {t : Nat} (ht : 256≤t) (j : Int) (score : 2*j-(t:Int)≤3) :
200000*((2*j-(t:Int))*((cell t j).1:Int)) ≤ heat initial t j := by
have nonneg (i : Int) : 0 ≤ heat delta t i := by
apply heat_nonneg
intro k; unfold delta; split <;> decide
rw [cell_count_as_delta]
by_cases hx : 2*j-(t:Int)≤0
· have zero := Int.mul_nonpos_of_nonpos_of_nonneg hx (nonneg j)
have pos := heat_nonneg initial initial_nonneg t j
omega
· have xbound := Int.mul_le_mul_of_nonneg_right score (nonneg j)
have jcap := atom_bound_sixteenth t ht j
have prevcap := atom_bound_sixteenth t ht (j-1)
have left := nonneg (j-2)
have right := nonneg (j+1)
have midbound := mid_positive_half t j (by omega)
have hseed : initial = seed 58905 1 := funext initial_eq
rw [hseed]
change _ ≤ heat (fun i => 58905*mid i+1*bump i) t j
rw [heat_linear,bump_heat]
linarith only [midbound, xbound, jcap, prevcap, left, right, nonneg j]
theorem small_seed_obstacle {C D : Int} (hD : 0≤D) (hc : 58905*D≤C)
{t : Nat} (ht : 256≤t) (j : Int) (score : 2*j-(t:Int)≤3) :
(D*200000)*((2*j-(t:Int))*((cell t j).1:Int)) ≤ heat (seed C D) t j := by
have h := Int.mul_le_mul_of_nonneg_left (small_obstacle ht j score) hD
rw [← Int.mul_assoc] at h
refine h.trans ?_
have hmid := heat_nonneg mid (fun k => by unfold mid; repeat' first | decide | split) t j
have hcoef := Int.mul_le_mul_of_nonneg_right hc hmid
have hseed : initial = seed 58905 1 := funext initial_eq
rw [hseed]
unfold seed
rw [heat_linear,heat_linear,Int.one_mul,Int.mul_add,←Int.mul_assoc,Int.mul_comm D 58905]
omega
end Problem14.Upper
~~~
#### `asmproof/GameUpperPrice.lean`
~~~lean
import asmproof.GameComparison
import asmproof.UpperCutoff
/-! Propagation with the actual real-valued coefficient, including the ghosts
and the normalization to dollars. The unnormalized barrier is multiplied by
200000 to use exactly the same signed finite stencil as the integer cutoff. -/
namespace Problem14.GameUpperPrice
open Upper
noncomputable def barrier (c : ℝ) (t : ℕ) (j : ℤ) : ℝ :=
100000*c*(heat mid t j : ℤ) + (heat bump t j : ℤ)
private theorem next (c : ℝ) (t : ℕ) (j : ℤ) :
barrier c (t+1) j = barrier c t j + barrier c t (j-1) := by
simp only [barrier, heat, Int.cast_add]; ring
theorem dominates_initial {c : ℝ} (hc : 58905 ≤ 100000*c) (t : ℕ) (j : ℤ) :
(heat initial t j:ℝ) ≤ barrier c t j := by
have eq : initial = seed 58905 1 := funext initial_eq
have m₀ : ∀ j, 0 ≤ mid j := by intro j; unfold mid; split <;> first | decide | (split <;> decide)
have m : (0:ℝ) ≤ heat mid t j := by exact_mod_cast heat_nonneg mid m₀ t j
rw [eq,show seed 58905 1 = fun j => 58905*mid j + 1*bump j by rfl,heat_linear]
push_cast
unfold barrier
linarith only [mul_le_mul_of_nonneg_right hc m]
/-- The only analytic upper premise is the pointwise exercise inequality. -/
theorem upper_price {c : ℝ} (hc : 58905 ≤ 100000*c) (T n : ℕ) (hn : T≤2*n)
(cut : test T=true)
(stop : ∀ t : ℕ, T
by_cases out : j<0 ∨ (t:ℤ) omega
| succ t =>
have e := stop (t+1) (by omega) j (by omega) (by omega)
have p := ih t (by omega) (by omega) j
have q := ih t (by omega) (by omega) (j-1)
rw [next] at e ⊢
simp only [cell,advance,Int.cast_max,Int.cast_add,Int.cast_mul] at e ⊢
rw [mul_max_of_nonneg _ _ (by norm_num)]
exact max_le e (by linarith only [p,q])
have g := prop (2*n) hn n
have a : (cell (2*n) n).2 = (closedNumerator n n : ℤ)-n*(weight (deck n n):ℤ) := by
rw [two_mul,cell_eq_game n n n (by omega),closedNumerator_eq_bellman]; rfl
rw [a,barrier,mid_center] at g
have b : (heat bump (2*n) n : ℝ) ≤ 0 := by exact_mod_cast bump_center n
let w := weight (deck n n)
have wpos : (0:ℝ)< w := by
dsimp [w]; rw [GameComparison.deck_count]; exact_mod_cast Nat.choose_pos (by omega : n≤n+n)
have pre : GameComparison.price n ≤ (c/2)*GameWallis.invMass n := by
unfold GameComparison.price GameWallis.invMass
rw [GameComparison.deck_count,←two_mul,←Nat.centralBinom_eq_two_mul_choose]
change (0:ℝ) < weight (deck n n) at wpos
rw [GameComparison.deck_count,←two_mul,←Nat.centralBinom_eq_two_mul_choose] at g wpos
push_cast at g
rw [←mul_div_assoc,div_le_div_iff_of_pos_right wpos]
linarith only [g,b]
exact pre.trans (mul_le_mul_of_nonneg_left (GameWallis.enclosure n).2 (by linarith))
end Problem14.GameUpperPrice
~~~
#### `asmproof/GameWallis.lean`
~~~lean
import Mathlib.Data.Real.Pi.Wallis
import Mathlib.Data.Nat.Choose.Central
import Mathlib.Data.Real.Sqrt
import Mathlib.Tactic.FieldSimp
import Mathlib.Tactic.Linarith
import Mathlib.Tactic.Positivity
/-! Finite Wallis inequalities for the central mass of a balanced simple walk. -/
namespace Problem14.GameWallis
noncomputable def invMass (n : ℕ) : ℝ := 2^(2*n) / (n.centralBinom : ℝ)
theorem squared (n : ℕ) : invMass n ^ 2 = (2*n+1)*Real.Wallis.W n := by
have choose : (n.centralBinom:ℝ) * n.factorial * n.factorial = (2*n).factorial := by
exact_mod_cast (show n.centralBinom * n.factorial * n.factorial = (2*n).factorial by
simpa only [Nat.centralBinom, two_mul] using Nat.add_choose_mul_factorial_mul_factorial n n)
have nz : (n.centralBinom:ℝ) ≠ 0 := by exact_mod_cast Nat.centralBinom_ne_zero n
have fac : (n.factorial:ℝ) ≠ 0 := by exact_mod_cast Nat.factorial_ne_zero n
rw [invMass,Real.Wallis.W_eq_factorial_ratio,← choose,show (2:ℝ)^(4*n)=((2:ℝ)^(2*n))^2 by rw [←pow_mul]; congr 1; omega]
field_simp
ring
/-- Reciprocal central mass, including the degenerate zero-card deck. -/
theorem enclosure (n : ℕ) :
Real.sqrt (Real.pi*n) ≤ invMass n ∧ invMass n ≤ Real.sqrt (Real.pi*((n:ℝ)+1/2)) := by
have nonneg : 0 ≤ invMass n := by unfold invMass; positivity
have f : 0 < (2*(n:ℝ)+2) := by positivity
have l := Real.Wallis.le_W n
rw [div_mul_eq_mul_div, div_le_iff₀ f] at l
have u := Real.Wallis.W_le n
have wl := mul_le_mul_of_nonneg_left l (show (0:ℝ) ≤ 2*n+1 by positivity)
have wu := mul_le_mul_of_nonneg_left u (show (0:ℝ) ≤ 2*n+1 by positivity)
have iden := squared n
constructor
· apply (Real.sqrt_le_left nonneg).2
apply (le_of_mul_le_mul_right _ f)
nlinarith only [wl,iden,Real.pi_pos]
· apply (Real.le_sqrt nonneg (by positivity)).2
nlinarith only [iden,wu]
end Problem14.GameWallis
~~~
#### `asmproof/OutputCertificate.lean`
~~~lean
import Quote
/-! Check the integers printed in an individual priceasm stdout record.
The verifier only trusts Lean's kernel. The roots and debit are witnesses
supplied by an untrusted generator; all their bounds are checked here. -/
namespace P14Quote
structure Record where
pairs : Nat
lo : Nat
hi : Nat
lowCent : Nat
highCent : Nat
single : Bool
deriving Repr
structure Witness where
r : Nat
s : Nat
debit : Nat
def Record.Check (o : Record) (w : Witness) : Prop :=
32768 ≤ o.pairs ∧ o.pairs < 2^64 ∧
w.r^2 ≤ inputLo o.pairs ∧ inputLo o.pairs < (w.r+1)^2 ∧
w.s^2 ≤ inputHi o.pairs ∧ inputHi o.pairs < (w.s+1)^2 ∧
0 < w.debit ∧ debitPower ≤ w.debit^5 * divisor o.pairs ∧
(w.debit-1)^5 * divisor o.pairs < debitPower ∧
lowerMicro o.pairs w.r w.debit = o.lo ∧ upperMicro o.pairs w.s = o.hi ∧
o.lo ≤ o.hi ∧ (o.lo+4999)/10000 = o.lowCent ∧
(o.hi+5000)/10000 = o.highCent ∧ o.single = decide (o.lowCent = o.highCent)
instance (o : Record) (w : Witness) : Decidable (o.Check w) := by
unfold Record.Check; infer_instance
theorem Record.witnesses {o : Record} {w : Witness} (h : o.Check w) :
SqrtSpec (inputLo o.pairs) w.r ∧ SqrtSpec (inputHi o.pairs) w.s ∧
DebitSpec o.pairs w.debit := by
obtain ⟨_,_,lr,ur,ls,us,dp,dh,dl,_⟩ := h
exact ⟨⟨lr,ur⟩,⟨ls,us⟩,debit_of_neighbors dp dh dl⟩
/-- The exact printed endpoints agree with the mathematical quote at its
uniquely specified integer roots and debit, independent of the generator. -/
theorem Record.exactEndpoints {o : Record} {w : Witness} (h : o.Check w) :
lowerMicro o.pairs (floorSqrt (inputLo o.pairs)) (debit o.pairs) = o.lo ∧
upperMicro o.pairs (floorSqrt (inputHi o.pairs)) = o.hi := by
obtain ⟨lr,ur,dr⟩ := o.witnesses h
obtain ⟨mina,maxa,_,_,_,_,_,_,_,lo,hi,_⟩ := h
have bound := radicands_fit128 maxa
rw [sqrt_unique (floorSqrt_spec _ bound.1) lr, sqrt_unique (floorSqrt_spec _ bound.2) ur,
debit_unique (debit_spec _ (by omega)) dr]
exact ⟨lo,hi⟩
/-- v/w is a rational price in microdollars; c is any nearest cent, including
either legal rounding at a half-cent tie. The first two inequalities encode
the analytic price bound in integers, with the rounded-up debit. -/
theorem Record.encloses {o : Record} {t : Witness} (h : o.Check t)
{v w c : Nat} (hw : 0 < w)
(hlo : (coefficient*w)^2 * inputLo o.pairs ≤ ((v+t.debit*w)*scale)^2)
(hhi : (v*scale)^2 ≤ ((coefficient+1)*w)^2 * inputHi o.pairs)
(cl : 10000*c*w ≤ v + 5000*w) (ch : v ≤ (10000*c+5000)*w) :
(o.lo*w ≤ v ∧ v ≤ o.hi*w) ∧
(o.lowCent ≤ c ∧ c ≤ o.highCent) ∧ (o.single = true → c = o.lowCent) := by
obtain ⟨lr,ur,dr⟩ := o.witnesses h
obtain ⟨mina,_,_,_,_,_,_,_,_,lo,hi,_,lc,hc,mode⟩ := h
have prices := rational_enclosure mina lr ur dr hlo hhi
rw [lo,hi] at prices
have cents := possible_cents hw prices.1 prices.2 cl ch
rw [lc,hc] at cents
refine ⟨prices,cents,?_⟩
intro single
rw [single, eq_comm, decide_eq_true_eq] at mode
omega
end P14Quote
~~~
#### `asmproof/OutputCertificateReal.lean`
~~~lean
import OutputCertificate
import QuoteReal
/-! Direct real-dollar interpretation of each numerical stdout certificate.
The analytic inputs are precisely those in QuoteReal.real_enclosure. -/
namespace P14Quote
theorem Record.realPrice {o : Record} {t : Witness} (h : o.Check t)
{K V : ℝ}
(hKlo : (coefficient:ℝ)/10^18 ≤ K)
(hKhi : K ≤ ((coefficient:ℝ)+1)/10^18)
(hVlo : K*Real.sqrt o.pairs-(137/1000)/(2*(o.pairs:ℝ)+1)^((1:ℝ)/5) ≤ V)
(hVhi : V ≤ K*Real.sqrt ((o.pairs:ℝ)+1/2)) :
(o.lo:ℝ)/10^6 ≤ V ∧ V ≤ (o.hi:ℝ)/10^6 ∧
∀ c : ℕ, (c:ℝ)-1/2 ≤ 100*V → 100*V ≤ (c:ℝ)+1/2 →
(o.lowCent ≤ c ∧ c ≤ o.highCent) ∧ (o.single = true → c = o.lowCent) := by
obtain ⟨lr,ur,dr⟩ := o.witnesses h
obtain ⟨mina,_,_,_,_,_,_,_,_,lo,hi,_,lc,hc,mode⟩ := h
obtain ⟨vl,vh⟩ := real_enclosure mina lr ur dr hKlo hKhi hVlo hVhi
rw [lo] at vl
rw [hi] at vh
refine ⟨vl,vh,?_⟩
intro c cl ch
have low : o.lowCent ≤ c := by
by_contra! bad
have skipped : 10000*c+5000 < o.lo := by omega
have skipped' : (10000:ℝ)*c+5000 < o.lo := by exact_mod_cast skipped
linarith only [skipped', vl, ch]
have high : c ≤ o.highCent := by
by_contra! bad
have skipped : o.hi+5000 < 10000*c := by omega
have skipped' : (o.hi:ℝ)+5000 < 10000*c := by exact_mod_cast skipped
linarith only [skipped', vh, cl]
refine ⟨⟨low,high⟩,?_⟩
intro single
rw [single, eq_comm, decide_eq_true_eq] at mode
omega
end P14Quote
~~~
#### `asmproof/Quote.lean`
~~~lean
import Std
/-!
The arithmetic specification of the fixed-width price quote. Natural-number
proofs have no overflow; separate bounds justify the machine-word widths.
All prices here are in microdollars and all divisions are Euclidean.
-/
namespace P14Quote
def coefficient : Nat := 522037675987123866
def scale : Nat := 10^12 * 2^32
def inputLo (n : Nat) := n * 2^64
def inputHi (n : Nat) := inputLo n + 2^63
def debitPower : Nat := 137000^5
def divisor (n : Nat) := 2*n+1
def SqrtSpec (a r : Nat) := r^2 ≤ a ∧ a < (r+1)^2
def DebitSpec (n d : Nat) := debitPower ≤ d^5 * divisor n ∧
∀ e < d, e^5 * divisor n < debitPower
def ceilRoot (a r : Nat) := r + (if r^2 < a then 1 else 0)
def lowerMicro (_n r d : Nat) := coefficient * r / scale - d
def upperMicro (n r : Nat) := ((coefficient+1) * ceilRoot (inputHi n) r + scale-1) / scale
/-- Standard integer bisection with a lower feasible and upper infeasible
sentinel. Its root theorem is independent of the method used to find those
two sentinels. -/
def bisect (feasible : Nat → Bool) (lo hi : Nat) : Nat :=
if h : lo+1 < hi then
let m := lo+(hi-lo)/2
if feasible m then bisect feasible m hi else bisect feasible lo m
else lo
termination_by hi-lo
decreasing_by all_goals omega
theorem bisect_edges (feasible : Nat → Bool) (lo hi : Nat) (h : lo < hi)
(hl : feasible lo = true) (hu : feasible hi = false) :
let r := bisect feasible lo hi
feasible r = true ∧ feasible (r+1) = false := by
induction lo,hi using bisect.induct feasible with
| case1 l u room m hm ih =>
rw [bisect, dif_pos room, if_pos hm]
exact ih (by dsimp [m]; omega) hm hu
| case2 l u room m hm ih =>
rw [bisect, dif_pos room, if_neg hm]
exact ih (by dsimp [m]; omega) hl (Bool.eq_false_iff.mpr hm)
| case3 l u done =>
rw [bisect, dif_neg done]
have equ : l+1 = u := by omega
exact ⟨hl,equ ▸ hu⟩
theorem bisect_power (p a h : Nat) (hp : p ≠ 0) (hh : a < h^p) :
let r := bisect (fun x => decide (x^p ≤ a)) 0 h
r^p ≤ a ∧ a < (r+1)^p := by
have pos : 0 < h := by
by_cases hz : h = 0
· simp [hz,Nat.zero_pow (by omega : 0 < p)] at hh
· omega
simpa using bisect_edges (fun x => decide (x^p ≤ a)) 0 h pos
(by simp [Nat.zero_pow (by omega : 0 < p)]) (by simp; omega)
def floorSqrt (a : Nat) := bisect (fun x => decide (x^2 ≤ a)) 0 (2^64)
theorem floorSqrt_spec (a : Nat) (h : a < 2^128) : SqrtSpec a (floorSqrt a) :=
bisect_power 2 a (2^64) (by decide) h
theorem sqrt_unique {a x y : Nat} (hx : SqrtSpec a x) (hy : SqrtSpec a y) : x = y := by
obtain ⟨xl,xu⟩ := hx
obtain ⟨yl,yu⟩ := hy
by_cases h : x < y
· have := Nat.pow_le_pow_left (by omega : x+1≤y) 2
omega
· by_cases h' : y < x
· have := Nat.pow_le_pow_left (by omega : y+1≤x) 2
omega
· omega
theorem ceilRoot_spec {a r : Nat} (h : SqrtSpec a r) :
a ≤ (ceilRoot a r)^2 ∧ (∀ e < ceilRoot a r, e^2 < a) := by
obtain ⟨lo,hi⟩ := h
unfold ceilRoot
split
· constructor
· omega
· intro e he
have := Nat.pow_le_pow_left (by omega : e ≤ r) 2
omega
· constructor
· simp; omega
· intro e he
have := Nat.pow_lt_pow_left (by omega : e < r) (by decide : 2 ≠ 0)
omega
/-- The additional unit after the fifth-root search accounts for both the
floor-root remainder and the remainder of dividing debitPower by 2*n+1. -/
def finishDebit (n r : Nat) :=
let q := debitPower / divisor n
r + (if r^5 < q ∨ debitPower % divisor n ≠ 0 then 1 else 0)
theorem finishDebit_spec {n r : Nat}
(h : r^5 ≤ debitPower/divisor n ∧ debitPower/divisor n < (r+1)^5) :
DebitSpec n (finishDebit n r) := by
let m := divisor n
let q := debitPower/m
have hm : 0 < m := by dsimp [m,divisor]; omega
obtain ⟨lo,hi⟩ := h
have lb : r^5*m ≤ debitPower := (Nat.le_div_iff_mul_le hm).mp lo
have ub : debitPower < (r+1)^5*m := (Nat.div_lt_iff_lt_mul hm).mp hi
have divide := Nat.div_add_mod debitPower m
rw [Nat.mul_comm m] at divide
have cmp : r^5*m < debitPower ↔ r^5 < q ∨ debitPower%m ≠ 0 := by
constructor
· intro lt
by_cases hsmall : r^5 < q
· exact Or.inl hsmall
· have eq : r^5 = q := by dsimp [q,m] at *; omega
right
intro hz
rw [eq] at lt
change q*m+debitPower%m = debitPower at divide
omega
· intro hlt
rcases hlt with h1 | h2
· have h3 := Nat.mul_lt_mul_of_pos_right h1 hm
change q*m+debitPower%m = debitPower at divide
omega
· have h3 := Nat.mul_le_mul_right m lo
change r^5*m ≤ q*m at h3
change q*m+debitPower%m = debitPower at divide
omega
by_cases hround : r^5 < q ∨ debitPower%m ≠ 0
· have hfinish : finishDebit n r = r+1 := by
unfold finishDebit; change r+(if r^5 hround (cmp.mp h)
refine ⟨by change debitPower ≤ r^5*m; omega,?_⟩
intro e he
have lt := Nat.mul_lt_mul_of_pos_right (Nat.pow_lt_pow_left he (by decide : 5 ≠ 0)) hm
change e^5*m < debitPower
omega
def debit (n : Nat) := finishDebit n
(bisect (fun x => decide (x^5 ≤ debitPower/divisor n)) 0 137000)
theorem debit_spec (n : Nat) (hn : 0 < n) : DebitSpec n (debit n) := by
apply finishDebit_spec
apply bisect_power _ _ _ (by decide)
change debitPower/divisor n < debitPower
apply Nat.div_lt_self (by decide)
dsimp [divisor]; omega
/-- An asm implementation can certify its debit directly by checking the two
adjacent products. All smaller positive candidates then fail as well. -/
theorem debit_of_neighbors {n d : Nat} (hd : 0 < d)
(hi : debitPower ≤ d^5 * divisor n)
(lo : (d-1)^5 * divisor n < debitPower) : DebitSpec n d := by
refine ⟨hi,?_⟩
intro e he
exact Nat.lt_of_le_of_lt
(Nat.mul_le_mul_right _ (Nat.pow_le_pow_left (by omega : e ≤ d-1) 5)) lo
theorem debit_unique {n e d : Nat} (he : DebitSpec n e) (hd : DebitSpec n d) : e = d := by
by_cases small : e < d
· have contra := hd.2 e small
have := he.1
omega
· by_cases big : d < e
· have contra := he.2 d big
have := hd.1
omega
· omega
theorem debit_le_limit {n d : Nat} (hd : DebitSpec n d) : d ≤ 137000 := by
by_cases h : 137000 < d
· have fail := hd.2 137000 h
have pos : 0 < divisor n := by unfold divisor; omega
have cap := Nat.le_mul_of_pos_right debitPower pos
change debitPower*divisor n < debitPower at fail
omega
· omega
theorem radicands_fit128 {n : Nat} (hn : n < 2^64) :
inputLo n < 2^128 ∧ inputHi n < 2^128 := by
unfold inputLo inputHi
unfold inputLo
omega
theorem sqrt_bound64 {a r : Nat} (ha : a < 2^128) (hr : SqrtSpec a r) :
r < 2^64 := by
by_cases h : 2^64 ≤ r
· have lo := Nat.pow_le_pow_left h 2
have hfalse := hr.1
change 2^128 ≤ r^2 at lo
omega
· omega
theorem ceilRoot_bound64 {a r : Nat} (ha : a < 2^128) (hr : SqrtSpec a r) :
ceilRoot a r ≤ 2^64 := by
have lt := sqrt_bound64 ha hr
unfold ceilRoot
split <;> omega
/-- In the price.c range even the loose debit bound 137000 cannot underflow. -/
theorem no_underflow {n r d : Nat} (hn : 32768 ≤ n)
(hr : SqrtSpec (inputLo n) r) (hd : DebitSpec n d) :
d ≤ coefficient*r/scale := by
have debitBound := debit_le_limit hd
have rootBound : 2^39 ≤ r := by
by_cases h : r < 2^39
· have upper := Nat.pow_le_pow_left (by omega : r+1 ≤ 2^39) 2
have hin := hr.2
unfold inputLo at hin
omega
· omega
have numer : 137000*scale ≤ coefficient*(2^39) := by decide
apply (Nat.le_div_iff_mul_le (by decide : 0 < scale)).mpr
exact Nat.le_trans (Nat.mul_le_mul_right _ debitBound)
(Nat.le_trans numer (Nat.mul_le_mul_left _ rootBound))
theorem lower_scale_le {n r d : Nat} (hn : 32768 ≤ n)
(hr : SqrtSpec (inputLo n) r) (hd : DebitSpec n d) :
(lowerMicro n r d + d) * scale ≤ coefficient * r := by
unfold lowerMicro
rw [Nat.sub_add_cancel (no_underflow hn hr hd)]
exact Nat.div_mul_le_self _ _
theorem ceilDiv_bounds (x m : Nat) (hm : 0 < m) :
x ≤ ((x+m-1)/m)*m ∧ ((x+m-1)/m)*m < x+m := by
have eq := Nat.div_add_mod (x+m-1) m
rw [Nat.mul_comm m] at eq
have rem := Nat.mod_lt (x+m-1) hm
omega
theorem scale_le_upper (n r : Nat) :
(coefficient+1)*ceilRoot (inputHi n) r ≤ upperMicro n r*scale :=
(ceilDiv_bounds _ scale (by decide)).1
theorem price_products_fit128 {n r s : Nat} (hn : n < 2^64)
(hr : SqrtSpec (inputLo n) r) (hs : SqrtSpec (inputHi n) s) :
coefficient*r < 2^128 ∧
(coefficient+1)*ceilRoot (inputHi n) s + scale-1 < 2^128 := by
have bounds := radicands_fit128 hn
have lo := sqrt_bound64 bounds.1 hr
have hi := ceilRoot_bound64 bounds.2 hs
unfold coefficient scale
omega
theorem prices_fit64 {n r s d : Nat} (hn : n < 2^64)
(hr : SqrtSpec (inputLo n) r) (hs : SqrtSpec (inputHi n) s) :
lowerMicro n r d < 2^64 ∧ upperMicro n s < 2^64 := by
have bounds := radicands_fit128 hn
have lo := sqrt_bound64 bounds.1 hr
have hi := ceilRoot_bound64 bounds.2 hs
unfold lowerMicro upperMicro coefficient scale
omega
private theorem square_le {x y : Nat} (h : x^2 ≤ y^2) : x ≤ y := by
by_cases b : y < x
· have := Nat.pow_lt_pow_left b (by decide : 2 ≠ 0)
omega
· omega
/-- Exact rational bridge. If v/w is the true price in MICROdollars, the
two final hypotheses are just the nonnegative analytic lower/upper price
inequalities after rounding the debit up and then squaring. They contain no
transcendental operations. Negative lower endpoints are handled by the
no-underflow hypothesis proved above. -/
theorem rational_enclosure {n r s d v w : Nat} (hn : 32768 ≤ n)
(hr : SqrtSpec (inputLo n) r) (hs : SqrtSpec (inputHi n) s)
(hd : DebitSpec n d)
(hlo : (coefficient*w)^2 * inputLo n ≤ ((v+d*w)*scale)^2)
(hhi : (v*scale)^2 ≤ ((coefficient+1)*w)^2 * inputHi n) :
lowerMicro n r d*w ≤ v ∧ v ≤ upperMicro n s*w := by
have hrootlo := Nat.mul_le_mul_left ((coefficient*w)^2) hr.1
have lr : (coefficient*w)*r ≤ (v+d*w)*scale := by
apply square_le
rw [Nat.mul_pow]
exact Nat.le_trans hrootlo hlo
have hr' := Nat.mul_le_mul_right w (lower_scale_le hn hr hd)
have lr' : ((lowerMicro n r d+d)*w)*scale ≤ (v+d*w)*scale := by
calc
_ = (lowerMicro n r d+d)*scale*w := by ac_rfl
_ ≤ coefficient*r*w := hr'
_ = coefficient*w*r := by ac_rfl
_ ≤ _ := lr
have lose := Nat.le_of_mul_le_mul_right lr' (by decide : 0 split <;> simp_all [Nat.mul_add] <;> omega
/-- The assembly subtracts one before division and adds one afterwards,
which evaluates the ceiling exactly without constructing a 65-bit root. -/
theorem asm_upper_quotient {n s : Nat} (hs : SqrtSpec (inputHi n) s) :
1 + (((coefficient+1)*s + (if s^2 = inputHi n then 0 else coefficient+1) - 1)
/ 2^32 / 10^12) = upperMicro n s := by
rw [asm_upper_product hs, Nat.div_div_eq_div_mul]
have bound := (ceilRoot_spec hs).1
have pos : 0 < ceilRoot (inputHi n) s := by
by_cases h : ceilRoot (inputHi n) s = 0
· rw [h] at bound
simp [inputHi,inputLo] at bound
· omega
have numerator := Nat.mul_pos (by decide : 0 < coefficient+1) pos
unfold upperMicro scale
omega
/-- Outward bounds for all memory accesses made by the exponent and
mantissa hint lookup. The 12-bit normalized significand includes its
implicit leading 1; the next eight bits index a 256-entry row. -/
theorem debit_hint_indices {n : Nat} (hn : 32768 ≤ n) (hu : n < 2^64) :
let e := n.log2
let x := n / 2^(e-12)
15 ≤ e ∧ e < 64 ∧ 4096 ≤ x ∧ x < 8192 ∧ (x-4096)/16 < 256 := by
have hnz : n ≠ 0 := by omega
have he : 15 ≤ n.log2 := (Nat.le_log2 hnz).mpr hn
have he' : n.log2 < 64 := by
by_cases h : 64 ≤ n.log2
· exact False.elim ((Nat.not_le_of_gt hu) ((Nat.le_log2 hnz).mp h))
· omega
have hpow : 0 < 2^(n.log2-12) := Nat.two_pow_pos _
have hlo : 4096 * 2^(n.log2-12) ≤ n := by
change 2^12 * 2^(n.log2-12) ≤ n
rw [← Nat.pow_add, Nat.add_sub_of_le (by omega : 12 ≤ n.log2)]
exact Nat.log2_self_le hnz
have hhi : n < 8192 * 2^(n.log2-12) := by
change n < 2^13 * 2^(n.log2-12)
rw [← Nat.pow_add, show 13+(n.log2-12) = n.log2+1 by omega]
exact Nat.lt_log2_self
have a := (Nat.le_div_iff_mul_le hpow).mpr hlo
have b := (Nat.div_lt_iff_lt_mul hpow).mpr hhi
dsimp only
exact ⟨he, he', a, b, by omega⟩
end P14Quote
~~~
#### `asmproof/QuoteEntry.lean`
~~~lean
import X86RootQuote
import DebitBytes
import QuoteSeed
import QuoteMachine
/-! Live-register call composition for `quote_asm`. `EntryReturns` threads
the two decoded MUL-based root loops, the two DIVQ pricing blocks,
and the decoded debit correction through the actual return registers.
The root candidates represent arbitrary results of the masked SSE2
conversion. `hint` represents the final 32-bit interpolation result;
it is intentionally allowed to range over all naturals. The memory
projection names two distinct writable output words. It assumes the
usual valid SysV stack and code/read-only-data mapping. -/
namespace P14Entry
open P14Quote
namespace R
export Problem14.X86Root (Reg CPU Returns root_repair_quote)
end R
namespace D
export P14Debit.X86 (Table tableOK fetched code Reaches State fetched_correct)
end D
namespace M
export P14Machine (State run lowerOps upperOps finalOps low_run high_run last_run)
end M
/-- All incoming scratch registers and flags may vary except the input
registers set by the call sequence. -/
def rootCPU (s : R.CPU) (hi lo fp : Nat) : R.CPU :=
{s with ip := 0, reg := fun r => match r with
| .di => lo | .si => hi | .dx => P14Seeds.rootSeed hi lo fp
| k => s.reg k}
def rootResult (s : M.State) (t : R.CPU) : M.State :=
{s with ax := t.reg .ax, dx := t.reg .dx}
def EntryReturns (n fpLo fpHi hint a0 a1 a2 a3 : Nat) (mem : D.Table) (s : M.State)
(scratchLow scratchHigh : R.CPU) (scratchDebit : D.State) (post : M.State → Prop) :=
R.Returns (fun l => ∃ a,
M.run (rootResult s l) M.lowerOps = some a ∧
R.Returns (fun h => ∃ b,
M.run (rootResult a h) M.upperOps = some b ∧
∃ d, D.Reaches (D.fetched (D.code a0 a1 a2 a3) n hint mem) {scratchDebit with pc:=0} d ∧
(d.pc=41 ∨ d.pc=58) ∧
∃ z, M.run {b with ax:=d.ax} M.finalOps=some z ∧ post z)
(rootCPU scratchHigh n (2^63) fpHi))
(rootCPU scratchLow n 0 fpLo)
private theorem root_call (s : R.CPU) (hi lo fp : Nat) (hh : hi<2^64)
(hl : lo<2^64) (hf : fp<2^64) :
let y := hi*2^64+lo
R.Returns (fun t => t.reg .ax = floorSqrt y ∧
t.reg .dx = if (floorSqrt y)^2=y then 1 else 0) (rootCPU s hi lo fp) := by
dsimp only
apply (R.root_repair_quote (rootCPU s hi lo fp) lo hi (P14Seeds.rootSeed hi lo fp)
rfl rfl rfl rfl hl hh (P14Seeds.seed_guard hh hl hf).2.2).weaken
intro t ht
exact ⟨ht.1,ht.2.1⟩
theorem quote_entry_correct {n fpLo fpHi hint : Nat} (hn : 32768≤n) (hu : n<2^64)
(a0 a1 a2 a3 : Nat) (fl : fpLo<2^64) (fh : fpHi<2^64) {mem : D.Table} (hm : D.tableOK mem)
(s : M.State) (sl sh : R.CPU) (sd : D.State) :
EntryReturns n fpLo fpHi hint a0 a1 a2 a3 mem s sl sh sd (fun z =>
z.outLo = lowerMicro n (floorSqrt (inputLo n)) (debit n) ∧
z.outHi = upperMicro n (floorSqrt (inputHi n))) := by
have roots := radicands_fit128 hu
have rl := floorSqrt_spec _ roots.1
have rh := floorSqrt_spec _ roots.2
have rb := sqrt_bound64 roots.1 rl
unfold EntryReturns
apply (root_call sl n 0 fpLo hu (by decide) fl).weaken
intro l hl
have la : l.reg .ax=floorSqrt (inputLo n) := by simpa [inputLo] using hl.1
obtain ⟨a,ar,save,_⟩ := M.low_run (rootResult s l) _ la rb
refine ⟨a,ar,?_⟩
apply (root_call sh n (2^63) fpHi hu (by decide) fh).weaken
intro h hh
obtain ⟨b,br,store,sv⟩ := M.high_run (rootResult a h) _ _ hu hh.1 hh.2 rh
refine ⟨b,br,?_⟩
obtain ⟨d,dr,ret,ok⟩ := D.fetched_correct a0 a1 a2 a3 n hint mem hm hn hu {sd with pc:=0} rfl
obtain ⟨z,zr,zlo,zhi⟩ := M.last_run {b with ax:=d.ax} n _ d.ax rfl
(sv.trans save) hn hu rl ok
have eqd := debit_unique ok (debit_spec n (by omega))
exact ⟨d,dr,ret,z,zr,by simpa [eqd] using zlo,zhi.trans store⟩
#print axioms quote_entry_correct
end P14Entry
~~~
#### `asmproof/QuoteMachine.lean`
~~~lean
import Quote
/-! Unsigned, live-register semantics for the straight-line price arithmetic in
quote.S. The machine starts with initialized, disjoint output words, a
valid SysV stack, and masked SSE exceptions. The floating-point conversion
result may be ANY unsigned word. All returned prices are proved below
without a floating-point error hypothesis. -/
namespace P14Machine
open P14Quote
set_option maxRecDepth 16000
set_option maxHeartbeats 3000000
abbrev W : Nat := 18446744073709551616
abbrev Half : Nat := 4294967296
macro "word_omega" : tactic => `(tactic| (simp only [W,Half] at *; omega))
structure State where
ax : Nat := 0
dx : Nat := 0
cx : Nat := 0
r8 : Nat := 0
r15 : Nat := 0
carry : Nat := 0
outLo : Nat := 0
outHi : Nat := 0
deriving Repr, DecidableEq
inductive Op where
| kLo | kHi | mul | shrd | shr | denom | divq | save
| decDX | andDX | toR8 | add | adc | subOne | sbb
| inc | putHi | debitSub | putLo
deriving Repr, DecidableEq
open Op
def instr : Op → List Nat
| kLo => [72,185,154,62,149,28,128,166,62,7]
| kHi => [72,185,155,62,149,28,128,166,62,7]
| mul => [72,247,225]
| shrd => [72,15,172,208,32]
| shr => [72,193,234,32]
| denom => [72,185,0,16,165,212,232,0,0,0]
| divq => [72,247,241]
| save => [73,137,199]
| decDX => [72,255,202]
| andDX => [72,33,202]
| toR8 => [73,137,208]
| add => [76,1,192]
| adc => [72,131,210,0]
| subOne => [72,131,232,1]
| sbb => [72,131,218,0]
| inc => [72,255,192]
| putHi => [73,137,6]
| debitSub => [73,41,199]
| putLo => [77,137,125,0]
def allOps := [kLo,kHi,mul,shrd,shr,denom,divq,save,decDX,andDX,toR8,add,adc,
subOne,sbb,inc,putHi,debitSub,putLo]
def decode : Nat → List Nat → Option (List Op)
| 0, [] => some []
| 0, _::_ => none
| _+1, [] => some []
| n+1, bytes@(_::_) => do
let op ← allOps.find? (fun op => (instr op).isPrefixOf bytes)
let tail ← decode n (bytes.drop (instr op).length)
return op::tail
def step (s : State) : Op → Option State
| kLo => some {s with cx := coefficient}
| kHi => some {s with cx := coefficient+1}
| mul => let p := s.ax*s.cx; some {s with ax := p%W, dx := p/W}
| shrd => some {s with ax := (s.dx%Half)*Half + s.ax/Half}
| shr => some {s with dx := s.dx/Half}
| denom => some {s with cx := 10^12}
| divq =>
if s.dx < s.cx then
let p := s.dx*W+s.ax
some {s with ax := p/s.cx, dx := p%s.cx}
else none
| save => some {s with r15 := s.ax}
| decDX => some {s with dx := (s.dx+W-1)%W}
| andDX => some {s with dx := s.dx &&& s.cx}
| toR8 => some {s with r8 := s.dx}
| add => let z := s.ax+s.r8; some {s with ax := z%W, carry := z/W}
| adc => some {s with dx := (s.dx+s.carry)%W}
| subOne => some {s with ax := (s.ax+W-1)%W, carry := if s.ax=0 then 1 else 0}
| sbb => some {s with dx := (s.dx+W-s.carry)%W}
| inc => some {s with ax := (s.ax+1)%W}
| putHi => some {s with outHi := s.ax}
| debitSub => some {s with r15 := (s.r15+W-s.ax)%W}
| putLo => some {s with outLo := s.r15}
def run (s : State) : List Op → Option State
| [] => some s
| i::is => (step s i).bind (fun z => run z is)
def lowerOps := [kLo,mul,shrd,shr,denom,divq,save]
def upperOps := [kHi,decDX,andDX,toR8,mul,add,adc,subOne,sbb,shrd,shr,denom,divq,inc,putHi]
def finalOps := [debitSub,putLo]
-- Relocation-free slices at offsets 0x58..0x7d, 0x9d..0xdd and 0xe6..0xec.
def lowBytes : List Nat := [
72,185,154,62,149,28,128,166,62,7,72,247,225,72,15,172,208,32,72,193,234,32,
72,185,0,16,165,212,232,0,0,0,72,247,241,73,137,199]
def highBytes : List Nat := [
72,185,155,62,149,28,128,166,62,7,72,255,202,72,33,202,73,137,208,72,247,225,
76,1,192,72,131,210,0,72,131,232,1,72,131,218,0,72,15,172,208,32,72,193,
234,32,72,185,0,16,165,212,232,0,0,0,72,247,241,72,255,192,73,137,6]
def finalBytes : List Nat := [73,41,199,77,137,125,0]
set_option maxRecDepth 4096 in
theorem decode_blocks :
decode 20 lowBytes = some lowerOps ∧ decode 20 highBytes = some upperOps ∧
decode 20 finalBytes = some finalOps := by decide
def shiftDivide (s : State) (p : Nat) :
State := {s with ax := (p/Half)/(10^12), dx := (p/Half)%(10^12), cx := 10^12}
theorem divide_block (s : State) (p : Nat) (hax:s.ax=p%W) (hdx:s.dx=p/W)
(hp:p<2^128) : run s [shrd,shr,denom,divq] = some (shiftDivide s p) := by
have join := shrd32_value p
have fit := (divq_fits p hp).1
have hh : (p/W)/Half < 10^12 := by word_omega
simp [run,step,hax,hdx,hh,shiftDivide, ←Nat.add_assoc,join]
theorem run_append (s : State) (a b : List Op) :
run s (a++b) = (run s a).bind (fun z => run z b) := by
induction a generalizing s with
| nil => rfl
| cons h t ih =>
simp only [List.cons_append,run]
cases step s h with
| none => rfl
| some v => exact ih v
private theorem run_join {s t u : State} {a b : List Op}
(ha : run s a = some t) (hb : run t b = some u) :
run s (a++b) = some u := by rw [run_append,ha]; exact hb
theorem low_run (s : State) (r : Nat) (a : s.ax=r) (bound:r simp only [if_pos, if_neg, if_true, if_false, hz] <;> word_omega
theorem high_run (s : State) (n r : Nat) (hn:n
#### `asmproof/QuoteReal.lean`
~~~lean
import Quote
import Mathlib.Analysis.SpecialFunctions.Pow.Real
import Mathlib.Data.Real.Sqrt
import Mathlib.Tactic.Linarith
import Mathlib.Tactic.NormNum
import Mathlib.Tactic.Positivity
import Mathlib.Tactic.FieldSimp
/-!
Real-valued bridge from the analytic price estimate to microdollar output.
The coefficient bracket and the two game inequalities are explicit hypotheses.
The rounding of both square roots, the fifth root debit, and every integer
quotient is handled by Quote.lean. This file uses mathlib v4.19.0.
-/
namespace P14Quote
private theorem debit_real {n d : ℕ} (hd : DebitSpec n d) :
137000 / (2*(n:ℝ)+1)^((1:ℝ)/5) ≤ d := by
let y := (2*(n:ℝ)+1)^((1:ℝ)/5)
have hpos : 0 < y := Real.rpow_pos_of_pos (by positivity) _
have hpow : y^5 = 2*(n:ℝ)+1 := by
dsimp [y]
rw [← Real.rpow_natCast _ 5, ← Real.rpow_mul (by positivity)]
norm_num
have ha := hd.1
unfold debitPower divisor at ha
have hreal : (137000:ℝ)^5 ≤ (d:ℝ)^5*(2*(n:ℝ)+1) := by exact_mod_cast ha
have hfinal : (137000:ℝ) ≤ (d:ℝ)*y := by
apply (pow_le_pow_iff_left₀ (by norm_num) (mul_nonneg (Nat.cast_nonneg d) hpos.le)
(by decide : (5:ℕ) ≠ 0)).mp
rw [mul_pow,hpow]
exact hreal
exact (div_le_iff₀ hpos).mpr hfinal
private theorem lower_root_real {n r : ℕ} (hr : SqrtSpec (inputLo n) r) :
(r:ℝ) ≤ Real.sqrt n * 2^32 := by
have h := hr.1
unfold inputLo at h
apply (sq_le_sq₀ (Nat.cast_nonneg r) (by positivity)).mp
rw [mul_pow,Real.sq_sqrt (Nat.cast_nonneg n)]
exact_mod_cast h
private theorem upper_root_real {n s : ℕ} (hs : SqrtSpec (inputHi n) s) :
Real.sqrt ((n:ℝ)+1/2) * 2^32 ≤ ceilRoot (inputHi n) s := by
have h := (ceilRoot_spec hs).1
change n*2^64+2^63 ≤ (ceilRoot (inputHi n) s)^2 at h
have hreal : (n:ℝ)*2^64+2^63 ≤ (ceilRoot (inputHi n) s : ℝ)^2 := by exact_mod_cast h
apply (sq_le_sq₀ (by positivity) (Nat.cast_nonneg _)).mp
rw [mul_pow,Real.sq_sqrt (by positivity)]
linarith
/-- Let K=(1-alpha^2)*sqrt(pi), with dollar-valued V. Under the established
coefficient bracket and the analytic upper/lower bounds, the assembly's
integer-valued endpoints enclose V for every supported n. -/
theorem real_enclosure {n r s d : ℕ} {K V : ℝ} (hn : 32768 ≤ n)
(hr : SqrtSpec (inputLo n) r) (hs : SqrtSpec (inputHi n) s)
(hd : DebitSpec n d)
(hKlo : (coefficient:ℝ)/10^18 ≤ K)
(hKhi : K ≤ ((coefficient:ℝ)+1)/10^18)
(hVlo : K*Real.sqrt n-(137/1000)/(2*(n:ℝ)+1)^((1:ℝ)/5) ≤ V)
(hVhi : V ≤ K*Real.sqrt ((n:ℝ)+1/2)) :
(lowerMicro n r d : ℝ)/10^6 ≤ V ∧ V ≤ (upperMicro n s : ℝ)/10^6 := by
have low := lower_scale_le hn hr hd
have high := scale_le_upper n s
unfold scale at low high
have hlow : ((lowerMicro n r d : ℝ)+d)*(10^12*2^32) ≤ (coefficient:ℝ)*r := by
exact_mod_cast low
have hhigh : ((coefficient:ℝ)+1)*ceilRoot (inputHi n) s ≤
(upperMicro n s : ℝ)*(10^12*2^32) := by exact_mod_cast high
have rlo := mul_le_mul_of_nonneg_left (lower_root_real hr) (Nat.cast_nonneg coefficient)
have rhi := mul_le_mul_of_nonneg_left (upper_root_real hs)
(show (0:ℝ) ≤ (coefficient:ℝ)+1 by positivity)
have lower_constant := mul_le_mul_of_nonneg_right hKlo (Real.sqrt_nonneg n)
have upper_constant := mul_le_mul_of_nonneg_right hKhi (Real.sqrt_nonneg ((n:ℝ)+1/2))
have hd' := debit_real hd
rw [div_eq_mul_inv (137 / 1000)] at hVlo
rw [div_eq_mul_inv (137000:ℝ)] at hd'
constructor
· linarith only [hlow,rlo,lower_constant,hVlo,hd']
· linarith only [hhigh,rhi,upper_constant,hVhi]
end P14Quote
~~~
#### `asmproof/QuoteSeed.lean`
~~~lean
import Quote
/-! Nontrapping guards in the assembly hint paths. Masked SSE conversion may
return any 64-bit bit pattern; the semantic proof uses no analytic or
IEEE-accuracy property of that pattern. -/
namespace P14Seeds
abbrev W : Nat := 18446744073709551616
/-- ADD followed by one-bit RCR, retaining the carry as the new top bit. -/
def rcrMean (a b : Nat) : Nat :=
((a+b)/W)*2^63 + ((a+b)%W)/2
theorem mean_correct (a b : Nat) (ha : a simp_all only [W] <;> omega
have safe : q≠0 → hi
#### `asmproof/RecordReplay.lean`
~~~lean
import asmproof.GameMachinePrice
namespace P14CheckedOutput
open P14Quote
private theorem halfUp {v : ℝ} (hv : 0≤v) :
let c : ℕ := ⌊100*v+1/2⌋₊
(c:ℝ)-1/2 ≤ 100*v ∧ 100*v ≤ (c:ℝ)+1/2 := by
have h := Nat.floor_le (by positivity : (0:ℝ)≤100*v+1/2)
have h' := Nat.lt_floor_add_one (100*v+1/2)
dsimp only
constructor <;> linarith only [h,h']
def line0 : Record := ⟨133787000, 6038215406, 6038218246, 603822, 603822, true⟩
def hint0 : Witness := ⟨49678310653537, 49678310746368, 2827⟩
theorem verified0 : line0.Check hint0 := by decide
def endpoints0 := @Record.exactEndpoints _ _ verified0
def cents0 := @Record.encloses _ _ verified0
def realPrice0 := @Record.realPrice _ _ verified0
theorem gameDollars0 : (6038215406:ℝ)/10^6 ≤ Problem14.GameComparison.price 133787000 ∧
Problem14.GameComparison.price 133787000 ≤ (6038218246:ℝ)/10^6 := by
have h := P14Entry.printed_game verified0
exact ⟨h.1,h.2.1⟩
def allNearest0 := (P14Entry.printed_game verified0).2.2
theorem roundedCents0 : ⌊100*(Problem14.GameComparison.price 133787000)+1/2⌋₊ = 603822 := by
have lower := gameDollars0.1
have pos : 0 ≤ Problem14.GameComparison.price 133787000 := le_trans (by positivity) lower
obtain ⟨hl,hu⟩ := halfUp pos
have out := allNearest0 _ hl hu
exact out.2 rfl
def line1 : Record := ⟨500000000, 11673115131, 11673117310, 1167312, 1167312, true⟩
def hint1 : Witness := ⟨96038388349944, 96038388397963, 2172⟩
theorem verified1 : line1.Check hint1 := by decide
def endpoints1 := @Record.exactEndpoints _ _ verified1
def cents1 := @Record.encloses _ _ verified1
def realPrice1 := @Record.realPrice _ _ verified1
theorem gameDollars1 : (11673115131:ℝ)/10^6 ≤ Problem14.GameComparison.price 500000000 ∧
Problem14.GameComparison.price 500000000 ≤ (11673117310:ℝ)/10^6 := by
have h := P14Entry.printed_game verified1
exact ⟨h.1,h.2.1⟩
def allNearest1 := (P14Entry.printed_game verified1).2.2
theorem roundedCents1 : ⌊100*(Problem14.GameComparison.price 500000000)+1/2⌋₊ = 1167312 := by
have lower := gameDollars1.1
have pos : 0 ≤ Problem14.GameComparison.price 500000000 := le_trans (by positivity) lower
obtain ⟨hl,hu⟩ := halfUp pos
have out := allNearest1 _ hl hu
exact out.2 rfl
def line2 : Record := ⟨1000000000000, 522037675512, 522037675988, 52203768, 52203768, true⟩
def hint2 : Witness := ⟨4294967296000000, 4294967296001073, 475⟩
theorem verified2 : line2.Check hint2 := by decide
def endpoints2 := @Record.exactEndpoints _ _ verified2
def cents2 := @Record.encloses _ _ verified2
def realPrice2 := @Record.realPrice _ _ verified2
theorem gameDollars2 : (522037675512:ℝ)/10^6 ≤ Problem14.GameComparison.price 1000000000000 ∧
Problem14.GameComparison.price 1000000000000 ≤ (522037675988:ℝ)/10^6 := by
have h := P14Entry.printed_game verified2
exact ⟨h.1,h.2.1⟩
def allNearest2 := (P14Entry.printed_game verified2).2.2
theorem roundedCents2 : ⌊100*(Problem14.GameComparison.price 1000000000000)+1/2⌋₊ = 52203768 := by
have lower := gameDollars2.1
have pos : 0 ≤ Problem14.GameComparison.price 1000000000000 := le_trans (by positivity) lower
obtain ⟨hl,hu⟩ := halfUp pos
have out := allNearest2 _ hl hu
exact out.2 rfl
end P14CheckedOutput
~~~
#### `asmproof/Threshold.lean`
~~~lean
import Quote
/-! Inverse endpoint comparisons for the faster quote. Instead of finding two
square roots, test candidate microdollar endpoints directly with a pair of
unsigned wide multiplications and an integer square comparison. -/
namespace P14Threshold
open P14Quote
def word : Nat := 2^64
def base : Nat := 2^112
def lowA : Nat := 0x20235018f799840f
def lowB : Nat := 0xed9149e90e8fc718
def highA : Nat := 0x20235018f799840b
def highB : Nat := 0x7df0a236f864225f
/-- The first product contributes only its high 64 bits; the second
is a full-width 128-bit product. The final 48-bit shift is unsigned. -/
def inverse (j a b : Nat) := (j*b/word+j*a)/2^48
def lowerThreshold (j : Nat) := inverse j lowA lowB+1
def upperThreshold (j : Nat) := inverse j highA highB
theorem inverse_value (j a b : Nat) :
inverse j a b = j*(a*word+b)/base := by
unfold inverse base word
rw [show 2^112=2^64*2^48 by decide, ←Nat.div_div_eq_div_mul, Nat.mul_add,
←Nat.mul_assoc, Nat.add_comm (j*a*2^64), Nat.add_mul_div_right _ _ (by decide)]
theorem lower_split_lt {j r : Nat} (hp : 0 < j) (hj : j < 2^52) :
lowerThreshold j ≤ r ↔ j*scale ≤ coefficient*r := by
unfold lowerThreshold
rw [inverse_value, Nat.add_one_le_iff, Nat.div_lt_iff_lt_mul (by decide : 0 < base)]
unfold base word lowA lowB scale coefficient
omega
theorem upper_split_le {j r : Nat} (hj : j < 2^52) :
r ≤ upperThreshold j ↔ (coefficient+1)*r ≤ j*scale := by
unfold upperThreshold
rw [inverse_value, Nat.le_div_iff_mul_le (by decide : 0 < base)]
unfold base word highA highB scale coefficient
omega
private theorem le_sqrt_iff {y a r : Nat} (h : SqrtSpec y r) : a ≤ r ↔ a^2 ≤ y := by
obtain ⟨lo,hi⟩ := h
constructor
· intro le
exact Nat.le_trans (Nat.pow_le_pow_left le 2) lo
· intro hq
by_cases he : a ≤ r
· exact he
· have := Nat.pow_le_pow_left (by omega : r+1 ≤ a) 2
omega
private theorem ceilRoot_le_iff {y a r : Nat} (h : SqrtSpec y r) :
ceilRoot y r ≤ a ↔ y ≤ a^2 := by
obtain ⟨hl,least⟩ := ceilRoot_spec h
constructor
· intro le
exact Nat.le_trans hl (Nat.pow_le_pow_left le 2)
· intro hq
by_cases he : ceilRoot y r ≤ a
· exact he
· have := least a (by omega)
omega
/-- The lower endpoint comparison uses the unrounded price before debit. -/
theorem lower_predicate {n r j : Nat} (hr : SqrtSpec (inputLo n) r)
(hp : 0 < j) (hj : j < 2^52) :
(lowerThreshold j)^2 ≤ inputLo n ↔ j ≤ coefficient*r/scale := by
rw [← le_sqrt_iff hr,lower_split_lt hp hj,Nat.le_div_iff_mul_le (by decide : 0 < scale)]
theorem upper_predicate {n r j : Nat} (hr : SqrtSpec (inputHi n) r) (hj : j < 2^52) :
inputHi n ≤ (upperThreshold j)^2 ↔ upperMicro n r ≤ j := by
rw [← ceilRoot_le_iff hr,upper_split_le hj]
unfold upperMicro scale
omega
/-- A threshold represented by more than one word is above every possible
radicand's square root. The upper and lower comparisons use opposite ties. -/
theorem square_guard {x y : Nat} (hy : y < 2^128) :
(x^2 ≤ y ↔ x < word ∧ (x%word)^2 ≤ y) ∧
(y ≤ x^2 ↔ word ≤ x ∨ y ≤ (x%word)^2) := by
by_cases hx : x < word
· simp [hx,Nat.not_le_of_gt hx,Nat.mod_eq_of_lt hx]
· have h : word^2 ≤ x^2 := Nat.pow_le_pow_left (by omega) 2
change 2^128 ≤ x^2 at h
constructor <;> constructor <;> intro h0 <;> simp_all <;> omega
/-- Even after both integer roundings, neighbouring root thresholds differ
by more than the 8192-wide one-sided acceptance radius. -/
theorem gaps (j : Nat) :
lowerThreshold j + 8193 ≤ lowerThreshold (j+1) ∧
upperThreshold j + 8193 ≤ upperThreshold (j+1) := by
unfold lowerThreshold upperThreshold
simp only [inverse_value,lowA,lowB,highA,highB,word,base,Nat.add_mul]
omega
def radius : Nat := 8192
def wide : Nat := 2^128
def within (t y : Nat) := (t-radius)^2 ≤ y ∧ y ≤ (t+radius)^2
/-- Unsigned evaluation of y−t²+(t<<14)−2²⁶, modulo 2¹²⁸. Addition of
one modulus before each subtraction expresses unsigned subtraction in Nat. -/
def bandWord (t y : Nat) :=
(y + wide - t^2 + t*2^14 + wide - 2^26) % wide
theorem wrapping_band {t y : Nat} (hlo : radius ≤ t) (hhi : t+radius < word)
(hy : y < wide) : bandWord t y ≤ t*2^15 ↔ within t y := by
obtain ⟨a,he⟩ := Nat.exists_eq_add_of_le hlo
subst t
have cap := Nat.pow_lt_pow_left hhi (by decide : (2:Nat) ≠ 0)
unfold radius word at *
change (8192+a+8192)^2 < wide at cap
have hsub : 8192 + a - 8192 = a := by omega
unfold bandWord within
unfold radius
rw [hsub]
simp only [Nat.pow_succ,Nat.pow_zero,Nat.mul_one,Nat.mul_add,Nat.add_mul] at cap ⊢
unfold wide at *
omega
/-- A distance certificate at j brackets the exact endpoint between its
neighbouring thresholds. This uses only threshold order and the integer
square inequalities; the candidate's origin does not enter the proof. -/
private theorem neighbors {f : Nat → Nat} {j y : Nat} (hj : 0 < j)
(h : within (f j) y) (gap : ∀ i, f i+8193 ≤ f (i+1)) :
(f (j-1))^2 < y ∧ y < (f (j+1))^2 := by
have g0 := gap (j-1)
have g1 := gap j
rw [show j-1+1=j by omega] at g0
obtain ⟨low,hi⟩ := h
unfold radius at low hi
exact ⟨Nat.lt_of_lt_of_le (Nat.pow_lt_pow_left (by omega : f (j-1) inputLo n then 1 else 0) = coefficient*r/scale := by
let u := coefficient*r/scale
have ⟨before,after⟩ := neighbors hj h (fun i => (gaps i).1)
have below : j-1 ≤ u := by
by_cases h0 : 0 < j-1
· exact (lower_predicate hr h0 (by omega)).mp (Nat.le_of_lt before)
· have hz : j-1 = 0 := by omega
rw [hz]
exact Nat.zero_le _
have above : u < j+1 := by
by_cases h0 : j+1 ≤ u
· have := (lower_predicate hr (by omega : 0 omega
theorem upper_hit {n r j : Nat} (hr : SqrtSpec (inputHi n) r) (hj : 0 (gaps i).2)
have below : j-1 < upperMicro n r := by
by_cases h0 : upperMicro n r ≤ j-1
· have := (upper_predicate hr (j:=j-1) (by omega)).mpr h0
omega
· omega
have above := (upper_predicate hr hcap).mp (Nat.le_of_lt after)
have test := upper_predicate hr (j:=j) (by omega)
split <;> omega
/-- For large n the code first compares just the upper 64-bit words of
the squared threshold and the radicand. The subtracted unit covers all
possible low words, as well as the radius squared in the exact test. -/
theorem coarse_band {t y : Nat} (hlo : radius ≤ t)
(h : ((t^2/word)-(y/word)) + ((y/word)-(t^2/word)) < t/2^50-1) :
within t y := by
obtain ⟨a,he⟩ := Nat.exists_eq_add_of_le hlo
subst t
unfold radius word at h
unfold within radius
rw [show 8192+a-8192=a by omega]
simp only [Nat.pow_succ, Nat.pow_zero, Nat.mul_one, Nat.mul_add, Nat.add_mul] at h ⊢
omega
theorem min_thresholds {j : Nat} (h : 0 omega
· simp only [decide_eq_true_eq] at pass
exact (wrapping_band tl th ys).mp pass
/-- The complete guarded arithmetic path. The machine substitutes the
proved reference endpoint routine exactly when this function returns none. -/
def guarded (coarse : Bool) (n jl jh : Nat) : Option (Nat × Nat) :=
let tl := lowerThreshold jl
let th := upperThreshold jh
if hintOK jl ∧ hintOK jh ∧ tl+radius < word ∧ th+radius < word ∧
bandOK coarse n tl (inputLo n) ∧ bandOK coarse n th (inputHi n) then
some (jl-(if tl^2 > inputLo n then 1 else 0)-debit n,
jh+(if th^2 < inputHi n then 1 else 0))
else none
theorem guarded_correct (coarse : Bool) (n jl jh : Nat) (hn : n < 2^64) (jlWord : jl < word) (jhWord : jh < word) :
(guarded coarse n jl jh).getD (lowerMicro n (floorSqrt (inputLo n)) (debit n),
upperMicro n (floorSqrt (inputHi n))) =
(lowerMicro n (floorSqrt (inputLo n)) (debit n),
upperMicro n (floorSqrt (inputHi n))) := by
obtain ⟨ly,uy⟩ := radicands_fit128 hn
unfold guarded
dsimp only
split
· rename_i pass
obtain ⟨l,h,tl1,th1,lb,hb⟩ := pass
obtain ⟨l0,l1⟩ := (hintOK_iff jlWord).mp l
obtain ⟨h0,h1⟩ := (hintOK_iff jhWord).mp h
have hl : inputLo n / word = n := by unfold inputLo word; omega
have hh : inputHi n / word = n := by unfold inputHi inputLo word; omega
have low := bandOK_sound tl1 (min_thresholds l0).1 ly hl lb
have high := bandOK_sound th1 (min_thresholds h0).2 uy hh hb
have lo := lower_hit (floorSqrt_spec _ ly) l0 l1 low
have hi := upper_hit (floorSqrt_spec _ uy) h0 h1 high
simp [lo,hi,lowerMicro]
· rfl
#print axioms guarded_correct
end P14Threshold
~~~
#### `asmproof/ThresholdBandBytes.lean`
~~~lean
import ThresholdBytes
/-! The compiler's two unsigned square-band tests after the guarded inverse
thresholds. RSP-relative stack slots are identified by their offsets (RSP
does not move). SHL/SHLD carry flags are dead before any read. -/
namespace P14ThresholdBand
open P14ThresholdBytes
open P14Threshold
set_option maxRecDepth 32768
inductive Op where
| base (i : I)
| stackStore (off s : Nat) | stackLoad (d off : Nat)
| stackSub (d off : Nat) (withBorrow : Bool)
| lowMul (d s : Nat) | shld (d s n : Nat) | shl (d n : Nat)
| addCarry (d s : Nat) | subReg (d s : Nat)
deriving Repr, DecidableEq
def decodeBand (xs : List Nat) : Option (Op×List Nat) := do
match xs with
| 0x45::0x31::md::rest =>
if md≥192 && md/8%8=md%8 then return (.base (.zero (md%8+8)),rest) else none
| 0x72::k::rest => return (.base (.jb k),rest)
| rex::opc::md::rest =>
if 0x48≤rex && rex≤0x4f then
let d := md/8%8+8*(rex/4%2)
let r := md%8+8*(rex%2)
if (md/64=0 || md/64=1) && md%8=4 && rex%4=0 then
match rest with
| 0x24::ts =>
let (off,ss) := if md/64=0 then (0,ts) else (ts.headD 0,ts.drop 1)
match opc with
| 0x89 => return (.stackStore off d,ss)
| 0x8b => return (.stackLoad d off,ss)
| 0x2b => return (.stackSub d off false,ss)
| 0x1b => return (.stackSub d off true,ss)
| _ => pure ()
| _ => pure ()
if md≥192 then
match opc,rest with
| 0xc1,k::ss => if md/8%8=4 then return (.shl r (k%64),ss)
| 0x11,ss => return (.addCarry r d,ss)
| 0x29,ss => return (.subReg r d,ss)
| 0x81,ss => if md/8%8=0 then
let (i,rs) ← imm 4 true ss (.addi r)
return (.base i,rs)
| _,_ => pure ()
if opc=0x0f then
match rest with
| mm::rs =>
if mm≥192 then
let d := mm/8%8+8*(rex/4%2)
let r := mm%8+8*(rex%2)
if md=0xaf then return (.lowMul d r,rs)
if md=0xa4 then
match rs with
| k::ts => if 0 pure ()
| _ => pure ()
| _ => pure ()
let (i,ss) ← P14ThresholdBytes.decode xs
return (.base i,ss)
def all : Nat → List Nat → Option (List Op)
| _,[] => some []
| 0,_::_ => none
| n+1,xs => do let (i,ss) ← decodeBand xs; return i :: (← all n ss)
structure S where
cpu : CPU
slot : Nat → Nat
def act (s : S) (i : Op) : S :=
let a := s.cpu
let r := a.reg
match i with
| .base j => {s with cpu := step a j}
| .stackStore off src => {s with slot := fun k => if k=off then r src else s.slot k}
| .stackLoad d off => {s with cpu := put a d (s.slot off)}
| .stackSub d off cf => {s with cpu := borrow a d (r d) (s.slot off+(if cf then a.cf.toNat else 0))}
| .lowMul d src => {s with cpu := put a d ((r d*r src)%W)}
| .shld d src k => {s with cpu := put a d (((r d*2^k)%W+r src/2^(64-k))%W)}
| .shl d k => {s with cpu := put a d ((r d*2^k)%W)}
| .addCarry d src => {s with cpu := count a d (r d+r src+a.cf.toNat)}
| .subReg d src => {s with cpu := borrow a d (r d) (r src)}
def run : S → List Op → S
| a,[] => a
| a,i::is => if a.cpu.taken then a else run (act a i) is
def lowOps : List Op := [
.base (.mov 8 7), .base (.mov 0 6), .base (.zero 13), .stackStore 8 9,
.lowMul 8 6, .base (.mov 12 13), .stackStore 0 13, .base (.mov 13 9), .base (.mul 6),
.base (.add 8 8), .base (.add 8 2), .stackStore 16 0, .base (.mov 2 7), .base (.mov 0 6),
.shld 2 6 15, .shld 7 6 14, .stackStore 24 8, .shl 0 15, .shl 6 14,
.base (.addi 12 0xfffffffffc000000), .base (.adc 13 0xffffffffffffffff),
.base (.add 6 12), .addCarry 7 13, .stackSub 6 16 false, .stackSub 7 24 true,
.base (.cmp 0 6), .base (.sbb 2 7), .base (.jb 0xe2)]
def highOps : List Op := [
.base (.mov 7 11), .base (.mov 0 10), .lowMul 7 10, .base (.mul 10),
.base (.mov 6 7), .stackLoad 7 8, .base (.add 6 6), .base (.mov 12 0),
.base (.mov 0 10), .base (.add 6 2), .shl 0 15, .base (.mov 2 11),
.base (.mov 13 6), .stackLoad 6 0, .shld 2 10 15, .stackStore 32 0,
.base (.imm 0 0x7ffffffffc000000), .shld 11 10 14, .stackStore 40 2,
.base (.zero 2), .shl 10 14, .base (.add 0 6), .addCarry 2 7,
.base (.add 0 10), .stackLoad 10 32, .addCarry 2 11, .stackLoad 11 40,
.subReg 0 12, .base (.sbb 2 13), .base (.cmp 10 0), .base (.mov 14 11),
.base (.sbb 14 2), .base (.jb 0x68)]
def lowCode : List Nat := [
73, 137, 248, 72, 137, 240, 69, 49, 237, 76, 137, 76, 36, 8,
76, 15, 175, 198, 77, 137, 236, 76, 137, 44, 36, 77, 137, 205,
72, 247, 230, 77, 1, 192, 73, 1, 208, 72, 137, 68, 36, 16,
72, 137, 250, 72, 137, 240, 72, 15, 164, 242, 15, 72, 15, 164,
247, 14, 76, 137, 68, 36, 24, 72, 193, 224, 15, 72, 193, 230,
14, 73, 129, 196, 0, 0, 0, 252, 73, 131, 213, 255, 76, 1,
230, 76, 17, 239, 72, 43, 116, 36, 16, 72, 27, 124, 36, 24,
72, 57, 240, 72, 25, 250, 15, 130, 226, 0, 0, 0]
def highCode : List Nat := [
76, 137, 223, 76, 137, 208, 73, 15, 175, 250, 73, 247, 226, 72,
137, 254, 72, 139, 124, 36, 8, 72, 1, 246, 73, 137, 196, 76,
137, 208, 72, 1, 214, 72, 193, 224, 15, 76, 137, 218, 73, 137,
245, 72, 139, 52, 36, 76, 15, 164, 210, 15, 72, 137, 68, 36,
32, 72, 184, 0, 0, 0, 252, 255, 255, 255, 127, 77, 15, 164,
211, 14, 72, 137, 84, 36, 40, 49, 210, 73, 193, 226, 14, 72,
1, 240, 72, 17, 250, 76, 1, 208, 76, 139, 84, 36, 32, 76,
17, 218, 76, 139, 92, 36, 40, 76, 41, 224, 76, 25, 234, 73,
57, 194, 77, 137, 222, 73, 25, 214, 114, 104]
theorem low_decoded : all lowCode.length lowCode=some lowOps := by decide +kernel
theorem high_decoded : all highCode.length highCode=some highOps := by decide +kernel
abbrev Pair := Nat×Nat
def limbs (x : Nat) : Pair := (x%W,(x/W)%W)
def shiftPair (x k : Nat) : Pair := ((x*2^k)%W,(x/2^(64-k))%W)
def plusPair (p q : Pair) : Pair :=
let x := p.1+q.1
(x%W,(p.2+q.2+(decide (W≤x)).toNat)%W)
def minusPair (p q : Pair) : Pair :=
((p.1+W-q.1)%W,(p.2+W-(q.2+(decide (p.1 dsimp <;> omega
private theorem shift15 (t : Nat) :
shiftPair t 15 = limbs (t*2^15) := by unfold shiftPair limbs W; apply Prod.ext <;> dsimp <;> omega
private theorem plus_limbs (x y : Nat) :
plusPair (limbs x) (limbs y)=limbs (x+y) := by
unfold plusPair limbs W
by_cases h : 18446744073709551616≤x%18446744073709551616+y%18446744073709551616 <;>
simp [h,Bool.toNat] <;> (try constructor) <;> omega
private theorem minus_limbs (x y : Nat) (hy : y
simp [h,Bool.toNat] <;> (try constructor) <;> omega
private theorem less_limbs (x y : Nat) :
less (limbs x) (limbs y)=false ↔ y%wide≤x%wide := by
unfold less limbs W wide
by_cases h : x%18446744073709551616
simp [h,Bool.toNat] <;> omega
private theorem n_limbs (n : Nat) (hn : n
#### `asmproof/ThresholdBytes.lean`
~~~lean
import Threshold
/-! Decoder and word-level semantics for the unmodified GCC 14.2 register-only
inverse-threshold and overflow-test block in p14_threshold_seeded. Offsets are
from the ELF function symbol, independent of its link address. -/
namespace P14ThresholdBytes
open P14Threshold
set_option maxRecDepth 16384
abbrev R := Nat -- architectural register indices RAX=0, RCX=1, RDX=2, ...
inductive I where
| imm (d : R) (v : Nat) | mov (d s : R) | mul (s : R)
| add (d s : R) | adc (d v : Nat) | addi (d v : Nat)
| shrd (d s k : Nat) | shr (d k : Nat)
| push (s : R) | lea (d s disp : Nat) | subi (d v : Nat)
| zero (d : R) | cmp (l r : R) | sbb (d s : R) | jb (disp : Nat)
deriving DecidableEq, Repr
def leBytes : List Nat → Nat
| [] => 0
| a::as => a+256*leBytes as
def imm (k : Nat) (signed : Bool) (xs : List Nat) (op : Nat → I) : Option (I×List Nat) :=
if xs.length some (.mul b,ss)
| 0x89,_,ss => some (.mov b r,ss)
| 0x01,_,ss => some (.add b r,ss)
| 0x39,_,ss => some (.cmp b r,ss)
| 0x19,_,ss => some (.sbb b r,ss)
| 0x83,5,ss => imm 1 true ss (.subi b)
| 0x83,2,ss => imm 1 true ss (.adc b)
| 0x83,0,ss => imm 1 true ss (.addi b)
| 0xc7,0,ss => imm 4 true ss (.imm b)
| 0xc1,5,k::ss => some (.shr b (k%64),ss)
| _,_,_ => none
def decode : List Nat → Option (I×List Nat)
| 0x55::ss => some (.push 5,ss)
| 0x53::ss => some (.push 3,ss)
| 0x41::opc::ss => if 0x50≤opc && opc<0x58 then some (.push (8+(opc-0x50)),ss) else none
| 0x31::md::ss => if md≥192 && md%8=md/8%8 then some (.zero (md%8),ss) else none
| 0x0f::0x82::ss => imm 4 false ss .jb
| rex::opc::ss =>
if rex<0x48 || rex>0x4f then none else
if 0xb8≤opc && opc<0xc0 then imm 8 false ss (.imm (opc-0xb8+8*(rex%2))) else
match opc,ss with
| 0x8d,md::ts =>
if md/64=1 && md%8≠4 then
imm 1 true ts (.lea (md/8%8+8*(rex/4%2)) (md%8+8*(rex%2))) else none
| 0x0f,0xac::md::k::ts =>
if md≥192 && 0 regop rex opc md ts
| _,_ => none
| _ => none
def decodeAll : Nat → List Nat → Option (List I)
| _, [] => some []
| 0, _::_ => none
| n+1, xs => do
let (i,rest) ← decode xs
return i :: (← decodeAll n rest)
def code : List Nat := [
72, 184, 24, 199, 143, 14, 233, 73, 145, 237, 72, 247, 225, 72,
184, 15, 132, 153, 247, 24, 80, 35, 32, 73, 137, 208, 72, 247,
225, 72, 137, 198, 72, 137, 215, 72, 184, 95, 34, 100, 248, 54,
162, 240, 125, 76, 1, 198, 72, 131, 215, 0, 72, 15, 172, 254,
48, 72, 193, 239, 48, 72, 131, 198, 1, 72, 131, 215, 0, 73,
247, 231, 72, 184, 11, 132, 153, 247, 24, 80, 35, 32, 73, 137,
208, 73, 247, 231, 73, 137, 194, 73, 137, 211, 72, 199, 194, 255,
223, 255, 255, 77, 1, 194, 73, 131, 211, 0, 49, 192, 77, 15,
172, 218, 48, 73, 137, 198, 73, 193, 235, 48, 72, 57, 242, 73,
25, 254, 15, 130, 92, 1, 0, 0, 76, 57, 210, 76, 25, 216,
15, 130, 80, 1, 0, 0]
open I
def arithmetic : List I := [
.imm 0 0xed9149e90e8fc718, .mul 1,
.imm 0 0x20235018f799840f, .mov 8 2, .mul 1, .mov 6 0, .mov 7 2,
.imm 0 0x7df0a236f864225f, .add 6 8, .adc 7 0,
.shrd 6 7 48, .shr 7 48, .addi 6 1, .adc 7 0,
.mul 15, .imm 0 0x20235018f799840b, .mov 8 2, .mul 15,
.mov 10 0, .mov 11 2, .imm 2 0xffffffffffffdfff,
.add 10 8, .adc 11 0, .zero 0, .shrd 10 11 48, .mov 14 0, .shr 11 48]
def guards : List I := [.cmp 2 6,.sbb 14 7,.jb 0x15c,.cmp 2 10,.sbb 0 11,.jb 0x150]
theorem decoded : decodeAll code.length code = some (arithmetic ++ guards) := by decide +kernel
def W : Nat := 18446744073709551616
structure CPU where
reg : R → Nat
cf : Bool
taken : Bool
def put (a : CPU) (d v : Nat) := { a with reg := fun i => if i=d then v else a.reg i }
def setcarry (a : CPU) (c : Bool) := {a with cf:=c}
def count (a : CPU) (d v : Nat) :=
setcarry (put a d (v%W)) (decide (W≤v))
def borrow (a : CPU) (d l r : Nat) :=
setcarry (put a d ((l+W-r)%W)) (decide (l put a d v
| .mov d s => put a d (a.reg s)
| .mul s =>
let v := a.reg 0 * a.reg s
setcarry (put (put a 0 (v%W)) 2 (v/W)) (decide (W≤v))
| .add d s => count a d (a.reg d+a.reg s)
| .adc d v => count a d (a.reg d+v+a.cf.toNat)
| .addi d v => count a d (a.reg d+v)
| .shr d k => put a d (a.reg d/2^k)
| .shrd d s k => put a d (((a.reg d + a.reg s*W)/2^k)%W)
| .zero d => setcarry (put a d 0) false
| .push _ => put a 4 ((a.reg 4+W-8)%W)
| .lea d r disp => put a d ((a.reg r+disp)%W)
| .subi d v => borrow a d (a.reg d) v
| .cmp l r => setcarry a (decide (a.reg l borrow a d (a.reg d) (a.reg s+a.cf.toNat)
| .jb _ => {a with taken:=a.cf}
def run : CPU → List I → CPU
| a, [] => a
| a, i::is => if a.taken then a else run (step a i) is
/-- After an unsigned carry-producing sum of (low,high) and an addend of
one word, the emitted SHRD/SHR pair is the ordinary 128-bit right shift. -/
private theorem shifted (lo hi u : Nat) (l : lo simp [c,Bool.toNat] <;> omega
private theorem full (v : Nat) : v%W+(v/W)*W=v := by
unfold W; omega
/-- Reassembly also distributes across the low and high word of a right
shift, assuming the lower argument is a single architectural word. -/
private theorem join_shift (lo hi : Nat) (hl : lo simp [c,Bool.toNat] <;> omega
theorem arithmetic_correct (a : CPU) (go : a.taken=false)
(hl : a.reg 1<2^52) (hh : a.reg 15<2^52) :
let b := run a arithmetic
b.reg 6+b.reg 7*W = lowerThreshold (a.reg 1) ∧
b.reg 10+b.reg 11*W = upperThreshold (a.reg 15) := by
obtain ⟨_,l,h,_⟩ := execute a go
have lw := congrArg (fun p : Nat×Nat => p.1+p.2*W) l
have hw := congrArg (fun p : Nat×Nat => p.1+p.2*W) h
dsimp only at lw hw ⊢
rw [lw,hw,plus_value _ (pair_small ..), pair_value _ _ _ hl (by decide) (by decide),
pair_value _ _ _ hh (by decide) (by decide)]
exact ⟨rfl,rfl⟩
private theorem run_append (a : CPU) (xs ys : List I) :
run a (xs++ys) = run (run a xs) ys := by
have stop (b : CPU) (h : b.taken=true) (zs : List I) : run b zs=b := by
cases zs <;> simp [run,h]
induction xs generalizing a with
| nil => rfl
| cons i is ih =>
simp only [List.cons_append,run]
cases e : a.taken
· exact ih (step a i)
· simp [e,stop a e ys]
theorem inverted_guard (b : CPU) (go : b.taken=false) (rdx : b.reg 2=W-8193)
(z : b.reg 0=0) (z' : b.reg 14=0)
(l : b.reg 6 by_cases hc : W-8193
by_cases ll : b.reg 7=0 <;> by_cases hh : b.reg 11=0 <;>
simp [guards,run,go,step,put,setcarry,borrow,rdx,z,z',lc,hc,ll,hh,Bool.toNat,Nat.pos_of_ne_zero] <;>
unfold W at * <;> omega
theorem byte_guard (a : CPU) (go : a.taken=false) (hl : a.reg 1<2^52) (hh : a.reg 15<2^52) :
let b := run a ((decodeAll code.length code).getD [])
b.taken=false ↔ lowerThreshold (a.reg 1)≤W-8193 ∧ upperThreshold (a.reg 15)≤W-8193 := by
rw [decoded]
simp only [Option.getD_some,run_append]
have e := execute a go
have q := arithmetic_correct a go hl hh
dsimp only at e q
obtain ⟨go',lw,hw,z,z',rdx⟩ := e
have ll := congrArg Prod.fst lw
have hl' : (run a arithmetic).reg 6
by_cases high : 0xffffffffffffd < (a.reg 8+0xffffffffffffffff)%W <;>
simp [run,entry,go,step,put,setcarry,borrow,low,high] <;> omega
/-- Within this executable prefix an arbitrary candidate either branches to
the single fallback, or both exact integer thresholds fit below the cutoff. -/
theorem linked_prefix_guard (a : CPU) (go : a.taken=false) (jl : a.reg 1 ⟨hl, hh, b.mp hp⟩, fun hp => b.mpr hp.2.2⟩
· have stop (xs : List I) : run (run a entry) xs=run a entry := by cases xs <;> simp [run,he]
rw [stop,stop,he]
have bad : ¬(admissible (a.reg 1) ∧ admissible (a.reg 8)) := by
intro h; have e := gate.1.mpr h; rw [he] at e; contradiction
simp only [Bool.true_eq_false, false_iff]
intro h; exact bad ⟨h.1,h.2.1⟩
theorem entry_branches_target_fallback : 0x2e+0x1f2=0x220 ∧ 0x3e+0x1e2=0x220 := by decide
#print axioms linked_prefix_guard
end P14ThresholdBytes
~~~
#### `asmproof/Upper.lean`
~~~lean
import Problem14
/-! Unnormalised path counts remove every probability division.
At remaining time t, binomial index j=(t+x)/2 increases with score x.
One draw leads to indices j and j−1, each carrying its own path mass. -/
namespace Problem14.Upper
abbrev UCell := Nat × Int
def empty : UCell := (0,0)
def advance (t : Nat) (j : Int) (a b : UCell) : UCell :=
let n := a.1+b.1
(n, max ((2*j-(t:Int))*(n:Int)) (a.2+b.2))
def cell : Nat → Int → UCell
| 0, j => if j=0 then (1,0) else empty
| t+1, j => advance (t+1) j (cell t j) (cell t (j-1))
theorem cell_outside (t : Nat) (j : Int) (h : j<0 ∨ (t:Int) simp [cell, show j≠0 by omega]
| succ t ih =>
rw [cell, ih j (by omega), ih (j-1) (by omega)]
simp [advance, empty]
def unshift (R : Nat) (a : Cell) : UCell := (a.1, (a.2:Int)-(R:Int)*(a.1:Int))
private theorem unshift_combine (R r b : Nat) (hr : r≤R) (u v : Cell) :
unshift R (combine R r b u v) =
advance (r+b) b (unshift R u) (unshift R v) := by
have castmax (a b : Nat) : (↑(max a b) : Int)=max (a:Int) (b:Int) := by omega
apply Prod.ext
· rfl
· simp only [unshift, combine, reward, advance, castmax, Int.natCast_mul,
Int.natCast_add, Int.ofNat_sub hr]
rw [← Int.sub_max_sub_right]
congr 1
· rw [← Int.sub_mul]
congr 1
omega
· rw [Int.mul_add]
omega
/-- The row numerator is the original optimal stopping value, summed over
physical decks with its constant shift removed. -/
theorem cell_eq_game (R r b : Nat) (hr : r≤R) :
cell (r+b) b = unshift R (model R r b) := by
have mod00 : model R 0 0 = (1,R) := by simp [model, deck, weight, paths, bellman]
have modR (a : Nat) : model R (a+1) 0 = combine R (a+1) 0 (model R a 0) (0,0) := by
simp [model, deck, weight, paths, bellman, combine]
have modB (b : Nat) : model R 0 (b+1) = combine R 0 (b+1) (0,0) (model R 0 b) := by
simp [model, deck, weight, paths, bellman, combine]
have modRB (a b : Nat) : model R (a+1) (b+1) =
combine R (a+1) (b+1) (model R a (b+1)) (model R (a+1) b) := by
simp [model, deck, weight, paths, bellman, combine]
induction r,b using deck.induct with
| case1 => simp [cell, mod00, unshift]
| case2 r ih =>
rw [modR, unshift_combine _ _ _ hr]
change advance (r+1) 0 (cell r 0) (cell r (0-1)) = _
have ih' : cell r 0 = unshift R (model R r 0) := ih (by omega)
rw [cell_outside r (0-1) (by omega), ih']
simp [unshift, empty]
| case3 b ih =>
rw [modB, unshift_combine _ _ _ hr]
rw [Nat.zero_add, cell, Int.natCast_succ, Int.add_sub_cancel, cell_outside b (↑b+1) (by omega)]
rw [Nat.zero_add] at ih
rw [ih (by omega)]
simp [unshift, empty]
| case4 r b ih₁ ih₂ =>
rw [modRB, unshift_combine _ _ _ hr]
have he : r+1+(b+1) = (r+(b+1))+1 := by omega
rw [he, cell]
simp only [Int.natCast_succ, Int.add_sub_cancel]
simp only [Int.natCast_succ] at ih₁
rw [ih₁ (by omega)]
congr 1
simpa [show r+(b+1)=r+1+b by omega] using ih₂ (by omega)
/-- Unnormalised heat propagation on the *whole* integer line. -/
def heat (initial : Int → Int) : Nat → Int → Int
| 0, j => initial j
| t+1, j => heat initial t j + heat initial t (j-1)
theorem heat_nonneg (f : Int → Int) (hf : ∀ j, 0≤f j) (t : Nat) (j : Int) :
0≤heat f t j := by
induction t generalizing j with
| zero => exact hf j
| succ t ih => exact Int.add_nonneg (ih j) (ih (j-1))
/-- This comparison extends over both physical edges, including the impossible
child on the right. On such a child the card-game numerator is zero and the
full-line comparison is nonnegative. -/
theorem propagate (T : Nat) (D : Int) (f : Int → Int) (hf : ∀ j, 0≤f j)
(cut : ∀ j : Int, 0≤j → j≤(T:Int) → D*(cell T j).2≤heat f T j)
(stop : ∀ t : Nat, T
have : T=0 := by omega
subst T
by_cases h : j<0 ∨ (0:Int)
by_cases outside : j<0 ∨ ((t+1:Nat):Int) (try decide)
split <;> (try decide)
split <;> (try decide)
split <;> (try decide)
split <;> decide
end Problem14.Upper
~~~
#### `asmproof/Upper3600.lean`
~~~lean
import asmproof.UpperCentral
/-! The exact 3,601-state arithmetic certificate. Only this file uses Lean's
native evaluation axiom; the game equivalence, heat comparison, all edge
conditions, centering, and Boolean-reflection theorem are kernel proofs in
the three imported source files. -/
namespace Problem14.Upper
theorem verified_cutoff_3600 : test 3600=true := by native_decide
theorem finite_upper_3600 (j : Int) (lo : 0≤j) (hi : j≤3600) :
200000*(cell 3600 j).2+400*((cell 3600 j).1:Int) ≤ heat initial 3600 j :=
cutoff_sound 3600 verified_cutoff_3600 j lo hi
theorem upper_3600 {n : Nat} {C D : Int} (hD : 0≤D) (hc : 58905*D ≤ C)
(hn : 3600≤2*n)
(obstacle : ∀ t : Nat, 3600
#### `asmproof/UpperBinomial.lean`
~~~lean
import asmproof.GameSmallObstacle
import asmproof.GameBeta
import asmproof.UpperContact
/-! Exact adjacent binomial masses and the heat mid-CDF agree with the
rational correction and the beta integral throughout the large-score region. -/
namespace Problem14.UpperReal
open Problem14.Upper Finset
private theorem mid_left (t : Nat) (j : Int) (hj : j<0) : heat mid t j=0 := by
induction t generalizing j with
| zero => simp [heat, mid, hj]
| succ t ih => rw [heat, ih j hj, ih (j-1) (by omega)]; rfl
private theorem mid_zero (t : Nat) : heat mid t 0=1 := by
induction t with
| zero => rfl
| succ t ih => rw [heat, ih, mid_left t (0-1) (by decide)]; rfl
private theorem mid_diff (t : Nat) (j : Int) :
heat mid t (j+1)-heat mid t j = heat delta t j+heat delta t (j+1) := by
induction t generalizing j with
| zero =>
simp only [heat,mid,delta]
repeat' first | omega | split
| succ t ih =>
simp only [heat,Int.add_sub_cancel]
have a := ih j
have b := ih (j-1)
rw [show j-1+1=j by omega] at b
omega
theorem heat_mid_choose (t k : Nat) :
heat mid t k = 2*(∑ i ∈ range k, (t.choose i:Int))+(t.choose k:Int) := by
induction k with
| zero => simp [mid_zero]
| succ k ih =>
rw [Finset.sum_range_succ, Int.natCast_succ]
have m := mid_diff t (k:Int)
rw [delta_choose t k, ← Int.natCast_succ, delta_choose, Int.natCast_succ] at m
omega
theorem heat_mid_ratio (t k : Nat) (hk : k≤t) :
((heat mid t k:ℤ):ℝ)/(t.choose k:ℝ) = 2*(BinomialBeta.midCDF t k/BinomialBeta.mass t k) := by
have p : (0:ℝ) (n:ℝ)) (Nat.choose_succ_right_eq t k)
simpa [Nat.cast_sub h] using e
theorem bump_ratio (t k : Nat) (hk : 2≤k) (hkt : k≤t) :
(heat bump t k:ℝ) = 200000*(t.choose k:ℝ)*correction t (2*(k:ℝ)-t) := by
let p : ℝ := t.choose k
let z : ℝ := k
let b : ℝ := t-z
have bz : 0≤b := by dsimp [b,z]; exact sub_nonneg.mpr (by exact_mod_cast hkt)
have zz : 0≤z := Nat.cast_nonneg _
have b1 : 0
#### `asmproof/UpperCentral.lean`
~~~lean
import asmproof.UpperCutoff
/-! Centering and rational coefficient transport for the discrete majorant.
A rational upper coefficient is represented by C/(100000 D), D positive. -/
namespace Problem14.Upper
def delta (j : Int) : Int := if j=0 then 1 else 0
def mid (j : Int) : Int := if j<0 then 0 else if j=0 then 1 else 2
def bump (j : Int) : Int :=
110000*(delta (j-2)-delta (j-1)) + 28000*(delta (j+1)+delta (j-1)-2*delta j)
def seed (C D j : Int) := C*mid j + D*bump j
theorem initial_eq (j : Int) : initial j = seed 58905 1 j := by
unfold initial seed mid bump delta
repeat' first | omega | split
private theorem mid_nonneg (j : Int) : 0≤mid j := by
unfold mid; split <;> (try decide); split <;> decide
theorem heat_mono {f g : Int → Int} (h : ∀ j, f j ≤ g j) (t : Nat) (j : Int) :
heat f t j ≤ heat g t j := by
induction t generalizing j with
| zero => exact h j
| succ t ih => exact Int.add_le_add (ih j) (ih (j-1))
theorem heat_linear (a b : Int) (f g : Int → Int) (t : Nat) (j : Int) :
heat (fun i => a*f i+b*g i) t j = a*heat f t j+b*heat g t j := by
induction t generalizing j with
| zero => rfl
| succ t ih => simp only [heat, ih, Int.mul_add]; omega
theorem heat_shift (f : Int → Int) (k : Int) (t : Nat) (j : Int) :
heat (fun i => f (i+k)) t j = heat f t (j+k) := by
induction t generalizing j with
| zero => rfl
| succ t ih => simp only [heat, ih]; congr 2; omega
theorem heat_reflect (f : Int → Int) (t : Nat) (j : Int) :
heat (fun i => f (-i)) t j = heat f t ((t:Int)-j) := by
induction t generalizing j with
| zero => simp [heat]
| succ t ih =>
simp only [heat, ih, Int.natCast_succ]
rw [show (t:Int)-(j-1) = t+1-j by omega, show (t:Int)+1-j-1 = t-j by omega, Int.add_comm]
private theorem heat_const (a : Int) (t : Nat) (j : Int) :
heat (fun _ => a) t j = a*2^t := by
induction t generalizing j with
| zero => simp [heat]
| succ t ih => simp only [heat, ih, Int.pow_succ, ← Int.mul_assoc]; omega
theorem mid_center (n : Nat) : heat mid (2*n) n = 2^(2*n) := by
have hm : (fun i => 1*mid i+1*mid (-i)) = fun _ => (2:Int) := by
funext i; unfold mid; repeat' first | omega | split
have e := heat_linear 1 1 mid (fun i => mid (-i)) (2*n) n
rw [hm, heat_const, heat_reflect, show ((2*n:Nat):Int) - (n:Int)=n by omega] at e
omega
private theorem delta_even (j : Int) : delta (-j)=delta j := by
unfold delta; repeat' first | omega | split
/-- Pascal masses increase toward the center. A one-step induction works
because the adjacent difference at t+1 is the sum of the two adjacent
differences at t, except at the central tie (handled by symmetry). -/
theorem delta_unimodal (t : Nat) (j : Int) (h : 2*j<(t:Int)) :
heat delta t j ≤ heat delta t (j+1) := by
induction t generalizing j with
| zero =>
simp only [heat, delta]
repeat' first | omega | split
| succ t ih =>
by_cases h' : 2*j < (t:Int)
· exact Int.add_le_add (ih j h') (by simpa using ih (j-1) (by omega))
· have eq : 2*j=(t:Int) := by omega
have sym := heat_reflect delta t (j+1)
simp only [delta_even] at sym
change heat delta t (j+1) = heat delta t ((t:Int)-(j+1)) at sym
rw [show (t:Int) - (j+1) = j-1 by omega] at sym
simp only [heat, Int.add_sub_cancel]
omega
theorem bump_heat (t : Nat) (j : Int) :
heat bump t j = 110000*(heat delta t (j-2)-heat delta t (j-1))+
28000*(heat delta t (j+1)+heat delta t (j-1)-2*heat delta t j) := by
induction t generalizing j with
| zero => rfl
| succ t ih =>
simp only [heat, ih]
rw [show j-1+1=j by omega, show j+1-1=j by omega, show j-1-2=j-2-1 by omega]
omega
theorem bump_center (n : Nat) : heat bump (2*n) n ≤ 0 := by
rw [bump_heat]
have a := delta_unimodal (2*n) ((n:Int)-2) (by omega)
have b := delta_unimodal (2*n) ((n:Int)-1) (by omega)
have c := heat_reflect delta (2*n) ((n:Int)+1)
simp only [delta_even, show ((2*n:Nat):Int)-((n:Int)+1)=n-1 by omega] at c
change heat delta (2*n) ((n:Int)+1) = heat delta (2*n) ((n:Int)-1) at c
rw [show (n:Int)-2+1=n-1 by omega] at a
rw [show (n:Int)-1+1=n by omega] at b
omega
private theorem seed_ge (C D j : Int) (hc : 58905*D≤C) :
D*initial j ≤ seed C D j := by
have e := Int.mul_le_mul_of_nonneg_right hc (mid_nonneg j)
rw [initial_eq]
simp only [seed, Int.one_mul, Int.mul_add]
rw [← Int.mul_assoc, Int.mul_comm D 58905]; omega
private theorem heat_scale (D : Int) (f : Int → Int) (t : Nat) (j : Int) :
heat (fun i => D*f i) t j = D*heat f t j := by
simpa using heat_linear D 0 f f t j
/-- If the remaining infinite-family obstacle inequalities hold, the finite
certificate gives a balanced-deck upper bound at every horizon above T.
Every quantity in this statement refers to the original card-game tree. -/
theorem game_upper {T n : Nat} {C D : Int} (hD : 0≤D) (hc : 58905*D ≤ C)
(checked : test T=true) (hn : T≤2*n)
(obstacle : ∀ t : Nat, T C*mid j+D*bump j) (2*n) n ≤ _
rw [heat_linear, mid_center]
have e := Int.mul_le_mul_of_nonneg_left (bump_center n) hD
omega
rw [show 2*n=n+n by omega] at rhs
simpa [show 2*n=n+n by omega] using Int.le_trans p rhs
end Problem14.Upper
~~~
#### `asmproof/UpperContact.lean`
~~~lean
import Mathlib.Analysis.Calculus.Deriv.MeanValue
import Mathlib.Analysis.Calculus.Deriv.Mul
import Mathlib.Tactic.Linarith
import Mathlib.Tactic.FieldSimp
import Mathlib.Tactic.Positivity
/-! The continuous upper-contact estimate. Two applications of the mean
value theorem control the entire exceptional strip. The assumptions on g
are verified below for f−id, assuming only f'=k+xf, f≥0 and contact at α. -/
namespace Problem14.UpperReal
open Set
private theorem mean {f d : ℝ → ℝ} (hd : ∀ x, HasDerivAt f (d x) x)
{a b : ℝ} (hab : a (hd x).continuousAt)).continuousOn
(fun x _ => hd x)
exact ⟨z,hz,by rw [h]; field_simp [sub_ne_zero.mpr hab.ne']⟩
theorem contact {g d dd : ℝ → ℝ} {a s y : ℝ}
(gd : ∀ x, HasDerivAt g (d x) x) (gdd : ∀ x, HasDerivAt d (dd x) x)
(mono : MonotoneOn dd (Ici 0)) (pos : ∀ x≥0, 0≤dd x)
(ha : 0≤a) (hy : 0≤y) (hs : 0 v⟩
· have ya' : y simp <;> ring
obtain ⟨z,hz,we⟩ := mean dw ya'
have dz := (slope z (by linarith [hz.1]) hz.2).1
have wz : (a-y)*(d z+(a-z)*dd z) ≤ 0 := mul_nonpos_of_nonneg_of_nonpos (by linarith) (by linarith)
dsimp [w] at we
rw [g0,d0] at we
have tang : (a-y)*(-d y) ≤ 2*g y := by linarith
have sdy := slope y hy ya'
have dneg : 0 ≤ -d y := le_trans (mul_nonneg (by linarith) (pos y hy)) sdy.1
have far (h : 2≤s*(a-y)) : 0≤s*g y+d y := by
nlinarith [mul_nonneg (sub_nonneg.mpr h) dneg, mul_le_mul_of_nonneg_left tang hs.le]
constructor
· by_cases near : s*(a-y)≤2
· have e := mul_le_mul_of_nonneg_left sdy.2
(show 0≤2-s*(a-y) by linarith)
have sq := mul_nonneg ha (sq_nonneg (s*(a-y)-1))
apply (div_le_iff₀ hs).mpr
nlinarith [mul_le_mul_of_nonneg_left tang hs.le,
mul_le_mul_of_nonneg_left (mul_le_mul_of_nonneg_left tang hs.le) hs.le,
mul_le_mul_of_nonneg_left e hs.le]
· exact le_trans (div_nonpos_of_nonpos_of_nonneg (by linarith) hs.le) (far (by linarith))
· exact fun h => far (h.resolve_left ya)
/-- In the application k=1−α² and f=kA, where A solves A'=1+yA.
All derivative-monotonicity assumptions in contact follow from this ODE. -/
theorem ode_contact {f : ℝ → ℝ} {a s y : ℝ}
(df : ∀ x, HasDerivAt f (1-a^2+x*f x) x)
(fpos : ∀ x≥0, 0≤f x) (f0 : f a=a)
(ha : 0≤a) (ha1 : a≤1) (hy : 0≤y) (hs : 0
simp [p,q]
have dq (x : ℝ) : HasDerivAt q (2*p x+x*q x) x := by
convert (df x).add ((hasDerivAt_id x).mul (dp x)) using 1 <;> simp [q,p] <;> ring
have pp (x : ℝ) (hx : 0≤x) : 0≤p x := by
dsimp [p]; nlinarith [mul_nonneg (sub_nonneg.mpr ha1) (show 0≤1+a by linarith),
mul_nonneg hx (fpos x hx)]
have qp (x : ℝ) (hx : 0≤x) : 0≤q x := add_nonneg (fpos _ hx) (mul_nonneg hx (pp _ hx))
have mq : MonotoneOn q (Ici 0) := by
intro x hx z _ h
rcases eq_or_lt_of_le h with rfl|hh
· exact le_rfl
obtain ⟨c,hc,e⟩ := mean dq hh
have hc0 : 0≤c := le_trans hx hc.1.le
have dpos : 0≤2*p c+c*q c := add_nonneg (by linarith [pp c hc0]) (mul_nonneg hc0 (qp c hc0))
nlinarith [mul_nonneg (sub_nonneg.mpr h) dpos]
have dg (x : ℝ) : HasDerivAt (fun z => f z-z) (p x-1) x := (df x).sub (hasDerivAt_id x)
have ddg (x : ℝ) : HasDerivAt (fun z => p z-1) (q x) x := (dp x).sub_const 1
exact contact dg ddg mq qp ha hy hs (by simp [f0]) (by simp [p,f0]; ring)
(by simp [q,p,f0]; ring)
/-- The actual adjacent-binomial corrections in M−Q. -/
noncomputable def correction (t x : ℝ) : ℝ :=
(55/100)*(t+x)/(t-x+2)*(2*x-6)/(t-x+4) +
(56/100)*(x^2-t-2)/((t+2)^2-x^2)
theorem correction_bound {t x : ℝ} (hx : 4≤x) (ht : x≤t) :
(11/10)*(x-3)/(t+1)-(56/100)/(t+2) ≤ correction t x := by
have p1 : 0 out (Or.inl h))
have p : (496/100:ℝ) ≤ a*s/10 := by
nlinarith [mul_nonneg (sub_nonneg.mpr ha) hs0.le]
have q : a/s ≤ ((11/10)*(x-3)-56/100)/(t+1) := by
rw [div_le_div_iff₀ hs0 ht1, ← hsq]
nlinarith [mul_nonneg (show 0≤(11/10)*(x-3)-56/100-a*s by linarith) hs0.le]
rw [neg_div] at localBound
linarith
end Problem14.UpperReal
~~~
#### `asmproof/UpperCutoff.lean`
~~~lean
import asmproof.Upper
/-! Exact executable Pascal/Bellman/majorant table. One pass over each row.
The first entry represents binomial index −1. The last represents t+2.
Beyond the right sentinel the initial heat function is constant. -/
namespace Problem14.Upper
abbrev Entry := UCell × Int
def merge (t : Nat) (j : Int) (l r : Entry) : Entry :=
(advance t j r.1 l.1,r.2+l.2)
def ghost (t : Nat) : Entry := (empty,117810*2^t)
def sweep (t : Nat) (j : Int) (prev : Entry) : List Entry → List Entry
| [] => []
| a::as => merge t j prev a :: sweep t (j+1) a as
def row : Nat → List Entry
| 0 => [(empty,28000),((1,0),2905),(empty,35810),(empty,227810)]
| t+1 => sweep (t+1) (-1) (empty,0) (row t ++ [ghost t])
def checkGap : List Entry → Bool
| [] => true
| e::es => decide (200000*e.1.2+400*(e.1.1:Int)≤e.2) && checkGap es
def test (t : Nat) := checkGap (row t)
def reference (t : Nat) (j : Int) : Entry := (cell t j,heat initial t j)
private theorem left_heat (t : Nat) (j : Int) (h : j < -1) : heat initial t j = 0 := by
induction t generalizing j with
| zero => simp [heat, initial, h]
| succ t ih => rw [heat, ih j h, ih (j-1) (by omega)]; rfl
private theorem right_heat (t : Nat) (j : Int) (h : (t:Int)+2 < j) :
heat initial t j = (ghost t).2 := by
induction t generalizing j with
| zero =>
simp [heat, ghost, initial, show ¬ j < -1 by omega, show j ≠ -1 by omega,
show j ≠ 0 by omega, show j ≠ 1 by omega, show j ≠ 2 by omega]
| succ t ih =>
rw [heat, ih j (by omega), ih (j-1) (by omega)]
simp [ghost, Int.pow_succ]; omega
private theorem merge_ref (t : Nat) (j : Int) :
merge (t+1) j (reference t (j-1)) (reference t j) = reference (t+1) j := by rfl
private theorem sweep_length (t : Nat) (j : Int) (prev : Entry) (xs : List Entry) :
(sweep t j prev xs).length = xs.length := by
induction xs generalizing j prev with
| nil => rfl
| cons a as ih => simp [sweep, ih]
private theorem sweep_eq (t : Nat) (j : Int) (prev : Entry) (xs : List Entry)
(hp : prev = reference t (j-1))
(hx : ∀ (i : Nat) (hi : i simp at hi
| cons a as ih =>
cases i with
| zero =>
have ha := hx 0 (by simp)
simp at ha
simpa [sweep, hp, ha] using merge_ref t j
| succ i =>
have hr : i rfl
| succ t ih => simp [row, sweep_length, ih]
/-- Every entry of the efficient table is the actual Bellman numerator and
the whole-line heat solution, including the two carried boundary entries. -/
theorem row_eq (t i : Nat) (hi : i<(row t).length) :
(row t)[i] = reference t (-1+(i:Int)) := by
induction t generalizing i with
| zero =>
have hh : i < 4 := hi
have : i=0 ∨ i=1 ∨ i=2 ∨ i=3 := by omega
rcases this with h|h|h|h <;> subst i <;> rfl
| succ t ih =>
simp only [row] at hi ⊢
have hp : (empty,(0:Int)) = reference t (-1-1) := by
change (empty,(0:Int)) = (cell t (-2),heat initial t (-2))
rw [cell_outside t _ (Or.inl (by decide : (-2:Int)<0)), left_heat t _ (by decide : (-2:Int) < -1)]
apply sweep_eq t (-1) _ (row t++[ghost t]) hp _ i (by simpa [sweep_length] using hi)
intro k hk
rw [List.getElem_append]
split
· exact ih k ‹_›
· rename_i h
have e : k=(row t).length := by
simp only [List.length_append, List.length_cons, List.length_nil] at hk
omega
subst k
have hi' : (t:Int)+2 < -1+((row t).length:Int) := by rw [row_length]; omega
simp [reference, right_heat t _ hi', cell_outside t _ (Or.inr (by omega :
(t:Int) < -1+((row t).length:Int)))]
rfl
private theorem checkGap_get (xs : List Entry) (h : checkGap xs=true)
(i : Nat) (hi : i simp at hi
| cons e es ih =>
simp only [checkGap, Bool.and_eq_true, decide_eq_true_eq] at h
cases i with
| zero => exact h.1
| succ i => exact ih h.2 i (by simpa using hi)
/-- Boolean reflection. This is the finite-cutoff premise used in propagate,
with the stronger certified safety margin of 1/500. -/
theorem cutoff_sound (t : Nat) (h : test t=true) (j : Int) (hj : 0≤j) (hj' : j≤(t:Int)) :
200000*(cell t j).2 + 400*((cell t j).1:Int) ≤ heat initial t j := by
let i := j.toNat+1
have hi : i<(row t).length := by rw [row_length]; dsimp [i]; omega
have e := checkGap_get _ h i hi
rw [row_eq _ _ hi] at e
have hjj : -1+(i:Int) = j := by dsimp [i]; omega
exact hjj ▸ e
end Problem14.Upper
~~~
#### `asmproof/UpperGame.lean`
~~~lean
import asmproof.UpperGaussian
import asmproof.UpperBinomial
import asmproof.GameUpperPrice
import asmproof.Upper3600
import Brownian
/-! The whole upper bound, from the finite optimal stopping game to the
universal Gaussian coefficient; every asymptotic hypothesis is discharged. -/
namespace Problem14.UpperReal
open Upper GameUpperPrice Set MeasureTheory Real
open P14Quote.Coefficient
theorem large_game_obstacle {a : ℝ} (ha : 83/100≤a) (ha1 : a≤1)
(root : (1-a^2)*laplace a=a) (t : ℕ) (ht : 3600≤t) (j : ℤ)
(hj : 0≤j) (hj' : j≤(t:ℤ)) (hx : 4≤2*j-(t:ℤ)) :
200000*((2*j-(t:ℤ))*(↑(cell t j).1:ℤ):ℤ) ≤ barrier (2*(1-a^2)) t j := by
obtain ⟨k,rfl⟩ := Int.eq_ofNat_of_zero_le hj
have hkt : k≤t := by omega
have hk : 2≤k := by omega
let x : ℝ := 2*(k:ℝ)-t
let p : ℝ := t.choose k
let Q : ℝ := (1-a^2)*((heat mid t k:ℤ):ℝ)/p
have xmin : 4≤x := by dsimp [x]; exact_mod_cast hx
have xmax : x≤t := by
dsimp [x]
have : (k:ℝ)≤t := by exact_mod_cast hkt
linarith
have hp : 0
game_obstacle t (by omega))
linarith only [h]
#print axioms gaussian_game_upper
end Problem14.UpperReal
~~~
#### `asmproof/UpperGaussian.lean`
~~~lean
import asmproof.UpperContact
import Mathlib.Analysis.SpecialFunctions.Gaussian.GaussianIntegral
import Mathlib.Analysis.SpecialFunctions.Trigonometric.Series
import Mathlib.Analysis.SpecialFunctions.ImproperIntegrals
import Mathlib.MeasureTheory.Integral.IntervalIntegral.FundThmCalculus
/-! The Brownian half-line Gaussian profile, its ODE and the one-sided
discrete Laplace estimate with all integrability assumptions discharged. -/
namespace Problem14.UpperReal
open Set MeasureTheory Real
noncomputable section
def gaussian (u : ℝ) := exp (-u^2/2)
def profile (y : ℝ) := exp (y^2/2) *
((∫ u in Ioi (0:ℝ), gaussian u)+(∫ u in (0:ℝ)..y, gaussian u))
private theorem gauss_cont : Continuous gaussian := by unfold gaussian; fun_prop
private theorem gauss_integrable : Integrable gaussian := by
convert integrable_exp_neg_mul_sq (by norm_num : (0:ℝ)<1/2) using 1
unfold gaussian; congr 1; funext u; congr 1; ring
theorem profile_deriv (y : ℝ) : HasDerivAt profile (1+y*profile y) y := by
have hi := intervalIntegral.integral_hasDerivAt_right (gauss_cont.intervalIntegrable 0 y)
gauss_cont.stronglyMeasurable.stronglyMeasurableAtFilter gauss_cont.continuousAt
have de : HasDerivAt (fun u : ℝ => exp (u^2/2)) (exp (y^2/2)*y) y := by
convert (((hasDerivAt_id y).pow 2).div_const 2).exp using 1 <;> simp <;> ring
have h := de.mul ((hasDerivAt_const y (∫ u in Ioi 0, gaussian u)).add hi)
convert h using 1
unfold profile gaussian
have one : exp (y^2/2)*exp (-y^2/2) = 1 := by rw [← exp_add]; convert exp_zero using 1; ring_nf
nlinarith only [one]
theorem profile_eq_laplace {y : ℝ} (hy : 0≤y) :
profile y = ∫ u in Ioi (0:ℝ), exp (y*u-u^2/2) := by
have shift := (measurePreserving_add_right (volume : Measure ℝ) (-y)).setIntegral_preimage_emb
(measurableEmbedding_addRight (-y)) gaussian (Ioi (-y))
have pre : (fun x : ℝ => x + -y) ⁻¹' Ioi (-y) = Ioi (0:ℝ) := by ext x; simp
rw [pre] at shift
have sym := intervalIntegral.integral_comp_neg (a:=0) (b:=y) gaussian
simp only [neg_zero] at sym
have neg : (fun x => gaussian (-x))=gaussian := by funext x; simp [gaussian]
rw [neg] at sym
rw [intervalIntegral.integral_of_le (by linarith : -y≤0)] at sym
have part := setIntegral_union (f:=gaussian) (μ:=volume)
(show Disjoint (Ioc (-y) 0) (Ioi (0:ℝ)) by
apply Set.disjoint_left.mpr; intro z hz hz'; exact (not_lt_of_ge hz.2) hz')
measurableSet_Ioi gauss_integrable.integrableOn gauss_integrable.integrableOn
rw [Ioc_union_Ioi (by simp), min_eq_left (by linarith)] at part
have eq (u : ℝ) : exp (y*u-u^2/2) = exp (y^2/2)*gaussian (u + -y) := by
rw [gaussian, ← exp_add]; congr 1; ring
simp_rw [eq]
rw [integral_const_mul, shift, part, ← sym, profile, add_comm]
theorem profile_nonneg {y : ℝ} (hy : 0≤y) : 0≤profile y := by
rw [profile_eq_laplace hy]
exact integral_nonneg fun u => (exp_pos _).le
def lapKernel (s y u : ℝ) := exp (y*u - s^2*log (cosh (u/s)))
def discreteIntegral (s y : ℝ) := ∫ u in Ioi (0:ℝ), lapKernel s y u
private theorem cosh_lower (z : ℝ) : z-log 2 ≤ log (cosh z) := by
have e : exp z/2 ≤ cosh z := by rw [Real.cosh_eq]; linarith [exp_pos (-z)]
simpa [Real.log_div (exp_pos z).ne' (by norm_num : (2:ℝ)≠0)] using
Real.log_le_log (by positivity : 0 by rw [Real.norm_eq_abs, abs_of_pos (show 0 kernel_lower hs y u)
apply h.mono'
· exact (show Continuous (fun u : ℝ => exp (y*u-u^2/2)) by fun_prop).aestronglyMeasurable
· exact .of_forall fun u => by rw [Real.norm_eq_abs, abs_of_pos (exp_pos _)]; exact kernel_lower hs y u
/-- A dilation of the unscaled beta-sech integral; the 1/s Jacobian is
included. The physical binomial index is supplied separately by the beta
identity. -/
theorem rescale {t x s y : ℝ} (hs : 0 mul_nonneg hk (profile_nonneg hz)) f0 ha0 ha1 y0 hs
rw [rescale hs hsq he] at beta
have fac : (t+x)*s⁻¹=s+y := by rw [← div_eq_mul_inv]; apply (div_eq_iff hs.ne').mpr; nlinarith
have qeq : Q = (1-a^2)*(1+(s+y)*discreteIntegral s y) := by
rw [beta, ← mul_assoc, fac]
have q : s*(f y-y)+(1-a^2+y*f y-1) ≤ Q-x := by
rw [qeq]; dsimp [f]
nlinarith [mul_le_mul_of_nonneg_left (discrete_ge_profile hs y0 ys)
(show 0≤(1-a^2)*(s+y) from mul_nonneg hk (by linarith))]
apply restore hx hxt (by nlinarith : 60≤s) hsq ha (le_trans fc.1 q)
rintro (h|h)
· exact le_trans (fc.2 (Or.inr (by nlinarith))) q
· exact le_trans (fc.2 (Or.inl (by
dsimp [y]; apply (le_div_iff₀ hs).mpr; linarith))) q
end
end Problem14.UpperReal
~~~
#### `asmproof/VectorBatch.lean`
~~~lean
import VectorEntry
import VectorMasks
/-! Actual per-input mask packing and execution of both CTZ store loops
after the initial eight provisional results have been written. -/
namespace P14VectorBatch
set_option maxRecDepth 65536
open P14Quote P14Threshold P14VectorLane P14VectorGuard P14VectorEntry P14VectorMasks P14VectorThreshold
def accepted (n jl jh : Nat) : Bool :=
let tl := laneInvLow jl
let th := laneInvHigh jh
decide (validInvLow jl ∧ validInvHigh jh) &&
guard ⟨n,0⟩ (machineSquare tl) tl && guard ⟨n,2^63⟩ (machineSquare th) th
def provisional (n jl jh seed : Nat) : Nat×Nat :=
let lower := if le128 (machineSquare (laneInvLow jl)) ⟨n,0⟩ then jl else subW jl 1
let higher := if le128 ⟨n,2^63⟩ (machineSquare (laneInvHigh jh)) then jh else addW jh 1
(subW lower (clip seed),higher)
def repair (n seed : Nat) (out : Nat×Nat) := (subW (addW out.1 (clip seed)) (debit n),out.2)
def run (mem : Nat → Nat) (n jl jh d : Index → Nat) : Index → Nat×Nat :=
let ok := pack (fun i=>accepted (n i) (jl i) (jh i))
let wrong := pack (fun i=> !(debitPass mem (n i) (clip (d i))))
let out := fun i=>provisional (n i) (jl i) (jh i) (d i)
let debitFixed := applyMask (fun i=>repair (n i) (d i)) (adjust wrong ok) out
applyMask (fun i _=>reference (n i)) (missing ok) debitFixed
private theorem choose {A B : Type} (ok validDebit : Bool) (original repaired : A) (h : B) (slow : A×B) :
(if ok then (if !validDebit then (repaired,h) else (original,h)) else slow) =
(if ok then ((if validDebit then original else repaired),h) else slow) := by
cases ok <;> cases validDebit <;> rfl
theorem run_eq_batch (mem : Nat → Nat) (n jl jh d : Index → Nat) :
run mem n jl jh d = batch mem n jl jh d := by
funext i
unfold run batch
try dsimp only
rw [two_repairs,bit_pack,bit_pack]
exact choose (accepted (n i) (jl i) (jh i)) (debitPass mem (n i) (clip (d i)))
(provisional (n i) (jl i) (jh i) (d i)).1
(repair (n i) (d i) (provisional (n i) (jl i) (jh i) (d i))).1
(provisional (n i) (jl i) (jh i) (d i)).2 (reference (n i))
/-- No assumptions about hint accuracy or which lanes go through either
fallback. The correct table can be instantiated with table words checked
by the ELF checker, or directly with the closed threshold formula. -/
theorem run_correct {mem : Nat → Nat} (table : tableOK mem)
(n jl jh d : Index → Nat) (hn : ∀ i, 32768 ≤ n i ∧ n i < word) :
run mem n jl jh d = fun i=>reference (n i) := by
rw [run_eq_batch]
exact batch_correct table _ _ _ _ hn
theorem exact_table (n jl jh d : Index → Nat) (hn : ∀ i, 32768 ≤ n i ∧ n i < word) :
run (fun q=>P14Debit.threshold (q+17)) n jl jh d = fun i=>reference (n i) :=
run_correct (fun _ _ => rfl) _ _ _ _ hn
#print axioms exact_table
end P14VectorBatch
~~~
#### `asmproof/VectorEntry.lean`
~~~lean
import VectorGuard
import VectorThreshold
/-! Composition of the AVX-512 operations in a quote lane. Integer seeds
stand for arbitrary results of the floating-point instructions. The lane
uses 64-bit add/sub, checked square and threshold masks, debit repair and
the reference fallback. The batch interface requires eight readable inputs
and two disjoint, writable output arrays that do not alias those inputs. -/
namespace P14VectorEntry
open P14Quote P14Threshold P14VectorLane P14VectorGuard
set_option maxRecDepth 65000
set_option maxHeartbeats 2500000
def reference (n : Nat) : Nat×Nat :=
(lowerMicro n (floorSqrt (inputLo n)) (debit n),upperMicro n (floorSqrt (inputHi n)))
/-- The two roots and their acceptance bits arrive from the IFMA block.
The integer square, guards, comparisons, and late debit repair are explicit. -/
def finish (mem : Nat → Nat) (n jl jh tl th seed : Nat) (accepted : Bool) : Nat×Nat :=
let yl : Pair := ⟨n,0⟩
let yh : Pair := ⟨n,2^63⟩
let sl := machineSquare tl
let sh := machineSquare th
if accepted && guard yl sl tl && guard yh sh th then
let lower := if le128 sl yl then jl else subW jl 1
let upper := if le128 yh sh then jh else addW jh 1
let d := clip seed
let provisional := subW lower d
(if debitPass mem n d then provisional else subW (addW provisional d) (debit n), upper)
else reference n
theorem finish_correct {mem : Nat → Nat} (hm : tableOK mem) (n jl jh tl th seed : Nat)
(ok : Bool) (hn : 32768 ≤ n) (hu : n < word)
(cert : ok = true → tl = lowerThreshold jl ∧ th = upperThreshold jh ∧
radius ≤ tl ∧ tl+radius < word ∧ radius ≤ th ∧ th+radius < word) :
finish mem n jl jh tl th seed ok = reference n := by
unfold finish
dsimp only
split
· rename_i pass
simp only [Bool.and_eq_true] at pass
obtain ⟨⟨okp,lowG⟩,highG⟩ := pass
obtain ⟨rfl,rfl,tlo,tlh,tho,thh⟩ := cert okp
obtain ⟨jl0,jl1⟩ := vector_lower_index tlo tlh
obtain ⟨jh0,jh1⟩ := vector_upper_index tho thh
have ⟨glo,ghi⟩ := paired_guards hu (by omega : lowerThreshold jl hle (cl.mp h))]
rw [if_pos (Nat.lt_of_not_ge hle)] at lr
rw [show subW jl 1=jl-1 by unfold subW P14Vector.Word; omega]
exact lr
have hw : (if le128 ⟨n,2^63⟩ (machineSquare (upperThreshold jh)) then jh else addW jh 1) =
upperMicro n rh := by
by_cases hle : inputHi n ≤ (upperThreshold jh)^2
· rw [if_pos (ch.mpr hle)]
simpa [Nat.not_lt_of_ge hle] using hr
· rw [if_neg (fun h => hle (ch.mp h))]
rw [if_pos (Nat.lt_of_not_ge hle)] at hr
rw [show addW jh 1=jh+1 by unfold addW P14Vector.Word; omega]
exact hr
rw [lw,hw]
have hdn := debit_spec n (by omega)
have nonneg : debit n ≤ v := no_underflow hn (floorSqrt_spec _ ly) hdn
have small : v < word := by
split at lr <;> unfold word <;> omega
change (_,upperMicro n rh) = (v-debit n,upperMicro n rh)
congr 1
split
· rename_i good
have dspec := gathered_debit_correct hm (d:=clip seed) (by unfold clip; omega)
(by unfold clip; omega) hu good
rw [debit_unique dspec hdn]
unfold subW P14Vector.Word word at *
omega
· have oh : clip seed < word := by unfold clip word; omega
exact debit_repair_mod small oh nonneg
· rfl
open P14VectorThreshold
def lane (mem : Nat → Nat) (n jl jh seed : Nat) :=
finish mem n jl jh (laneInvLow jl) (laneInvHigh jh) seed
(decide (validInvLow jl ∧ validInvHigh jh))
theorem lane_correct {mem : Nat → Nat} (hm : tableOK mem) (n jl jh seed : Nat)
(hn : 32768 ≤ n) (hu : n < word) : lane mem n jl jh seed = reference n := by
apply finish_correct hm _ _ _ _ _ _ _ hn hu
intro ok
obtain ⟨low,high⟩ := of_decide_eq_true ok
obtain ⟨el,rl,cl⟩ := low_correct low
obtain ⟨eh,rh,ch⟩ := high_correct high
exact ⟨el,eh,rl,cl,rh,ch⟩
/-- Each set bit in the two fallback masks refers to its original lane:
the specification below quantifies over every lane in an eight-input batch. -/
def batch (mem : Nat → Nat) (n loHint hiHint debitHint : Fin 8 → Nat) :
Fin 8 → Nat×Nat :=
fun i => lane mem (n i) (loHint i) (hiHint i) (debitHint i)
theorem batch_correct {mem : Nat → Nat} (hm : tableOK mem)
(n loHint hiHint debitHint : Fin 8 → Nat)
(h : ∀ i, 32768 ≤ n i ∧ n i < word) :
batch mem n loHint hiHint debitHint = fun i => reference (n i) := by
funext i
exact lane_correct hm _ _ _ _ (h i).1 (h i).2
#print axioms batch_correct
#print axioms lane_correct
end P14VectorEntry
~~~
#### `asmproof/VectorGuard.lean`
~~~lean
import VectorWords
import VectorLane
/-! The unsigned 128-bit distance test in experimental/threshold8.c, per
AVX-512 lane. Every 64-bit add/sub and both carry/borrow masks are modeled. -/
namespace P14VectorGuard
open P14Vector P14Threshold
set_option maxHeartbeats 3000000
abbrev Wide : Nat := 340282366920938463463374607431768211456
structure Pair where
hi : Nat
lo : Nat
deriving Repr, DecidableEq
def fits (p : Pair) := p.hi < Word ∧ p.lo < Word
def value (p : Pair) := p.hi*Word+p.lo
def addW (x y : Nat) := (x+y)%Word
def subW (x y : Nat) := (x+Word-y)%Word
def add (a b : Pair) : Pair :=
let lo := addW a.lo b.lo
let hi := addW a.hi b.hi
⟨if lo exact ⟨addW_lt ..,addW_lt ..⟩
private theorem fit_sub (a b : Pair) : fits (sub a b) := by
unfold fits sub; dsimp only
split <;> exact ⟨subW_lt ..,subW_lt ..⟩
private theorem fit_subLow {a : Pair} (ha : fits a) (c : Nat) : fits (subLow a c) := by
unfold fits subLow; dsimp only
split
· exact ⟨subW_lt ..,subW_lt ..⟩
· exact ⟨ha.1,subW_lt ..⟩
theorem lex_correct {a b : Pair} (ha : a.lo dsimp only [Word, Wide] at * <;> omega
theorem sub_value {a b : Pair} (ha : fits a) (hb : fits b) :
value (sub a b) = (value a+Wide-value b)%Wide := by
obtain ⟨ah,al⟩ := ha
obtain ⟨bh,bl⟩ := hb
unfold value sub subW; dsimp only
split <;> dsimp only [Word, Wide] at * <;> omega
theorem subLow_value {a : Pair} (ha : fits a) (c : Nat) (hc : c>50,t<<14) and (t>>49,t<<15) respectively;
the left shift discards bits beyond its 64-bit lane. -/
def shift14 (t : Nat) : Pair := ⟨t/2^50,(t*2^14)%Word⟩
def shift15 (t : Nat) : Pair := ⟨t/2^49,(t*2^15)%Word⟩
private theorem shift14_ok {t : Nat} (h : t dsimp only [addW,Word,Half] at * <;> omega
/-- The two bit masks used to decrement jl or increment jh read the true
orders of the 128-bit square and radicand. -/
theorem square_cmp {y : Pair} {t : Nat} (hy : fits y) (ht : t
#### `asmproof/VectorLane.lean`
~~~lean
import Threshold
import DebitTable
/-! One lane of the eight-quote kernel. Each independent lane can use
either the integer endpoint certificate or the verified reference quote.
Its debit can come from a successful adjacent-table test or scalar repair. -/
namespace P14VectorLane
open P14Quote P14Threshold
abbrev clip (d : Nat) := max 17 (min d 14909)
abbrev now (d : Nat) := d-17
abbrev previous (d : Nat) := max (d-17) 1-1
def tableOK (mem : Nat → Nat) := ∀ i, i < 14893 → mem i = P14Debit.threshold (i+17)
def debitPass (mem : Nat → Nat) (n d : Nat) :=
decide (mem (now d) ≤ n ∧ (d=17 ∨ n < mem (previous d)))
theorem gathered_debit_correct {mem : Nat → Nat} (table : tableOK mem)
{n d : Nat} (dh : 17 ≤ d) (du : d ≤ 14909) (nh : n < word)
(pass : debitPass mem n d = true) : DebitSpec n d := by
have ni : now d < 14893 := by unfold now; omega
have pi : previous d < 14893 := by unfold previous; omega
have nword := table _ ni
have pword := table _ pi
unfold debitPass at pass
simp only [decide_eq_true_eq,nword,pword] at pass
obtain ⟨ok,either⟩ := pass
rw [show now d+17=d by unfold now; omega] at ok
rcases either with h | bad
· subst d
exact P14Debit.first_success ok nh
· by_cases h : d=17
· subst d
exact P14Debit.first_success ok nh
· apply P14Debit.neighbors dh ok
rw [show previous d+17=d-1 by unfold previous; omega] at bad
exact bad
/-- The vector implementation allows more candidate seeds through its
integer-index guard than the scalar one. The threshold's word bounds
imply the two neighbour indices are still admissible. -/
theorem vector_lower_index {j : Nat} (lo : radius ≤ lowerThreshold j)
(hi : lowerThreshold j+radius < word) : 0 inputLo n then 1 else 0)-d,
jh+(if th^2 < inputHi n then 1 else 0))
else (lowerMicro n (floorSqrt (inputLo n)) (debit n),upperMicro n (floorSqrt (inputHi n)))
theorem eval_correct {mem : Nat → Nat} (hm : tableOK mem) (n jl jh seed : Nat)
(hn : 32768 ≤ n) (hu : n < word) :
eval mem n jl jh seed =
(lowerMicro n (floorSqrt (inputLo n)) (debit n),upperMicro n (floorSqrt (inputHi n))) := by
obtain ⟨ly,uy⟩ := radicands_fit128 hu
unfold eval
dsimp only
split
· rename_i pass
obtain ⟨tl0,th0,tl1,th1,lb,hb⟩ := pass
obtain ⟨jl0,jl1⟩ := vector_lower_index tl0 tl1
obtain ⟨jh0,jh1⟩ := vector_upper_index th0 th1
have lo := lower_hit (floorSqrt_spec _ ly) jl0 jl1 ((wrapping_band tl0 tl1 ly).mp lb)
have hi := upper_hit (floorSqrt_spec _ uy) jh0 jh1 ((wrapping_band th0 th1 uy).mp hb)
rw [lo,hi]
split
· rename_i good
have dspec := gathered_debit_correct hm (d:=clip seed) (by unfold clip; omega)
(by unfold clip; omega) hu good
rw [debit_unique dspec (debit_spec n (by omega))]
rfl
· rfl
· rfl
#print axioms eval_correct
end P14VectorLane
~~~
#### `asmproof/VectorMasks.lean`
~~~lean
import Std
/-! The two CTZ repair loops in the eight-lane implementation.
Indices start at the least significant bit as in the x86 mask layout.
Each store updates one element of a disjoint output array. -/
namespace P14VectorMasks
abbrev Mask := Fin 256
abbrev Index := Fin 8
def bit (m : Mask) (i : Index) := m.val.testBit i.val
private def packBits : Nat → (Nat → Bool) → Nat
| 0, _ => 0
| n+1, f => (f 0).toNat+2*packBits n (fun i=>f (i+1))
private theorem pack_lt (n : Nat) (f : Nat → Bool) : packBits n f < 2^n := by
induction n generalizing f with
| zero => simp [packBits]
| succ n ih =>
have h := ih (fun i=>f (i+1))
rw [packBits,Nat.pow_succ]
cases f 0 <;> change _ + 2*packBits n (fun i=>f (i+1)) < _ <;> simp <;> omega
private theorem pack_bit (n : Nat) (f : Nat → Bool) (i : Nat) (hi : i omega
| succ n ih =>
rw [packBits]
cases i with
| zero => rw [Nat.testBit_zero]; cases f 0 <;> simp [Bool.toNat,Nat.add_mod]
| succ i =>
rw [Nat.testBit_succ]
have eq : ((f 0).toNat+2*packBits n (fun i=>f (i+1)))/2=packBits n (fun i=>f (i+1)) := by
cases f 0 <;> simp [Bool.toNat,Nat.add_mul_div_left]
rw [eq]; exact ih _ _ (by omega)
def pack (f : Index → Bool) : Mask :=
⟨packBits 8 (fun i => if h:i<8 then f ⟨i,h⟩ else false),pack_lt 8 _⟩
theorem bit_pack (f : Index → Bool) (i : Index) : bit (pack f) i = f i := by
unfold bit pack
rw [pack_bit _ _ _ i.isLt,dif_pos i.isLt]
/-- CTZ on a nonzero 8-bit mask is the least index with a set bit. -/
def ctz (m : Mask) : Index := ((List.finRange 8).find? (bit m)).getD 0
def clear (m : Mask) : Mask :=
⟨m.val &&& (m.val-1),Nat.lt_of_le_of_lt Nat.and_le_left m.isLt⟩
set_option maxRecDepth 12000 in
private theorem clear_facts : ∀ (m : Mask), m.val ≠ 0 →
(clear m).val < m.val ∧ bit m (ctz m) = true ∧ bit (clear m) (ctz m) = false ∧
∀ i, i ≠ ctz m → bit (clear m) i = bit m i := by decide +kernel
private def setEntry {A : Type} (f : Index → A → A) (m : Mask) (out : Index → A) (i : Index) :=
if i = ctz m then f i (out i) else out i
/-- The loop body uses the old value of exactly that output entry. -/
def applyMask {A : Type} (f : Index → A → A) (m : Mask) (out : Index → A) : Index → A :=
if _hp : m.val = 0 then out else
applyMask f (clear m) (setEntry f m out)
termination_by m.val
decreasing_by exact (clear_facts m _hp).1
theorem applyMask_eq {A : Type} (f : Index → A → A) (m : Mask) (out : Index → A) :
∀ i, applyMask f m out i = if bit m i then f i (out i) else out i := by
induction m,out using applyMask.induct f with
| case1 m out zero =>
rw [applyMask,dif_pos zero]
intro i
simp [bit,zero]
| case2 m out nonzero ih =>
rw [applyMask,dif_neg nonzero]
obtain ⟨_,yes,no,rest⟩ := clear_facts m nonzero
intro i
rw [ih i]
by_cases index : i=ctz m
· subst i; simp [setEntry,yes,no]
· simp [setEntry,index,rest i index]
def adjust (wrong ok : Mask) : Mask :=
⟨wrong.val &&& ok.val,Nat.lt_of_le_of_lt Nat.and_le_left wrong.isLt⟩
def missing (ok : Mask) : Mask := ⟨255 ^^^ ok.val, by
exact Nat.xor_lt_two_pow (n:=8) (by decide : 255<2^8) ok.isLt⟩
set_option maxRecDepth 12000 in
private theorem missing_bit : ∀ (ok : Mask) (i : Index),
bit (missing ok) i = !(bit ok i) := by decide +kernel
theorem two_repairs {A : Type} (wrong ok : Mask) (repair : Index → A → A) (slow : Index → A)
(out : Index → A) (i : Index) :
applyMask (fun j _ => slow j) (missing ok) (applyMask repair (adjust wrong ok) out) i =
if bit ok i then (if bit wrong i then repair i (out i) else out i) else slow i := by
rw [applyMask_eq,applyMask_eq,missing_bit]
have eq : bit (adjust wrong ok) i = (bit wrong i && bit ok i) := by
simp [bit,adjust,Nat.testBit_and]
rw [eq]
cases bit ok i <;> cases bit wrong i <;> rfl
#print axioms two_repairs
end P14VectorMasks
~~~
#### `asmproof/VectorThreshold.lean`
~~~lean
import VectorWords
import Threshold
/-! Actual 52-bit immediates and the unsigned result mask from
`experimental/threshold8.c`, projected to one lane. -/
namespace P14VectorThreshold
open P14Threshold P14Vector
set_option maxHeartbeats 3000000
set_option maxRecDepth 65536
private abbrev Pick := Nat × Nat × Nat × Nat
private def low : Pick := (0x149e90e8fc718,0x18f799840fed9,0x202350,1)
private def high : Pick := (0xa236f864225f,0x18f799840b7df,0x202350,0)
private def c1 (j : Nat) (p : Pick) := j*p.1/Limb + j*p.2.1%Limb
private def c2 (j : Nat) (p : Pick) := c1 j p/Limb + j*p.2.1/Limb + j*p.2.2.1%Limb
private def c3 (j : Nat) (p : Pick) := c2 j p/Limb + j*p.2.2.1/Limb
private def lane (j : Nat) (p : Pick) :=
((c3 j p * 2^44)%Word + ((c2 j p)%Limb)/256 + p.2.2.2)%Word
private def valid (j : Nat) (p : Pick) :=
j
#### `asmproof/VectorWords.lean`
~~~lean
import Std
/-! Arithmetic of one AVX-512 IFMA lane in `experimental/threshold8.c`.
The lane's inputs to VPMADD52 are 52-bit nonnegative integers. -/
namespace P14Vector
abbrev Limb : Nat := 4503599627370496
abbrev Half : Nat := 4294967296
abbrev Word : Nat := 18446744073709551616
set_option maxHeartbeats 3000000
/-- IFMA extracts the low or high 52-bit word of each single limb product.
Carrying those products yields the top of the exact fixed-point product. -/
theorem carry52 (p0 p1 p2 : Nat) :
let c1:=p0/Limb + p1%Limb
let c2:=c1/Limb + p1/Limb + p2%Limb
let c3:=c2/Limb + p2/Limb
c3*2^44 + (c2%Limb)/256 = (p0 + Limb*p1 + (Limb*Limb)*p2)/2^112 := by
dsimp [Limb]; omega
theorem ifma_inverse (j a b c : Nat) :
let c1:=(j*a)/Limb + (j*b)%Limb
let c2:=c1/Limb + (j*b)/Limb + (j*c)%Limb
let c3:=c2/Limb + (j*c)/Limb
c3*2^44 + (c2%Limb)/256 = j*(a+Limb*b+Limb^2*c)/2^112 := by
dsimp only
rw [carry52 (j*a) (j*b) (j*c)]
congr 1
simp only [Nat.mul_add,Nat.pow_succ,Nat.pow_zero,Nat.one_mul]
ac_rfl
theorem limbs_fit {j a b c : Nat} (hj:j z*z) rep
_ = _ := by
simp only [Nat.add_mul,Nat.mul_add]
change _ = x*x + ((Half+Half)*(x*y)) + (Half*Half)*(y*y)
rw [Nat.add_mul]; ac_rfl
simpa only [←sq] using square_parts (x*x) (x*y) (y*y)
#print axioms ifma_inverse
#print axioms square_lane
end P14Vector
~~~
#### `asmproof/X86Debit.lean`
~~~lean
import DebitTable
/-! A small-step model of the instructions used by p14_debit_correct.
PC values are byte offsets from the symbol. The ELF checker matches every
opcode, both memory addressing modes, all jump displacements and the RIP
displacement. RCX is represented by a tag since the sole write to it is a
LEA of the checked table base. RDI and ESI are read-only parameters. RET
ends the modeled call. Only flags read before the next overwrite are kept.
The memory parameter is the little-endian UInt64 word at the computed
table index. The proof below checks that every live access is in range. -/
namespace P14Debit.X86
set_option maxRecDepth 65536
set_option maxHeartbeats 4000000
open P14Quote P14Debit
attribute [local irreducible] threshold
structure State where
pc : Nat
ax : Nat := 0
dx : Nat := 0
cf : Bool := false
zf : Bool := false
ptr : Bool := false
deriving DecidableEq, Repr
abbrev Table := Nat → Nat
def tableOK (mem : Table) := ∀ i, 17 ≤ i → i ≤ 14909 → mem i = threshold i
/-- The EAX writes zero-extend to RAX. Input ESI is the low 32 bits. -/
def step (n hint : Nat) (mem : Table) (s : State) : State :=
match s.pc with
| 0 => {s with ax := 17, pc := 5}
| 5 => {s with cf := decide (hint < s.ax), zf := decide (hint = s.ax), pc := 7}
| 7 => {s with ax := if !s.cf then hint else s.ax, pc := 10}
| 10 => {s with dx := 14909, pc := 15}
| 15 => {s with cf := decide (s.ax < s.dx), zf := decide (s.ax = s.dx), pc := 17}
| 17 => {s with ax := if !s.cf && !s.zf then s.dx else s.ax, pc := 20}
| 20 => {s with ptr := true, pc := 27}
| 27 | 35 => if s.ptr then
{s with cf := decide (n < mem s.ax), zf := decide (n = mem s.ax), pc := s.pc+4}
else {s with pc := 255}
| 31 => {s with pc := if s.cf then 33 else 42}
| 33 => {s with ax := (s.ax+1)%2^32, pc := 35}
| 39 => {s with pc := if s.cf then 33 else 41}
| 42 => {s with cf := decide (s.ax<17), zf := decide (s.ax=17), pc := 45}
| 45 => {s with pc := if s.zf then 58 else 47}
| 47 => if s.ptr then
{s with cf := decide (n < mem (s.ax-1)), zf := decide (n = mem (s.ax-1)), pc := 52}
else {s with pc := 255}
| 52 => {s with pc := if s.cf then 58 else 54}
| 54 => {s with ax := (s.ax+2^32-1)%2^32, pc := 56}
| 56 => {s with pc := 42}
| _ => s
inductive Reaches (f : State → State) : State → State → Prop
| refl (s) : Reaches f s s
| next {s t} : Reaches f (f s) t → Reaches f s t
theorem Reaches.trans {f : State → State} {a b c : State}
(h : Reaches f a b) (k : Reaches f b c) : Reaches f a c := by
induction h with
| refl => exact k
| next _ ih => exact .next (ih k)
def run (f : State → State) (k : Nat) (s : State) : State :=
match k with
| 0 => s
| k+1 => run f k (f s)
theorem steps (f : State → State) (k : Nat) (s : State) : Reaches f s (run f k s) := by
induction k generalizing s with
| zero => exact .refl _
| succ k ih => exact .next (ih _)
/-- PCs 41 and 58 both point at a RET. -/
def success (n : Nat) (s : State) :=
(s.pc = 41 ∨ s.pc = 58) ∧ DebitSpec n s.ax
private theorem up {n hint : Nat} {m : Table} (hm : tableOK m) (hn : 32768 ≤ n)
(s : State) (hp : s.pc = 33) (ptr : s.ptr = true) (hl : 17 ≤ s.ax)
(hu : s.ax ≤ 14909) (fail : n < threshold s.ax) :
∃ t, Reaches (step n hint m) s t ∧ success n t := by
have lt : s.ax < 14909 := by
have := last_fits hn
apply Classical.byContradiction
intro hb
have eq : s.ax = 14909 := by omega
rw [eq] at fail
omega
have fit : s.ax+1 < 2^32 := by omega
let v := run (step n hint m) 3 s
have vv : v.ax = s.ax+1 ∧ v.ptr=true ∧
v.pc=(if n < threshold (s.ax+1) then 33 else 41) := by
simp [v,run,step,hp,ptr,Nat.mod_eq_of_lt fit,hm (s.ax+1) (by omega) (by omega)]
have r := steps (step n hint m) 3 s
change Reaches _ s v at r
by_cases bad : n < threshold (s.ax+1)
· have vp : v.pc=33 := by simp [bad] at vv; exact vv.2.2
obtain ⟨t,ht,hs⟩ := up hm hn v vp vv.2.1 (by omega) (by omega) (by rwa [vv.1])
exact ⟨t,r.trans ht,hs⟩
· refine ⟨v,r,Or.inl (by simpa [bad] using vv.2.2),?_⟩
rw [vv.1]
apply neighbors (by omega) (by omega)
simpa using fail
termination_by 14909-s.ax
decreasing_by change 14909-v.ax < 14909-s.ax; rw [vv.1]; omega
private theorem pred_word (a : Nat) (l : 17 < a) (h : a ≤14909) :
(a+2^32-1)%2^32 = a-1 := by omega
private theorem downBack {n hint : Nat} {m : Table} (v : State) (vp : v.pc=54)
(pv : v.ptr=true) (lo : 17 < v.ax) (hi : v.ax ≤ 14909) :
∃ w, Reaches (step n hint m) v w ∧ w.pc=42 ∧ w.ptr=true ∧ w.ax=v.ax-1 := by
let a : State := {v with ax := (v.ax+2^32-1)%2^32, pc := 56}
let w : State := {a with pc := 42}
have one : step n hint m v = a := by unfold step; rw [vp]
have two : step n hint m a = w := rfl
have fromA : Reaches (step n hint m) a w := .next (two.symm ▸ Reaches.refl _)
have fromV : Reaches (step n hint m) v w := .next (one.symm ▸ fromA)
exact ⟨w,fromV,rfl,pv,pred_word v.ax lo hi⟩
private theorem downOne {n hint : Nat} {m : Table} (hm : tableOK m) (hn : n < 2^64)
(s : State) (hp : s.pc = 42) (ptr : s.ptr=true) (hl : 17 ≤ s.ax)
(hu : s.ax ≤ 14909) (yes : threshold s.ax ≤ n) :
(∃ t, Reaches (step n hint m) s t ∧ success n t) ∨
∃ w, Reaches (step n hint m) s w ∧ w.pc=42 ∧ w.ptr=true ∧
17 ≤ w.ax ∧ w.ax < s.ax ∧ threshold w.ax ≤ n := by
by_cases endp : s.ax=17
· let v := run (step n hint m) 2 s
have vv : v.pc=58 ∧ v.ax=17 := by simp [v,run,step,hp,endp]
refine Or.inl ⟨v,steps _ 2 _,Or.inr vv.1,?_⟩
rw [vv.2]
rw [endp] at yes
exact first_success yes hn
· have lt : 17 ≤ s.ax-1 := by omega
let v := run (step n hint m) 4 s
have vv : v.ax=s.ax ∧ v.ptr=true ∧
v.pc=(if n < threshold (s.ax-1) then 58 else 54) := by
simp [v,run,step,hp,ptr,endp,hm (s.ax-1) lt (by omega)]
have r := steps (step n hint m) 4 s
change Reaches _ s v at r
by_cases fail : n < threshold (s.ax-1)
· refine Or.inl ⟨v,r,Or.inr (by simpa [fail] using vv.2.2),?_⟩
rw [vv.1]; exact neighbors hl yes fail
· have vp : v.pc=54 := by simpa [fail] using vv.2.2
obtain ⟨w,wr,wp,wpPtr,wpAx⟩ := downBack (n:=n) (hint:=hint) (m:=m)
v vp vv.2.1 (by rw [vv.1]; omega) (by rw [vv.1]; exact hu)
rw [vv.1] at wpAx
have dec : s.ax-1 < s.ax := by omega
have predOK : threshold (s.ax-1) ≤ n := Nat.le_of_not_lt fail
exact Or.inr ⟨w,r.trans wr,wp,wpPtr,wpAx ▸ lt,wpAx ▸ dec,wpAx ▸ predOK⟩
private theorem down {n hint : Nat} {m : Table} (hm : tableOK m) (hn : n < 2^64)
(s : State) (hp : s.pc = 42) (ptr : s.ptr=true) (hl : 17 ≤ s.ax)
(hu : s.ax ≤ 14909) (yes : threshold s.ax ≤ n) :
∃ t, Reaches (step n hint m) s t ∧ success n t := by
rcases downOne (hint:=hint) hm hn s hp ptr hl hu yes with goal | ⟨w,reach,atPc,atPtr,low,decr,ok⟩
· exact goal
· obtain ⟨t,h,fin⟩ := down hm hn w atPc atPtr low (by omega) ok
exact ⟨t,reach.trans h,fin⟩
termination_by s.ax
decreasing_by assumption
theorem correct {n hint : Nat} {mem : Table} (hm : tableOK mem)
(hl : 32768 ≤ n) (hu : n < 2^64) (s : State) (start : s.pc=0) :
∃ t, Reaches (step n hint mem) s t ∧ success n t := by
let a := if hint<17 then 17 else hint
let d := if 14909 < a then 14909 else a
let v := run (step n hint mem) 7 s
have vx : v.ax=d ∧ v.ptr=true ∧ v.pc=27 := by
by_cases h : hint<17
· simp [v,d,a,run,step,start,h]
· by_cases u : hint<14909
· have u' : ¬14909 omega
have dl : 17 ≤ d := by dsimp [d]; split <;> omega
have du : d ≤ 14909 := by dsimp [d]; split <;> omega
let w := run (step n hint mem) 2 v
have wx : w.ax=d ∧ w.ptr=true ∧ w.pc=(if n
#### `asmproof/X86Root.lean`
~~~lean
import Std
/-! A byte decoder and small-step unsigned x86-64 model for p14_root_repair.
We track the touched general-purpose registers and the two flags read by this
code. Code addresses are relative to the symbol. The return observation is
made at its RET (under the ABI, RET returns to the valid caller's stack address).
No floating-point instruction or assumed quality of the input seed enters here. -/
namespace Problem14.X86Root
set_option maxRecDepth 16384
def W : Nat := 18446744073709551616
-- Machine-code bytes of the complete function, in address order.
def bytes : List Nat := [
72,137,209,72,137,200,72,247,225,72,57,199,73,137,240,73,
25,208,115,5,72,255,201,235,234,72,57,199,117,5,72,57,
214,116,30,72,131,193,1,114,17,72,137,200,72,247,225,72,
57,199,73,137,240,73,25,208,115,223,72,141,65,255,49,210,
195,72,137,200,186,1,0,0,0,195]
inductive Reg where
| ax | cx | dx | di | si | r8
deriving DecidableEq, Repr
open Reg
inductive Cond where | always | carry | noCarry | equal | unequal
deriving DecidableEq, Repr
inductive Op where
| mov (dst src : Reg) | mul (src : Reg) | cmp (left right : Reg)
| sbb (dst src : Reg) | dec (dst : Reg) | incByAdd (dst : Reg)
| jm (cond : Cond) (target : Nat) | leaMinusOne (dst src : Reg)
| xorSelf32 (dst : Reg) | one32 (dst : Reg) | ret
deriving DecidableEq, Repr
private def rel8 (next b : Nat) :=
if b < 128 then next + b else next + b - 256
/-- Decode only the x86 forms used in this function; other bytes give none.
REX.W selects a 64-bit operand; REX.B selects r8 in the two r/m destinations.
Branches use the signed 8-bit displacement relative to the following IP. -/
def decode (ip : Nat) : List Nat → Option (Op × Nat)
| 0x48::0x89::0xd1::_ => some (.mov cx dx, ip+3)
| 0x48::0x89::0xc8::_ => some (.mov ax cx, ip+3)
| 0x48::0xf7::0xe1::_ => some (.mul cx, ip+3)
| 0x48::0x39::0xc7::_ => some (.cmp di ax, ip+3)
| 0x48::0x39::0xd6::_ => some (.cmp si dx, ip+3)
| 0x49::0x89::0xf0::_ => some (.mov r8 si, ip+3)
| 0x49::0x19::0xd0::_ => some (.sbb r8 dx, ip+3)
| 0x48::0xff::0xc9::_ => some (.dec cx, ip+3)
| 0x48::0x83::0xc1::1::_ => some (.incByAdd cx, ip+4)
| 0x48::0x8d::0x41::0xff::_ => some (.leaMinusOne ax cx, ip+4)
| 0x31::0xd2::_ => some (.xorSelf32 dx, ip+2)
| 0xba::1::0::0::0::_ => some (.one32 dx, ip+5)
| 0x73::b::_ => some (.jm .noCarry (rel8 (ip+2) b), ip+2)
| 0x72::b::_ => some (.jm .carry (rel8 (ip+2) b), ip+2)
| 0x75::b::_ => some (.jm .unequal (rel8 (ip+2) b), ip+2)
| 0x74::b::_ => some (.jm .equal (rel8 (ip+2) b), ip+2)
| 0xeb::b::_ => some (.jm .always (rel8 (ip+2) b), ip+2)
| 0xc3::_ => some (.ret, ip+1)
| _ => none
def fetch (ip : Nat) := decode ip (bytes.drop ip)
structure CPU where
ip : Nat
reg : Reg → Nat
cf : Bool
zf : Bool
private def wr (s : CPU) (r : Reg) (v : Nat) :=
{s with reg := fun k => if k = r then v else s.reg k}
private def testFlag (s : CPU) : Cond → Bool
| .always => true | .carry => s.cf | .noCarry => !s.cf
| .equal => s.zf | .unequal => !s.zf
/-- next is the fallthrough address. The operand values entering a routine
are words. MUL's undefined ZF is irrelevant here (overwritten before use). -/
def exec (s : CPU) (next : Nat) (op : Op) : CPU :=
let z := {s with ip := next}
match op with
| .mov dst src => wr z dst (s.reg src)
| .mul src =>
let p := s.reg ax * s.reg src
wr (wr {z with cf := decide (p/W ≠ 0)} ax (p%W)) dx (p/W)
| .cmp a b => {z with cf := decide (s.reg a < s.reg b), zf := decide (s.reg a = s.reg b)}
| .sbb d v =>
let y := s.reg v + s.cf.toNat
let x := (s.reg d + W - y) % W
wr {z with cf := decide (s.reg d < y), zf := decide (x = 0)} d x
| .dec d =>
let x := (s.reg d + W - 1) % W
wr {z with zf := decide (x = 0)} d x
| .incByAdd d =>
let x := (s.reg d + 1) % W
wr {z with cf := decide (W ≤ s.reg d + 1), zf := decide (x = 0)} d x
| .jm c tgt => {s with ip := if testFlag s c then tgt else next}
| .leaMinusOne dst src => wr z dst ((s.reg src + W - 1) % W)
| .xorSelf32 d => wr {z with cf := false, zf := true} d 0
| .one32 d => wr z d 1
| .ret => s -- observed at RET, never stepped past by the proof below
/-- A finite trace to the actual decoded RET and its output predicate. -/
inductive Returns (post : CPU → Prop) : CPU → Prop where
| atRet {s next} : fetch s.ip = some (.ret,next) → post s → Returns post s
| step {s op next} : fetch s.ip = some (op,next) → op ≠ .ret →
Returns post (exec s next op) → Returns post s
/-- A small straight-line/branch block extracted from the decoded bytes. -/
inductive Steps : CPU → CPU → Prop where
| refl (s) : Steps s s
| cons {s u op next} : fetch s.ip = some (op,next) → op ≠ .ret →
Steps (exec s next op) u → Steps s u
private theorem prepend (p : Steps s t) (q : Returns post t) : Returns post s := by
induction p with
| refl => exact q
| cons h hn _ ih => exact .step h hn (ih q)
private theorem square_compare (r lo hi : Nat) (hl : lo s
| (op,k)::rest => walk (exec s k op) rest
private def legal (s : CPU) : List (Op × Nat) → Prop
| [] => True
| (op,k)::rest => fetch s.ip = some (op,k) ∧ op ≠ .ret ∧ legal (exec s k op) rest
private theorem walkSteps (s : CPU) (xs : List (Op × Nat)) (h : legal s xs) :
Steps s (walk s xs) := by
induction xs generalizing s with
| nil => exact .refl _
| cons a rest ih => rcases a with ⟨o,k⟩; exact .cons h.1 h.2.1 (ih _ h.2.2)
-- Each decoded instruction here is checked against the actual byte list.
@[simp] private theorem pc0 : fetch 0 = some (.mov cx dx, 3) := by decide
@[simp] private theorem pc3 : fetch 3 = some (.mov ax cx, 6) := by decide
@[simp] private theorem pc6 : fetch 6 = some (.mul cx, 9) := by decide
@[simp] private theorem pc9 : fetch 9 = some (.cmp di ax, 12) := by decide
@[simp] private theorem pc12 : fetch 12 = some (.mov r8 si, 15) := by decide
@[simp] private theorem pc15 : fetch 15 = some (.sbb r8 dx, 18) := by decide
@[simp] private theorem pc18 : fetch 18 = some (.jm .noCarry 25, 20) := by decide
@[simp] private theorem pc20 : fetch 20 = some (.dec cx, 23) := by decide
@[simp] private theorem pc23 : fetch 23 = some (.jm .always 3, 25) := by decide
@[simp] private theorem pc25 : fetch 25 = some (.cmp di ax, 28) := by decide
@[simp] private theorem pc28 : fetch 28 = some (.jm .unequal 35, 30) := by decide
@[simp] private theorem pc30 : fetch 30 = some (.cmp si dx, 33) := by decide
@[simp] private theorem pc33 : fetch 33 = some (.jm .equal 65, 35) := by decide
@[simp] private theorem pc35 : fetch 35 = some (.incByAdd cx, 39) := by decide
@[simp] private theorem pc39 : fetch 39 = some (.jm .carry 58, 41) := by decide
@[simp] private theorem pc41 : fetch 41 = some (.mov ax cx, 44) := by decide
@[simp] private theorem pc44 : fetch 44 = some (.mul cx, 47) := by decide
@[simp] private theorem pc47 : fetch 47 = some (.cmp di ax, 50) := by decide
@[simp] private theorem pc50 : fetch 50 = some (.mov r8 si, 53) := by decide
@[simp] private theorem pc53 : fetch 53 = some (.sbb r8 dx, 56) := by decide
@[simp] private theorem pc56 : fetch 56 = some (.jm .noCarry 25, 58) := by decide
@[simp] private theorem pc58 : fetch 58 = some (.leaMinusOne ax cx, 62) := by decide
@[simp] private theorem pc62 : fetch 62 = some (.xorSelf32 dx, 64) := by decide
@[simp] private theorem pc64 : fetch 64 = some (.ret, 65) := by decide
@[simp] private theorem pc65 : fetch 65 = some (.mov ax cx, 68) := by decide
@[simp] private theorem pc68 : fetch 68 = some (.one32 dx, 73) := by decide
@[simp] private theorem pc73 : fetch 73 = some (.ret, 74) := by decide
private def cmpBlock (a : Nat) : List (Op × Nat) := [
(.mov ax cx,a+3),(.mul cx,a+6),(.cmp di ax,a+9),
(.mov r8 si,a+12),(.sbb r8 dx,a+15),(.jm .noCarry 25,a+17)]
private theorem checked (s : CPU) (lo hi r a : Nat) (h : Input s lo hi r a)
(origin : a=3 ∨ a=41) (hl : lo
simp (config := {decide := true}) [cmpBlock,legal,exec,wr,ip]
· by_cases low : r*r ≤ hi*W+lo
· have noCarry : ¬ hi < r*r/W + (decide (lo < r*r%W)).toNat :=
fun hh => (Nat.not_lt_of_ge low) ((square_compare _ _ _ hl).mp hh)
simp [low, Good,Input,walk,cmpBlock,exec,wr,testFlag,cxv,di,si,noCarry]
· have carry : hi < r*r/W + (decide (lo < r*r%W)).toNat :=
(square_compare _ _ _ hl).mpr (by omega)
simp [low, Input,walk,cmpBlock,exec,wr,testFlag,cxv,di,si,carry]
private theorem sq_strict (r : Nat) : r*r < (r+1)*(r+1) := by
simp only [Nat.add_mul,Nat.mul_add,Nat.one_mul,Nat.mul_one]; omega
/-- The exact-square shortcut returns the current candidate. -/
private theorem return_exact (s : CPU) (lo hi r : Nat) (h : Good s lo hi r)
(hr : r ne ((square_eq r lo hi hl).mp ⟨elo,hh⟩).symm
let code : List (Op × Nat) := [(.cmp .di ax,28),(.jm .unequal 35,30),
(.cmp .si dx,33),(.jm .equal 65,35)]
exact ⟨_,walkSteps s code (by simp [legal,code,exec,wr,testFlag,ip,di,si,axv,dxv,elo,ehi]),
by simp [Input,walk,code,exec,wr,testFlag,di,si,cxv,axv,dxv,elo,ehi]⟩
· let code : List (Op × Nat) := [(.cmp .di ax,28),(.jm .unequal 35,30)]
exact ⟨_,walkSteps s code (by simp [legal,code,exec,ip]),
by simp [Input,walk,code,exec,testFlag,di,si,cxv,axv,elo]⟩
private theorem incremented (s : CPU) (lo hi r : Nat) (h : Input s lo hi r 35) :
∃ t, Steps s t ∧ Input t lo hi ((r+1)%W) (if W≤r+1 then 58 else 41) := by
obtain ⟨ip,di,si,cxv⟩ := h
let code : List (Op × Nat) := [(.incByAdd cx,39),(.jm .carry 58,41)]
exact ⟨_,walkSteps s code (by simp [legal,code,exec,wr,ip]),
by simp [Input,walk,code,exec,wr,testFlag,di,si,cxv]⟩
private theorem word_dec (a : Nat) (pos : 0 exact .atRet hret (f _ hp)
| step inst notRet _ ih => exact .step inst notRet ih
#print axioms root_repair_correct
end Problem14.X86Root
~~~
#### `asmproof/X86RootQuote.lean`
~~~lean
import Quote
import X86Root
/-! The decoded square-root routine implements the quote's mathematical root. -/
namespace Problem14.X86Root
open P14Quote
theorem root_repair_quote (s : CPU) (lo hi hint : Nat) (ip : s.ip=0)
(di : s.reg .di=lo) (si : s.reg .si=hi) (seed : s.reg .dx=hint)
(hl : lo
out.reg .ax = floorSqrt y ∧
out.reg .dx = (if (floorSqrt y)^2 = y then 1 else 0) ∧
out.reg .ax + (1-out.reg .dx) = ceilRoot y (floorSqrt y)) s := by
dsimp only
apply (root_repair_correct s lo hi hint ip di si seed hl hh hs).weaken
intro t cert
obtain ⟨_,lower,upper,flag⟩ := cert
have range : hi*W+lo < 2^128 := by dsimp [W] at *; omega
have spec : SqrtSpec (hi*W+lo) (t.reg .ax) := by
simpa [SqrtSpec,Nat.pow_succ] using And.intro lower upper
have eqroot := sqrt_unique spec (floorSqrt_spec _ range)
rw [eqroot] at flag lower ⊢
refine ⟨rfl,by simpa [Nat.pow_succ] using flag,?_⟩
rw [flag]
unfold ceilRoot
by_cases h : floorSqrt (hi*W+lo)*floorSqrt (hi*W+lo)=hi*W+lo
· simp [h,Nat.pow_succ]
· have hlt : floorSqrt (hi*W+lo)*floorSqrt (hi*W+lo)
#### `asmproof/linked-release/LinkedDebit.lean`
~~~lean
import DebitBytes
namespace P14LinkedDebit
open P14Debit
set_option maxRecDepth 8192
private theorem join {s m n : Nat} {a b : List Nat}
(ha : (List.range' s m).map threshold = a)
(hb : (List.range' (s+m) n).map threshold = b) :
(List.range' s (m+n)).map threshold = a++b := by
rw [← List.range'_append_1, List.map_append, ha, hb]
private def words17 : List Nat := [16995276445797006318, 12770570960399414046, 9745515921818957966, 7540894446406250000, 5908488117335981652, 4682302156712004272, 3749157282093263209, 3030516350954157825, 2471000292198400000, 2030982120968143757, 1681721278735725306, 1402111926281878458, 1176475400207955195, 993039597880658436, 842877325579791032, 719155735626816750, 616599460966189863, 531102388931156447, 459444036004045933, 399080342512481689, 347987961351844978, 304547372556842436, 267454435683047738, 235652951450195312, 208282871527092451, 184640253666749427, 164146097571416357, 146321942397250133, 130770646634490000, 117161165065414475, 105216427181691381, 94703635967317432, 85426465907814812, 77218759131200000, 69939409241962989, 63468191280254492, 57702348859364680, 52553789960491416, 47946774084730924, 43815997696308702, 40105003793493654, 36764856256498600, 33753031282127396, 31032487433770576, 28570883154388809, 26339916424368470, 24314765914962887, 22473616738338023, 20797256918713792, 19268733155193433, 17873056432613989, 16596949654098639, 15428630790507256, 14357626125126435, 13374609062381892, 12471260703515053, 11640148999186059, 10874623792245156, 10168725482297942, 9517105392401326, 8914956209602198, 8357951115095242, 7842190424700110, 7364154732818604]
private theorem words17_eq : (List.range' 17 64).map threshold = words17 := by decide
private def words81 : List Nat := [6920663698500927, 6508839735221639, 6126075970143271, 5770007927085920, 5438488462655042, 5129565549106761, 4841462552296112, 4572560699914067, 4321383475389286, 4086582707327812, 3866926154041804, 3661286408294202, 3468630969464161, 3288013349427856, 3118565094982067, 2959488623978670, 2810050784796800, 2669577059619213, 2537446341424650, 2413086222850000, 2295968742278348, 2185606538811343, 2081549373306812, 1983380977507953, 1890716197547514, 1803198401855146, 1720497126794498, 1642305936265357, 1568340474074339, 1498336690147841, 1432049223670144, 1369249928009647, 1309726523875216, 1253281368546677, 1199730330269844, 1148901758015581, 1100635537790320, 1054782227566481, 1011202263687571, 969765232305331, 930349200034673, 892840098574650, 857131158547706, 823122388261515, 790720093503488, 759836434842590, 730389019240982, 702300523073063, 675498343915294, 649914278709806, 625484226121029, 602147911099795, 579848629845836, 558533013519187, 538150809195432, 518654676690582, 500000000000000, 482144712203352, 465049132785280, 448675816410201, 432989412270335, 417956533199434, 403545633811529, 389726896984845]
private theorem words81_eq : (List.range' 81 64).map threshold = words81 := by decide
private def words145 : List Nat := [376472128066546, 363754656224564, 351549242418991, 339831993507661, 328580282039172, 317772671321811, 307388845389137, 297409543512541, 287816498938119, 278592381550069, 269720744185533, 261185972346726, 252973237075342, 245068450771878, 237458225758702, 230129835400581, 223071177610119, 216270740578154, 209717570580822, 203401241725676, 197311827509181, 191439874066977, 185776375006770, 180312747721435, 175040811087148, 169952764457970, 165041167874459, 160298923409586, 155719257580457, 151295704759253, 147022091521295, 142892521872315, 138901363300936, 135043233605915, 131312988451082, 127705709603994, 124216693817215, 120841442313806, 117575650841106, 114415200259194, 111356147632590, 108394717795755, 105527295364804, 102750417169620, 100060765082152, 97455159218190, 94930551491358, 92484019499333, 90112760723567, 87814087024900, 85585419418575, 83424283113100, 81328302798397, 79295198169520, 77322779673053, 75408944464062, 73551672562197, 71749023196198, 69999131326706, 68300204337854, 66650518888670, 65048417915838, 63492307779865, 61980655547124]
private theorem words145_eq : (List.range' 145 64).map threshold = words145 := by decide
private def words209 : List Nat := [60511986400699, 59084881173360, 57697973996338, 56349950057973, 55039543466592, 53765535212328, 52526751222853, 51322060508292, 50150373390837, 49010639814823, 47901847733276, 46823021567120, 45773220733483, 44751538239692, 43757099339759, 42789060250301, 41846606923037, 40928953871101, 40035343046620, 39165042767084, 38317346688184, 37491572820933, 36687062590956, 35903179937987, 35139310453680, 34394860555947, 33669256698141, 32961944611453, 32272388579013, 31600070740237, 30944490424028, 30305163509542, 29681621813241, 29073412501084, 28480097524695, 27901253080458, 27336469090501, 26785348704616, 26247507822175, 25722574633172, 25210189177544, 24710002921984, 24221678353475, 23744888588831, 23279316999542, 22824656851281, 22380610957428, 21946891346033, 21523218939627, 21109323247353, 20704942068891, 20309821209681, 19923714206980, 19546382066282, 19177593007700, 18817122221869, 18464751634997, 18120269682682, 17783471092137, 17454156672475, 17132133112739, 16817212787357, 16509213568716, 16207958646581]
private theorem words209_eq : (List.range' 209 64).map threshold = words209 := by decide
private def words273 : List Nat := [15913276354081, 15625000000000, 15342967707114, 15067022256355, 14797010936551, 14532785399540, 14274201520429, 14021119262819, 13773402548787, 13530919133448, 13293540483912, 13061141662482, 12833601213918, 12610801056610, 12392626377527, 12178965530776, 11969709939661, 11764754002080, 11563994999164, 11367333007018, 11174670811451, 10985913825593, 10800970010281, 10619749797114, 10442166014093, 10268133813724, 10097570603521, 9930395978807, 9766531657727, 9605901418411, 9448431038183, 9294048234767, 9142682609404, 8994265591816, 8848730386949, 8706011923440, 8566046803732, 8428773255798, 8294131086399, 8162061635835, 8032507734130, 7905413658604, 7780725092788, 7658389086621, 7538354017905, 7420569554959, 7304986620437, 7191557356268, 7080235089689, 6970974300316, 6863730588235, 6758460643067, 6655122213988, 6553674080651, 6454076024997, 6356288803927, 6260274122788, 6165994609662, 6073413790433, 5982496064593, 5893206681770, 5805511718962, 5719378058436, 5634773366295]
private theorem words273_eq : (List.range' 273 64).map threshold = words273 := by decide
private def words337 : List Nat := [5551666071658, 5470025346473, 5389821085906, 5311023889312, 5233605041756, 5157536496077, 5082790855466, 5009341356550, 4937161852962, 4866226799389, 4796511236067, 4727990773727, 4660641578967, 4594440360040, 4529364353047, 4465391308510, 4402499478339, 4340667603154, 4279874899962, 4220101050185, 4161326188015, 4103530889096, 4046696159521, 3990803425125, 3935834521083, 3881771681788, 3828597531007, 3776295072306, 3724847679740, 3674239088785, 3624453387530, 3575475008100, 3527288718303, 3479879613518, 3433233108786, 3387334931117, 3342171112008, 3297727980150, 3253992154335, 3210950536551, 3168590305252, 3126898908817, 3085864059169, 3045473725568, 3005716128564, 2966579734105, 2928053247805, 2890125609354, 2852785987073, 2816023772611, 2779828575783, 2744190219528, 2709098735009, 2674544356830, 2640517518379, 2607008847284, 2574009160992, 2541509462450, 2509500935904, 2477974942798, 2446923017774, 2416336864783, 2386208353275, 2356529514502]
private theorem words337_eq : (List.range' 337 64).map threshold = words337 := by decide
private def words401 : List Nat := [2327292537900, 2298489767569, 2270113698830, 2242156974881, 2214612383520, 2187472853960, 2160731453712, 2134381385558, 2108415984579, 2082828715271, 2057613168724, 2032763059870, 2008272224795, 1984134618121, 1960344310446, 1936895485848, 1913782439446, 1890999575022, 1868541402698, 1846402536667, 1824577692981, 1803061687386, 1781849433211, 1760935939312, 1740316308050, 1719985733331, 1699939498684, 1680172975385, 1660681620624, 1641460975714, 1622506664348, 1603814390884, 1585379938681, 1567199168464, 1549268016735, 1531582494213, 1514138684315, 1496932741665, 1479960890645, 1463219423973, 1446704701313, 1430413147921, 1414341253318, 1398485569990, 1382842712125, 1367409354367, 1352182230614, 1337158132822, 1322333909854, 1307706466345, 1293272761592, 1279029808472, 1264974672383, 1251104470207, 1237416369293, 1223907586471, 1210575387077, 1197417084006, 1184430036782, 1171611650654, 1158959375701, 1146470705967, 1134143178609, 1121974373062]
private theorem words401_eq : (List.range' 401 64).map threshold = words401 := by decide
private def words465 : List Nat := [1109961910229, 1098103451677, 1086396698866, 1074839392373, 1063429311157, 1052164271817, 1041042127882, 1030060769108, 1019218120790, 1008512143094, 997940830394, 987502210632, 977194344686, 967015325751, 956963278736, 947036359673, 937232755134, 927550681664, 917988385227, 908544140659, 899216251135, 890003047647, 880902888490, 871914158764, 863035269880, 854264659078, 845600788959, 837042147019, 828587245200, 820234619443, 811982829256, 803830457287, 795776108906, 787818411798, 779956015561, 772187591312, 764511831304, 756927448546, 749433176438, 742027768401, 734709997529, 727478656236, 720332555914, 713270526603, 706291416655, 699394092420, 692577437924, 685840354564, 679181760800, 672600591863, 666095799458, 659666351480, 653311231732, 647029439653, 640819990043, 634681912803, 628614252670, 622616068968, 616686435353, 610824439571, 605029183215, 599299781491, 593635362984, 588035069433]
private theorem words465_eq : (List.range' 465 64).map threshold = words465 := by decide
private def words529 : List Nat := [582498055510, 577023488594, 571610548564, 566258427584, 560966329899, 555733471629, 550559080574, 545442396015, 540382668523, 535379159773, 530431142357, 525537899605, 520698725403, 515912924022, 511179809947, 506498707706, 501868951704, 497289886065, 492760864470, 488281250000, 483850414984, 479467740847, 475132617964, 470844445511, 466602631326, 462406591767, 458255751574, 454149543736, 450087409353, 446068797513, 442093165159, 438159976963, 434268705205, 430418829650, 426609837428, 422841222920, 419112487640, 415423140122, 411772695811, 408160676953, 404586612485, 401050037935, 397550495315, 394087533019, 390660705726, 387269574298, 383913705686, 380592672837, 377306054595, 374053435614, 370834406270, 367648562565, 364495506048, 361374843724, 358286187974, 355229156469, 352203372093, 349208462858, 346244061830, 343309807050, 340405341458, 337530312821, 334684373656, 331867181160]
private theorem words529_eq : (List.range' 529 64).map threshold = words529 := by decide
private def words593 : List Nat := [329078397139, 326317687940, 323584724380, 320879181679, 318200739395, 315549081360, 312923895613, 310324874338, 307751713804, 305204114304, 302681780091, 300184419325, 297711744011, 295263469943, 292839316650, 290439007336, 288062268834, 285708831544, 283378429385, 281070799744, 278785683424, 276522824592, 274281970735, 272062872607, 269865284185, 267688962617, 265533668182, 263399164244, 261285217201, 259191596450, 257118074337, 255064426120, 253030429921, 251015866692, 249020520167, 247044176831, 245086625873, 243147659150, 241227071150, 239324658957, 237440222207, 235573563060, 233724486157, 231892798592, 230078309873, 228280831889, 226500178875, 224736167383, 222988616248, 221257346553, 219542181601, 217842946885, 216159470053, 214491580882, 212839111248, 211201895096, 209579768410, 207972569187, 206380137411, 204802315020, 203238945886, 201689875781, 200154952359, 198634025123]
private theorem words593_eq : (List.range' 593 64).map threshold = words593 := by decide
private def words657 : List Nat := [197126945404, 195633566337, 194153742832, 192687331552, 191234190892, 189794180951, 188367163512, 186953002019, 185551561551, 184162708805, 182786312073, 181422241218, 180070367653, 178730564326, 177402705692, 176086667697, 174782327757, 173489564739, 172208258943, 170938292077, 169679547248, 168431908935, 167195262974, 165969496541, 164754498134, 163550157555, 162356365891, 161173015502, 160000000000, 158837214233, 157684554272, 156541917392, 155409202057, 154286307905, 153173135733, 152069587481, 150975566218, 149890976127, 148815722491, 147749711679, 146692851130, 145645049343, 144606215859, 143576261251, 142555097111, 141542636033, 140538791604, 139543478391, 138556611927, 137578108698, 136607886135, 135645862599, 134691957366, 133746090624, 132808183453, 131878157818, 130955936559, 130041443375, 129134602820, 128235340284, 127343581992, 126459254985, 125582287116, 124712607035]
private theorem words657_eq : (List.range' 657 64).map threshold = words657 := by decide
private def words721 : List Nat := [123850144184, 122994828784, 122146591824, 121305365056, 120471080981, 119643672844, 118823074620, 118009221010, 117202047427, 116401489992, 115607485522, 114819971525, 114038886184, 113264168360, 112495757574, 111733594003, 110977618472, 110227772447, 109483998023, 108746237922, 108014435482, 107288534650, 106568479973, 105854216597, 105145690253, 104442847250, 103745634475, 103053999380, 102367889974, 101687254823, 101012043037, 100342204267, 99677688697, 99018447039, 98364430525, 97715590901, 97071880423, 96433251849, 95799658434, 95171053924, 94547392549, 93928629018, 93314718515, 92705616691, 92101279660, 91501663994, 90906726715, 90316425292, 89730717637, 89149562096, 88572917447, 88000742894, 87432998062, 86869642993, 86310638139, 85755944360, 85205522917, 84659335469, 84117344067, 83579511151, 83045799544, 82516172449, 81990593444, 81469026478]
private theorem words721_eq : (List.range' 721 64).map threshold = words721 := by decide
private def words785 : List Nat := [80951435864, 80437786281, 79928042764, 79422170702, 78920135834, 78421904247, 77927442368, 77436716962, 76949695131, 76466344305, 75986632243, 75510527024, 75037997051, 74569011040, 74103538019, 73641547328, 73183008610, 72727891809, 72276167172, 71827805237, 71382776835, 70941053088, 70502605402, 70067405465, 69635425245, 69206636985, 68781013203, 68358526686, 67939150489, 67522857929, 67109622586, 66699418299, 66292219161, 65887999518, 65486733967, 65088397352, 64692964761, 64300411523, 63910713207, 63523845621, 63139784803, 62758507025, 62379988787, 62004206816, 61631138064, 61260759701, 60893049122, 60527983933, 60165541958, 59805701233, 59448440002, 59093736719, 58741570043, 58391918834, 58044762156, 57700079271, 57357849636, 57018052906, 56680668925, 56345677731, 56013059548, 55682794788, 55354864047, 55029248103]
private theorem words785_eq : (List.range' 785 64).map threshold = words785 := by decide
private def words849 : List Nat := [54705927917, 54384884627, 54066099546, 53749554167, 53435230151, 53123109334, 52813173720, 52505405481, 52199786955, 51896300644, 51594929215, 51295655491, 50998462459, 50703333261, 50410251195, 50119199715, 49830162426, 49543123084, 49258065595, 48974974014, 48693832542, 48414625523, 48137337447, 47861952944, 47588456787, 47316833885, 47047069287, 46779148177, 46513055875, 46248777833, 45986299636, 45725606999, 45466685768, 45209521916, 44954101542, 44700410873, 44448436256, 44198164166, 43949581197, 43702674062, 43457429597, 43213834754, 42971876601, 42731542324, 42492819222, 42255694707, 42020156304, 41786191651, 41553788492, 41322934683, 41093618187, 40865827073, 40639549518, 40414773800, 40191488303, 39969681515, 39749342022, 39530458512, 39313019774, 39097014694, 38882432256, 38669261540, 38457491724, 38247112077]
private theorem words849_eq : (List.range' 849 64).map threshold = words849 := by decide
private def words913 : List Nat := [38038111965, 37830480846, 37624208269, 37419283875, 37215697395, 37013438649, 36812497547, 36612864083, 36414528341, 36217480491, 36021710785, 35827209561, 35633967242, 35441974332, 35251221415, 35061699158, 34873398309, 34686309695, 34500424219, 34315732865, 34132226693, 33949896840, 33768734517, 33588731012, 33409877686, 33232165974, 33055587383, 32880133494, 32705795958, 32532566496, 32360436901, 32189399035, 32019444826, 31850566275, 31682755446, 31516004472, 31350305552, 31185650950, 31022032995, 30859444082, 30697876667, 30537323271, 30377776477, 30219228930, 30061673335, 29905102461, 29749509133, 29594886240, 29441226727, 29288523598, 29136769916, 28985958802, 28836083432, 28687137038, 28539112912, 28392004396, 28245804890, 28100507848, 27956106777, 27812595239, 27669966846, 27528215265, 27387334214, 27247317461]
private theorem words913_eq : (List.range' 913 64).map threshold = words913 := by decide
private def words977 : List Nat := [27108158828, 26969852184, 26832391450, 26695770596, 26559983642, 26425024655, 26290887751, 26157567094, 26025056895, 25893351413, 25762444950, 25632331858, 25503006532, 25374463414, 25246696990, 25119701790, 24993472389, 24868003403, 24743289495, 24619325369, 24496105770, 24373625486, 24251879349, 24130862228, 24010569037, 23890994728, 23772134294, 23653982767, 23536535220, 23419786764, 23303732548, 23188367763, 23073687633, 22959687423, 22846362435, 22733708007, 22621719516, 22510392372, 22399722025, 22289703956, 22180333687, 22071606770, 21963518796, 21856065388, 21749242204, 21643044935, 21537469308, 21432511080, 21328166044, 21224430025, 21121298879, 21018768496, 20916834796, 20815493733, 20714741291, 20614573484, 20514986359, 20415975992, 20317538490, 20219669989, 20122366657, 20025624689, 19929440310, 19833809775]
private theorem words977_eq : (List.range' 977 64).map threshold = words977 := by decide
private def words1041 : List Nat := [19738729367, 19644195396, 19550204203, 19456752155, 19363835648, 19271451105, 19179594975, 19088263737, 18997453893, 18907161975, 18817384541, 18728118172, 18639359478, 18551105093, 18463351679, 18376095920, 18289334527, 18203064235, 18117281804, 18031984019, 17947167687, 17862829643, 17778966741, 17695575862, 17612653909, 17530197809, 17448204512, 17366670988, 17285594235, 17204971268, 17124799128, 17045074875, 16965795595, 16886958391, 16808560391, 16730598743, 16653070615, 16575973199, 16499303704, 16423059363, 16347237427, 16271835169, 16196849881, 16122278876, 16048119485, 15974369061, 15901024974, 15828084616, 15755545395, 15683404741, 15611660100, 15540308940, 15469348743, 15398777015, 15328591275, 15258789062, 15189367935, 15120325468, 15051659254, 14983366901, 14915446039, 14847894311, 14780709380, 14713888922]
private theorem words1041_eq : (List.range' 1041 64).map threshold = words1041 := by decide
private def words1105 : List Nat := [14647430635, 14581332229, 14515591433, 14450205993, 14385173668, 14320492237, 14256159492, 14192173242, 14128531312, 14065231542, 14002271789, 13939649922, 13877363829, 13815411411, 13753790584, 13692499280, 13631535444, 13570897038, 13510582035, 13450588427, 13390914215, 13331557420, 13272516071, 13213788216, 13155371914, 13097265239, 13039466277, 12981973129, 12924783909, 12867896744, 12811309775, 12755021155, 12699029050, 12643331640, 12587927117, 12532813685, 12477989563, 12423452979, 12369202175, 12315235407, 12261550940, 12208147054, 12155022039, 12102174197, 12049601843, 11997303303, 11945276914, 11893521026, 11842033999, 11790814206, 11739860029, 11689169863, 11638742113, 11588575196, 11538667539, 11489017580, 11439623769, 11390484564, 11341598436, 11292963866, 11244579345, 11196443374, 11148554465, 11100911140]
private theorem words1105_eq : (List.range' 1105 64).map threshold = words1105 := by decide
private def words1169 : List Nat := [11053511930, 11006355378, 10959440035, 10912764464, 10866327236, 10820126932, 10774162143, 10728431470, 10682933523, 10637666921, 10592630292, 10547822276, 10503241518, 10458886677, 10414756416, 10370849411, 10327164345, 10283699911, 10240454808, 10197427748, 10154617449, 10112022637, 10069642048, 10027474427, 9985518526, 9943773106, 9902236936, 9860908793, 9819787462, 9778871738, 9738160422, 9697652323, 9657346259, 9617241056, 9577335547, 9537628572, 9498118980, 9458805628, 9419687379, 9380763104, 9342031682, 9303492000, 9265142951, 9226983436, 9189012362, 9151228645, 9113631208, 9076218979, 9038990896, 9001945901, 8965082945, 8928400986, 8891898986, 8855575918, 8819430759, 8783462492, 8747670109, 8712052607, 8676608990, 8641338269, 8606239459, 8571311585, 8536553677, 8501964769]
private theorem words1169_eq : (List.range' 1169 64).map threshold = words1169 := by decide
private def words1233 : List Nat := [8467543904, 8433290131, 8399202503, 8365280082, 8331521933, 8297927131, 8264494752, 8231223883, 8198113612, 8165163038, 8132371261, 8099737389, 8067260537, 8034939823, 8002774373, 7970763316, 7938905790, 7907200935, 7875647899, 7844245834, 7812993898, 7781891255, 7750937073, 7720130526, 7689470793, 7658957059, 7628588512, 7598364348, 7568283767, 7538345973, 7508550177, 7478895592, 7449381440, 7420006944, 7390771334, 7361673846, 7332713717, 7303890192, 7275202521, 7246649956, 7218231756, 7189947184, 7161795506, 7133775997, 7105887931, 7078130590, 7050503260, 7023005231, 6995635797, 6968394258, 6941279916, 6914292080, 6887430061, 6860693175, 6834080743, 6807592090, 6781226544, 6754983439, 6728862111, 6702861903, 6676982158, 6651222227, 6625581462, 6600059222]
private theorem words1233_eq : (List.range' 1233 64).map threshold = words1233 := by decide
private def words1297 : List Nat := [6574654867, 6549367763, 6524197279, 6499142787, 6474203665, 6449379294, 6424669058, 6400072344, 6375588546, 6351217059, 6326957282, 6302808618, 6278770474, 6254842261, 6231023392, 6207313285, 6183711361, 6160217044, 6136829762, 6113548948, 6090374036, 6067304463, 6044339674, 6021479111, 5998722224, 5976068465, 5953517289, 5931068155, 5908720523, 5886473860, 5864327633, 5842281313, 5820334376, 5798486298, 5776736562, 5755084650, 5733530050, 5712072252, 5690710749, 5669445038, 5648274617, 5627198989, 5606217659, 5585330135, 5564535928, 5543834553, 5523225525, 5502708366, 5482282596, 5461947742, 5441703333, 5421548898, 5401483972, 5381508092, 5361620796, 5341821627, 5322110130, 5302485852, 5282948342, 5263497154, 5244131844, 5224851968, 5205657088, 5186546767]
private theorem words1297_eq : (List.range' 1297 64).map threshold = words1297 := by decide
private def words1361 : List Nat := [5167520570, 5148578067, 5129718827, 5110942424, 5092248433, 5073636434, 5055106007, 5036656734, 5018288203, 5000000000, 4981791716, 4963662945, 4945613280, 4927642321, 4909749666, 4891934919, 4874197682, 4856537564, 4838954174, 4821447122, 4804016023, 4786660492, 4769380147, 4752174609, 4735043500, 4717986444, 4701003069, 4684093004, 4667255879, 4650491328, 4633798986, 4617178490, 4600629480, 4584151598, 4567744487, 4551407792, 4535141162, 4518944246, 4502816695, 4486758164, 4470768308, 4454846785, 4438993254, 4423207376, 4407488816, 4391837238, 4376252309, 4360733700, 4345281080, 4329894123, 4314572503, 4299315897, 4284123983, 4268996442, 4253932955, 4238933206, 4223996881, 4209123668, 4194313254, 4179565332, 4164879593, 4150255733, 4135693446, 4121192432]
private theorem words1361_eq : (List.range' 1361 64).map threshold = words1361 := by decide
private def words1425 : List Nat := [4106752388, 4092373017, 4078054022, 4063795105, 4049595975, 4035456338, 4021375904, 4007354384, 3993391490, 3979486937, 3965640441, 3951851718, 3938120489, 3924446472, 3910829392, 3897268970, 3883764932, 3870317006, 3856924918, 3843588399, 3830307181, 3817080995, 3803909575, 3790792658, 3777729980, 3764721281, 3751766299, 3738864776, 3726016456, 3713221082, 3700478400, 3687788157, 3675150101, 3662563982, 3650029552, 3637546562, 3625114767, 3612733923, 3600403784, 3588124110, 3575894660, 3563715193, 3551585473, 3539505261, 3527474323, 3515492424, 3503559331, 3491674813, 3479838638, 3468050577, 3456310403, 3444617889, 3432972809, 3421374938, 3409824054, 3398319935, 3386862360, 3375451109, 3364085964, 3352766708, 3341493125, 3330264999, 3319082118, 3307944269]
private theorem words1425_eq : (List.range' 1425 64).map threshold = words1425 := by decide
private def words1489 : List Nat := [3296851240, 3285802820, 3274798802, 3263838977, 3252923137, 3242051077, 3231222593, 3220437481, 3209695537, 3198996562, 3188340353, 3177726713, 3167155443, 3156626345, 3146139223, 3135693883, 3125290130, 3114927772, 3104606615, 3094326470, 3084087146, 3073888454, 3063730206, 3053612216, 3043534296, 3033496263, 3023497932, 3013539120, 3003619645, 2993739326, 2983897982, 2974095435, 2964331506, 2954606017, 2944918793, 2935269657, 2925658435, 2916084954, 2906549040, 2897050522, 2887589228, 2878164989, 2868777636, 2859427000, 2850112913, 2840835210, 2831593724, 2822388290, 2813218746, 2804084926, 2794986670, 2785923816, 2776896202, 2767903670, 2758946061, 2750023215, 2741134977, 2732281189, 2723461697, 2714676344, 2705924976, 2697207442, 2688523587, 2679873261]
private theorem words1489_eq : (List.range' 1489 64).map threshold = words1489 := by decide
private def words1553 : List Nat := [2671256313, 2662672591, 2654121948, 2645604233, 2637119301, 2628667002, 2620247192, 2611859723, 2603504453, 2595181236, 2586889929, 2578630389, 2570402475, 2562206045, 2554040959, 2545907077, 2537804261, 2529732371, 2521691270, 2513680821, 2505700889, 2497751336, 2489832030, 2481942834, 2474083617, 2466254245, 2458454586, 2450684508, 2442943881, 2435232574, 2427550458, 2419897405, 2412273286, 2404677973, 2397111340, 2389573260, 2382063607, 2374582258, 2367129086, 2359703970, 2352306784, 2344937408, 2337595719, 2330281595, 2322994917, 2315735563, 2308503415, 2301298354, 2294120261, 2286969019, 2279844511, 2272746619, 2265675229, 2258630224, 2251611491, 2244618914, 2237652380, 2230711776, 2223796990, 2216907909, 2210044422, 2203206419, 2196393788, 2189606421]
private theorem words1553_eq : (List.range' 1553 64).map threshold = words1553 := by decide
private def words1617 : List Nat := [2182844207, 2176107039, 2169394808, 2162707406, 2156044726, 2149406663, 2142793109, 2136203959, 2129639108, 2123098453, 2116581888, 2110089310, 2103620617, 2097175706, 2090754475, 2084356822, 2077982647, 2071631849, 2065304328, 2058999985, 2052718721, 2046460436, 2040225035, 2034012417, 2027822488, 2021655149, 2015510305, 2009387860, 2003287719, 1997209788, 1991153971, 1985120176, 1979108308, 1973118275, 1967149985, 1961203345, 1955278263, 1949374650, 1943492413, 1937631463, 1931791710, 1925973064, 1920175438, 1914398741, 1908642886, 1902907785, 1897193351, 1891499498, 1885826138, 1880173186, 1874540556, 1868928164, 1863335923, 1857763750, 1852211561, 1846679272, 1841166801, 1835674064, 1830200979, 1824747464, 1819313437, 1813898817, 1808503524, 1803127477]
private theorem words1617_eq : (List.range' 1617 64).map threshold = words1617 := by decide
private def words1681 : List Nat := [1797770596, 1792432801, 1787114013, 1781814153, 1776533143, 1771270904, 1766027358, 1760802429, 1755596039, 1750408111, 1745238569, 1740087337, 1734954340, 1729839501, 1724742747, 1719664003, 1714603194, 1709560247, 1704535088, 1699527645, 1694537843, 1689565611, 1684610876, 1679673568, 1674753613, 1669850942, 1664965483, 1660097167, 1655245922, 1650411679, 1645594368, 1640793921, 1636010269, 1631243342, 1626493074, 1621759395, 1617042239, 1612341538, 1607657225, 1602989234, 1598337498, 1593701952, 1589082529, 1584479164, 1579891793, 1575320350, 1570764771, 1566224991, 1561700947, 1557192576, 1552699813, 1548222596, 1543760863, 1539314550, 1534883596, 1530467938, 1526067516, 1521682267, 1517312131, 1512957048, 1508616956, 1504291795, 1499981506, 1495686030]
private theorem words1681_eq : (List.range' 1681 64).map threshold = words1681 := by decide
private def words1745 : List Nat := [1491405305, 1487139275, 1482887879, 1478651059, 1474428757, 1470220915, 1466027476, 1461848381, 1457683573, 1453532996, 1449396593, 1445274307, 1441166083, 1437071864, 1432991594, 1428925219, 1424872682, 1420833930, 1416808908, 1412797560, 1408799833, 1404815673, 1400845027, 1396887840, 1392944060, 1389013633, 1385096507, 1381192630, 1377301949, 1373424412, 1369559968, 1365708564, 1361870150, 1358044675, 1354232087, 1350432336, 1346645372, 1342871144, 1339109602, 1335360698, 1331624380, 1327900601, 1324189310, 1320490460, 1316804001, 1313129885, 1309468063, 1305818489, 1302181114, 1298555890, 1294942771, 1291341709, 1287752657, 1284175568, 1280610397, 1277057096, 1273515620, 1269985922, 1266467958, 1262961681, 1259467047, 1255984009, 1252512525, 1249052547]
private theorem words1745_eq : (List.range' 1745 64).map threshold = words1745 := by decide
private def words1809 : List Nat := [1245604033, 1242166938, 1238741218, 1235326828, 1231923726, 1228531868, 1225151210, 1221781709, 1218423323, 1215076008, 1211739722, 1208414423, 1205100069, 1201796616, 1198504025, 1195222252, 1191951258, 1188690999, 1185441436, 1182202526, 1178974231, 1175756508, 1172549319, 1169352621, 1166166376, 1162990544, 1159825084, 1156669958, 1153525126, 1150390548, 1147266187, 1144152003, 1141047957, 1137954011, 1134870126, 1131796265, 1128732390, 1125678462, 1122634444, 1119600299, 1116575989, 1113561476, 1110556725, 1107561698, 1104576358, 1101600669, 1098634595, 1095678099, 1092731145, 1089793697, 1086865720, 1083947178, 1081038035, 1078138257, 1075247807, 1072366652, 1069494756, 1066632084, 1063778602, 1060934276, 1058099071, 1055272954, 1052455889, 1049647844]
private theorem words1809_eq : (List.range' 1809 64).map threshold = words1809 := by decide
private def words1873 : List Nat := [1046848785, 1044058678, 1041277489, 1038505187, 1035741736, 1032987106, 1030241262, 1027504172, 1024775803, 1022056124, 1019345101, 1016642703, 1013948898, 1011263653, 1008586938, 1005918720, 1003258968, 1000607651, 997964737, 995330196, 992703997, 990086108, 987476499, 984875140, 982282000, 979697048, 977120256, 974551592, 971991027, 969438531, 966894074, 964357628, 961829161, 959308646, 956796053, 954291352, 951794516, 949305515, 946824320, 944350904, 941885237, 939427292, 936977039, 934534452, 932099502, 929672160, 927252401, 924840195, 922435516, 920038335, 917648627, 915266362, 912891516, 910524060, 908163968, 905811213, 903465768, 901127607, 898796704, 896473032, 894156566, 891847278, 889545144, 887250137]
private theorem words1873_eq : (List.range' 1873 64).map threshold = words1873 := by decide
private def words1937 : List Nat := [884962232, 882681403, 880407624, 878140870, 875881116, 873628337, 871382507, 869143601, 866911595, 864686464, 862468183, 860256727, 858052072, 855854194, 853663068, 851478671, 849300977, 847129963, 844965606, 842807881, 840656764, 838512233, 836374263, 834242831, 832117914, 829999489, 827887532, 825782020, 823682932, 821590242, 819503930, 817423972, 815350345, 813283028, 811221998, 809167232, 807118708, 805076405, 803040299, 801010371, 798986596, 796968954, 794957423, 792951982, 790952608, 788959281, 786971979, 784990681, 783015366, 781046012, 779082599, 777125106, 775173512, 773227797, 771287939, 769353918, 767425713, 765503305, 763586673, 761675796, 759770655, 757871230, 755977499, 754089445]
private theorem words1937_eq : (List.range' 1937 64).map threshold = words1937 := by decide
private def words2001 : List Nat := [752207046, 750330282, 748459136, 746593585, 744733612, 742879197, 741030320, 739186961, 737349103, 735516726, 733689810, 731868336, 730052287, 728241642, 726436384, 724636493, 722841950, 721052739, 719268839, 717490232, 715716901, 713948826, 712185990, 710428375, 708675963, 706928735, 705186674, 703449762, 701717981, 699991313, 698269742, 696553249, 694841816, 693135428, 691434065, 689737712, 688046350, 686359962, 684678533, 683002043, 681330478, 679663819, 678002050, 676345154, 674693115, 673045916, 671403540, 669765971, 668133193, 666505189, 664881943, 663263438, 661649659, 660040590, 658436214, 656836515, 655241479, 653651087, 652065326, 650484179, 648907631, 647335665, 645768267, 644205421]
private theorem words2001_eq : (List.range' 2001 64).map threshold = words2001 := by decide
private def words2065 : List Nat := [642647112, 641093324, 639544041, 637999250, 636458934, 634923078, 633391667, 631864687, 630342122, 628823958, 627310179, 625800772, 624295720, 622795010, 621298626, 619806555, 618318782, 616835293, 615356072, 613881106, 612410381, 610943881, 609481594, 608023505, 606569599, 605119864, 603674284, 602232847, 600795538, 599362343, 597933249, 596508242, 595087308, 593670434, 592257607, 590848812, 589444036, 588043267, 586646490, 585253693, 583864862, 582479984, 581099046, 579722034, 578348937, 576979740, 575614431, 574252997, 572895426, 571541704, 570191819, 568845757, 567503507, 566165056, 564830392, 563499501, 562172371, 560848990, 559529346, 558213426, 556901219, 555592711, 554287890, 552986746]
private theorem words2065_eq : (List.range' 2065 64).map threshold = words2065 := by decide
private def words2129 : List Nat := [551689264, 550395435, 549105244, 547818682, 546535734, 545256391, 543980640, 542708468, 541439866, 540174820, 538913319, 537655352, 536400907, 535149973, 533902537, 532658590, 531418119, 530181112, 528947560, 527717450, 526490771, 525267512, 524047663, 522831211, 521618146, 520408457, 519202133, 517999162, 516799535, 515603241, 514410268, 513220605, 512034243, 510851170, 509671375, 508494849, 507321580, 506151559, 504984774, 503821215, 502660872, 501503734, 500349791, 499199033, 498051450, 496907030, 495765765, 494627644, 493492657, 492360794, 491232044, 490106398, 488983846, 487864378, 486747984, 485634654, 484524379, 483417148, 482312952, 481211782, 480113627, 479018477, 477926324, 476837158]
private theorem words2129_eq : (List.range' 2129 64).map threshold = words2129 := by decide
private def words2193 : List Nat := [475750969, 474667748, 473587485, 472510171, 471435796, 470364352, 469295828, 468230216, 467167506, 466107689, 465050756, 463996697, 462945504, 461897168, 460851679, 459809029, 458769208, 457732207, 456698018, 455666632, 454638040, 453612232, 452589201, 451568937, 450551432, 449536677, 448524663, 447515382, 446508825, 445504984, 444503850, 443505414, 442509668, 441516603, 440526212, 439538486, 438553416, 437570993, 436591211, 435614060, 434639532, 433667620, 432698314, 431731607, 430767490, 429805956, 428846996, 427890603, 426936767, 425985483, 425036740, 424090532, 423146851, 422205689, 421267037, 420330888, 419397235, 418466069, 417537383, 416611169, 415687420, 414766127, 413847284, 412930882]
private theorem words2193_eq : (List.range' 2193 64).map threshold = words2193 := by decide
private def words2257 : List Nat := [412016914, 411105372, 410196250, 409289539, 408385232, 407483321, 406583800, 405686660, 404791895, 403899497, 403009459, 402121773, 401236433, 400353430, 399472759, 398594411, 397718380, 396844658, 395973238, 395104114, 394237278, 393372722, 392510441, 391650428, 390792674, 389937174, 389083920, 388232906, 387384124, 386537568, 385693231, 384851106, 384011187, 383173467, 382337938, 381504595, 380673431, 379844439, 379017612, 378192944, 377370428, 376550058, 375731827, 374915728, 374101756, 373289904, 372480164, 371672532, 370867000, 370063562, 369262212, 368462944, 367665751, 366870626, 366077564, 365286558, 364497603, 363710691, 362925817, 362142975, 361362158, 360583361, 359806576, 359031799]
private theorem words2257_eq : (List.range' 2257 64).map threshold = words2257 := by decide
private def words2321 : List Nat := [358259024, 357488243, 356719451, 355952643, 355187811, 354424951, 353664056, 352905121, 352148139, 351393105, 350640012, 349888855, 349139629, 348392327, 347646944, 346903473, 346161910, 345422248, 344684482, 343948606, 343214614, 342482501, 341752261, 341023890, 340297380, 339572726, 338849924, 338128967, 337409850, 336692567, 335977113, 335263483, 334551672, 333841673, 333133481, 332427091, 331722498, 331019697, 330318681, 329619446, 328921987, 328226297, 327532373, 326840209, 326149799, 325461138, 324774222, 324089044, 323405601, 322723886, 322043895, 321365622, 320689063, 320014213, 319341066, 318669617, 317999862, 317331795, 316665412, 316000707, 315337676, 314676314, 314016615, 313358576]
private theorem words2321_eq : (List.range' 2321 64).map threshold = words2321 := by decide
private def words2385 : List Nat := [312702190, 312047454, 311394362, 310742910, 310093092, 309444904, 308798342, 308153400, 307510073, 306868358, 306228249, 305589742, 304952831, 304317513, 303683783, 303051635, 302421066, 301792071, 301164644, 300538783, 299914482, 299291736, 298670541, 298050893, 297432787, 296816218, 296201183, 295587676, 294975693, 294365231, 293756283, 293148847, 292542917, 291938490, 291335561, 290734125, 290134179, 289535717, 288938737, 288343232, 287749200, 287156636, 286565536, 285975895, 285387710, 284800975, 284215688, 283631843, 283049437, 282468465, 281888924, 281310809, 280734117, 280158842, 279584981, 279012531, 278441486, 277871843, 277303598, 276736747, 276171286, 275607211, 275044518, 274483203]
private theorem words2385_eq : (List.range' 2385 64).map threshold = words2385 := by decide
private def words2449 : List Nat := [273923262, 273364691, 272807486, 272251644, 271697160, 271144031, 270592252, 270041821, 269492732, 268944983, 268398569, 267853487, 267309733, 266767302, 266226192, 265686399, 265147918, 264610747, 264074881, 263540317, 263007050, 262475078, 261944397, 261415003, 260886892, 260360060, 259834505, 259310223, 258787209, 258265461, 257744975, 257225746, 256707773, 256191050, 255675576, 255161345, 254648355, 254136602, 253626083, 253116793, 252608731, 252101892, 251596272, 251091869, 250588680, 250086699, 249585925, 249086354, 248587982, 248090806, 247594823, 247100029, 246606422, 246113997, 245622751, 245132682, 244643786, 244156059, 243669499, 243184102, 242699864, 242216784, 241734856, 241254079]
private theorem words2449_eq : (List.range' 2449 64).map threshold = words2449 := by decide
private def words2513 : List Nat := [240774449, 240295962, 239818616, 239342408, 238867334, 238393391, 237920576, 237448886, 236978317, 236508868, 236040533, 235573312, 235107199, 234642193, 234178290, 233715487, 233253782, 232793170, 232333649, 231875217, 231417870, 230961604, 230506418, 230052308, 229599271, 229147304, 228696404, 228246569, 227797794, 227350079, 226903419, 226457811, 226013253, 225569742, 225127275, 224685849, 224245462, 223806110, 223367790, 222930500, 222494237, 222058998, 221624780, 221191581, 220759397, 220328227, 219898066, 219468913, 219040765, 218613619, 218187471, 217762321, 217338163, 216914997, 216492820, 216071627, 215651418, 215232189, 214813938, 214396662, 213980358, 213565023, 213150656, 212737253]
private theorem words2513_eq : (List.range' 2513 64).map threshold = words2513 := by decide
private def words2577 : List Nat := [212324812, 211913330, 211502804, 211093232, 210684612, 210276941, 209870216, 209464434, 209059594, 208655692, 208252727, 207850695, 207449593, 207049421, 206650174, 206251851, 205854448, 205457965, 205062397, 204667743, 204273999, 203881165, 203489237, 203098212, 202708089, 202318865, 201930537, 201543103, 201156561, 200770908, 200386142, 200002261, 199619262, 199237142, 198855900, 198475533, 198096039, 197717415, 197339659, 196962769, 196586743, 196211577, 195837271, 195463821, 195091225, 194719481, 194348587, 193978540, 193609339, 193240980, 192873462, 192506783, 192140939, 191775930, 191411753, 191048405, 190685884, 190324189, 189963316, 189603264, 189244031, 188885615, 188528012, 188171222]
private theorem words2577_eq : (List.range' 2577 64).map threshold = words2577 := by decide
private def words2641 : List Nat := [187815242, 187460070, 187105703, 186752140, 186399378, 186047415, 185696250, 185345880, 184996303, 184647516, 184299519, 183952308, 183605882, 183260239, 182915376, 182571291, 182227983, 181885449, 181543688, 181202697, 180862474, 180523018, 180184325, 179846395, 179509226, 179172814, 178837159, 178502258, 178168109, 177834711, 177502061, 177170157, 176838998, 176508582, 176178906, 175849968, 175521768, 175194302, 174867569, 174541567, 174216294, 173891748, 173567927, 173244830, 172922454, 172600798, 172279859, 171959636, 171640128, 171321331, 171003245, 170685867, 170369196, 170053229, 169737966, 169423403, 169109540, 168796374, 168483904, 168172128, 167861044, 167550650, 167240945, 166931926]
private theorem words2641_eq : (List.range' 2641 64).map threshold = words2641 := by decide
private def words2705 : List Nat := [166623592, 166315942, 166008972, 165702683, 165397071, 165092136, 164787875, 164484286, 164181368, 163879120, 163577539, 163276624, 162976373, 162676784, 162377856, 162079586, 161781974, 161485018, 161188715, 160893065, 160598065, 160303713, 160010009, 159716951, 159424536, 159132764, 158841632, 158551139, 158261283, 157972063, 157683477, 157395523, 157108200, 156821506, 156535440, 156250000, 155965184, 155680991, 155397419, 155114467, 154832133, 154550415, 154269312, 153988823, 153708945, 153429677, 153151018, 152872966, 152595520, 152318678, 152042438, 151766799, 151491759, 151217318, 150943473, 150670223, 150397566, 150125501, 149854026, 149583140, 149312842, 149043130, 148774002, 148505457]
private theorem words2705_eq : (List.range' 2705 64).map threshold = words2705 := by decide
private def words2769 : List Nat := [148237493, 147970109, 147703304, 147437076, 147171424, 146906346, 146641841, 146377906, 146114542, 145851746, 145589517, 145327854, 145066755, 144806218, 144546243, 144286828, 144027971, 143769671, 143511927, 143254737, 142998101, 142742015, 142486480, 142231493, 141977054, 141723161, 141469813, 141217008, 140964744, 140713022, 140461838, 140211193, 139961084, 139711510, 139462470, 139213962, 138965986, 138718539, 138471621, 138225231, 137979366, 137734025, 137489209, 137244914, 137001139, 136757885, 136515148, 136272928, 136031224, 135790034, 135549357, 135309191, 135069536, 134830391, 134591753, 134353622, 134115996, 133878874, 133642256, 133406139, 133170522, 132935405, 132700785, 132466663]
private theorem words2769_eq : (List.range' 2769 64).map threshold = words2769 := by decide
private def words2833 : List Nat := [132233035, 131999903, 131767263, 131535115, 131303457, 131072289, 130841609, 130611417, 130381710, 130152487, 129923748, 129695492, 129467716, 129240420, 129013603, 128787263, 128561400, 128336012, 128111098, 127886657, 127662687, 127439188, 127216159, 126993597, 126771503, 126549874, 126328711, 126108011, 125887773, 125667997, 125448681, 125229824, 125011426, 124793484, 124575998, 124358967, 124142389, 123926264, 123710590, 123495366, 123280592, 123066265, 122852386, 122638952, 122425964, 122213418, 122001316, 121789655, 121578435, 121367654, 121157312, 120947406, 120737937, 120528904, 120320304, 120112137, 119904403, 119697099, 119490226, 119283781, 119077764, 118872174, 118667010, 118462271]
private theorem words2833_eq : (List.range' 2833 64).map threshold = words2833 := by decide
private def words2897 : List Nat := [118257955, 118054062, 117850591, 117647540, 117444909, 117242697, 117040902, 116839524, 116638562, 116438014, 116237880, 116038159, 115838849, 115639950, 115441461, 115243380, 115045707, 114848441, 114651580, 114455124, 114259073, 114063423, 113868176, 113673330, 113478884, 113284836, 113091187, 112897935, 112705079, 112512618, 112320552, 112128878, 111937598, 111746708, 111556209, 111366100, 111176379, 110987046, 110798100, 110609539, 110421364, 110233573, 110046164, 109859138, 109672493, 109486229, 109300344, 109114838, 108929709, 108744957, 108560581, 108376581, 108192954, 108009700, 107826819, 107644309, 107462170, 107280400, 107099000, 106917967, 106737301, 106557002, 106377068, 106197498]
private theorem words2897_eq : (List.range' 2897 64).map threshold = words2897 := by decide
private def words2961 : List Nat := [106018292, 105839449, 105660967, 105482847, 105305087, 105127686, 104950644, 104773960, 104597632, 104421660, 104246044, 104070781, 103895872, 103721316, 103547112, 103373258, 103199755, 103026601, 102853796, 102681338, 102509227, 102337463, 102166043, 101994968, 101824237, 101653848, 101483801, 101314096, 101144731, 100975706, 100807020, 100638671, 100470660, 100302986, 100135647, 99968643, 99801973, 99635636, 99469632, 99303960, 99138619, 98973608, 98808926, 98644573, 98480548, 98316851, 98153479, 97990434, 97827713, 97665317, 97503243, 97341493, 97180064, 97018957, 96858170, 96697702, 96537554, 96377723, 96218210, 96059014, 95900134, 95741569, 95583318, 95425382]
private theorem words2961_eq : (List.range' 2961 64).map threshold = words2961 := by decide
private def words3025 : List Nat := [95267758, 95110447, 94953447, 94796758, 94640380, 94484310, 94328550, 94173098, 94017952, 93863114, 93708581, 93554354, 93400431, 93246812, 93093496, 92940482, 92787770, 92635360, 92483249, 92331438, 92179926, 92028712, 91877796, 91727177, 91576854, 91426826, 91277093, 91127655, 90978510, 90829657, 90681097, 90532829, 90384851, 90237163, 90089765, 89942656, 89795835, 89649301, 89503054, 89357094, 89211419, 89066029, 88920923, 88776100, 88631561, 88487304, 88343328, 88199634, 88056220, 87913086, 87770231, 87627654, 87485355, 87343333, 87201588, 87060119, 86918925, 86778006, 86637361, 86496990, 86356891, 86217064, 86077509, 85938225]
private theorem words3025_eq : (List.range' 3025 64).map threshold = words3025 := by decide
private def words3089 : List Nat := [85799212, 85660468, 85521993, 85383787, 85245849, 85108178, 84970774, 84833636, 84696763, 84560156, 84423812, 84287733, 84151916, 84016362, 83881070, 83746039, 83611270, 83476760, 83342510, 83208518, 83074786, 82941311, 82808093, 82675132, 82542427, 82409978, 82277784, 82145844, 82014158, 81882725, 81751544, 81620616, 81489940, 81359514, 81229339, 81099414, 80969738, 80840310, 80711131, 80582200, 80453515, 80325077, 80196885, 80068939, 79941237, 79813780, 79686566, 79559596, 79432869, 79306383, 79180139, 79054137, 78928374, 78802852, 78677569, 78552526, 78427720, 78303153, 78178823, 78054729, 77930872, 77807251, 77683865, 77560714]
private theorem words3089_eq : (List.range' 3089 64).map threshold = words3089 := by decide
private def words3153 : List Nat := [77437796, 77315113, 77192663, 77070445, 76948460, 76826706, 76705183, 76583891, 76462829, 76341996, 76221393, 76101018, 75980871, 75860952, 75741260, 75621794, 75502554, 75383540, 75264751, 75146187, 75027846, 74909729, 74791836, 74674164, 74556715, 74439488, 74322481, 74205696, 74089130, 73972784, 73856657, 73740749, 73625059, 73509587, 73394332, 73279294, 73164472, 73049866, 72935476, 72821300, 72707339, 72593591, 72480057, 72366736, 72253628, 72140732, 72028047, 71915574, 71803311, 71691258, 71579415, 71467782, 71356357, 71245141, 71134133, 71023332, 70912738, 70802351, 70692170, 70582195, 70472424, 70362859, 70253498, 70144341]
private theorem words3153_eq : (List.range' 3153 64).map threshold = words3153 := by decide
private def words3217 : List Nat := [70035387, 69926637, 69818089, 69709743, 69601599, 69493656, 69385914, 69278372, 69171030, 69063888, 68956945, 68850201, 68743654, 68637306, 68531155, 68425201, 68319443, 68213881, 68108516, 68003345, 67898369, 67793588, 67689000, 67584606, 67480406, 67376398, 67272582, 67168958, 67065526, 66962285, 66859234, 66756374, 66653703, 66551222, 66448930, 66346827, 66244911, 66143184, 66041644, 65940291, 65839125, 65738144, 65637350, 65536741, 65436317, 65336077, 65236022, 65136151, 65036463, 64936958, 64837635, 64738495, 64639537, 64540760, 64442165, 64343750, 64245515, 64147460, 64049585, 63951889, 63854371, 63757032, 63659871, 63562888]
private theorem words3217_eq : (List.range' 3217 64).map threshold = words3217 := by decide
private def words3281 : List Nat := [63466082, 63369453, 63273000, 63176723, 63080623, 62984697, 62888947, 62793371, 62697969, 62602741, 62507687, 62412806, 62318098, 62223562, 62129198, 62035005, 61940985, 61847135, 61753455, 61659946, 61566607, 61473437, 61380436, 61287605, 61194941, 61102446, 61010118, 60917958, 60825965, 60734138, 60642478, 60550983, 60459654, 60368491, 60277492, 60186658, 60095988, 60005482, 59915140, 59824961, 59734944, 59645090, 59555398, 59465868, 59376500, 59287292, 59198246, 59109359, 59020633, 58932067, 58843660, 58755412, 58667323, 58579392, 58491620, 58404005, 58316548, 58229248, 58142104, 58055117, 57968286, 57881611, 57795092, 57708727]
private theorem words3281_eq : (List.range' 3281 64).map threshold = words3281 := by decide
private def words3345 : List Nat := [57622518, 57536463, 57450562, 57364814, 57279221, 57193781, 57108493, 57023358, 56938376, 56853545, 56768866, 56684338, 56599961, 56515735, 56431659, 56347734, 56263958, 56180331, 56096854, 56013525, 55930345, 55847313, 55764429, 55681692, 55599103, 55516661, 55434365, 55352216, 55270212, 55188355, 55106643, 55025076, 54943654, 54862376, 54781243, 54700253, 54619408, 54538705, 54458146, 54377729, 54297455, 54217323, 54137333, 54057484, 53977777, 53898211, 53818785, 53739500, 53660355, 53581350, 53502484, 53423758, 53345170, 53266722, 53188411, 53110239, 53032204, 52954308, 52876548, 52798925, 52721439, 52644090, 52566877, 52489799]
private theorem words3345_eq : (List.range' 3345 64).map threshold = words3345 := by decide
private def words3409 : List Nat := [52412857, 52336050, 52259379, 52182842, 52106440, 52030171, 51954037, 51878036, 51802169, 51726435, 51650834, 51575365, 51500028, 51424824, 51349751, 51274810, 51200000, 51125321, 51050772, 50976354, 50902067, 50827909, 50753880, 50679981, 50606211, 50532570, 50459057, 50385673, 50312417, 50239288, 50166287, 50093414, 50020667, 49948047, 49875553, 49803186, 49730945, 49658829, 49586839, 49514974, 49443234, 49371619, 49300128, 49228761, 49157518, 49086399, 49015403, 48944531, 48873781, 48803155, 48732650, 48662268, 48592008, 48521869, 48451852, 48381956, 48312181, 48242527, 48172993, 48103580, 48034286, 47965112, 47896058, 47827123]
private theorem words3409_eq : (List.range' 3409 64).map threshold = words3409 := by decide
private def words3473 : List Nat := [47758307, 47689610, 47621031, 47552571, 47484229, 47416004, 47347897, 47279908, 47212035, 47144280, 47076641, 47009119, 46941712, 46874422, 46807248, 46740188, 46673245, 46606416, 46539702, 46473102, 46406617, 46340246, 46273989, 46207846, 46141816, 46075899, 46010095, 45944404, 45878825, 45813359, 45748004, 45682762, 45617631, 45552612, 45487703, 45422906, 45358220, 45293644, 45229178, 45164822, 45100576, 45036440, 44972413, 44908496, 44844687, 44780987, 44717396, 44653913, 44590538, 44527271, 44464112, 44401060, 44338116, 44275278, 44212548, 44149924, 44087406, 44024995, 43962689, 43900490, 43838396, 43776407, 43714524, 43652745]
private theorem words3473_eq : (List.range' 3473 64).map threshold = words3473 := by decide
private def words3537 : List Nat := [43591071, 43529502, 43468037, 43406676, 43345419, 43284266, 43223216, 43162270, 43101426, 43040686, 42980048, 42919513, 42859080, 42798749, 42738520, 42678393, 42618367, 42558442, 42498619, 42438896, 42379274, 42319753, 42260332, 42201011, 42141789, 42082668, 42023646, 41964723, 41905900, 41847175, 41788549, 41730022, 41671593, 41613262, 41555029, 41496894, 41438856, 41380916, 41323073, 41265327, 41207678, 41150125, 41092669, 41035309, 40978045, 40920877, 40863805, 40806828, 40749946, 40693160, 40636468, 40579872, 40523369, 40466962, 40410648, 40354428, 40298303, 40242271, 40186332, 40130487, 40074734, 40019075, 39963508, 39908034]
private theorem words3537_eq : (List.range' 3537 64).map threshold = words3537 := by decide
private def words3601 : List Nat := [39852653, 39797363, 39742166, 39687060, 39632046, 39577124, 39522293, 39467553, 39412903, 39358345, 39303878, 39249500, 39195213, 39141016, 39086909, 39032892, 38978964, 38925126, 38871377, 38817717, 38764146, 38710663, 38657269, 38603963, 38550746, 38497616, 38444575, 38391621, 38338754, 38285975, 38233283, 38180678, 38128160, 38075729, 38023384, 37971125, 37918953, 37866866, 37814866, 37762951, 37711121, 37659377, 37607718, 37556144, 37504655, 37453251, 37401931, 37350695, 37299544, 37248477, 37197493, 37146594, 37095778, 37045045, 36994395, 36943829, 36893345, 36842945, 36792627, 36742391, 36692237, 36642166, 36592177, 36542269]
private theorem words3601_eq : (List.range' 3601 64).map threshold = words3601 := by decide
private def words3665 : List Nat := [36492444, 36442699, 36393036, 36343454, 36293954, 36244534, 36195195, 36145936, 36096758, 36047660, 35998642, 35949705, 35900847, 35852068, 35803370, 35754750, 35706210, 35657749, 35609366, 35561063, 35512838, 35464691, 35416623, 35368633, 35320721, 35272887, 35225131, 35177452, 35129851, 35082326, 35034879, 34987509, 34940216, 34893000, 34845860, 34798796, 34751809, 34704898, 34658062, 34611303, 34564619, 34518011, 34471478, 34425021, 34378639, 34332331, 34286098, 34239941, 34193857, 34147848, 34101914, 34056053, 34010266, 33964554, 33918915, 33873349, 33827857, 33782439, 33737093, 33691821, 33646621, 33601494, 33556440, 33511458]
private theorem words3665_eq : (List.range' 3665 64).map threshold = words3665 := by decide
private def words3729 : List Nat := [33466548, 33421711, 33376946, 33332253, 33287631, 33243081, 33198603, 33154196, 33109860, 33065596, 33021402, 32977280, 32933228, 32889247, 32845336, 32801495, 32757725, 32714025, 32670394, 32626834, 32583343, 32539922, 32496570, 32453287, 32410074, 32366929, 32323854, 32280847, 32237909, 32195039, 32152238, 32109505, 32066841, 32024244, 31981715, 31939254, 31896860, 31854534, 31812276, 31770084, 31727960, 31685903, 31643913, 31601989, 31560132, 31518342, 31476618, 31434960, 31393368, 31351843, 31310383, 31268989, 31227661, 31186398, 31145201, 31104069, 31063002, 31022000, 30981063, 30940191, 30899383, 30858641, 30817962, 30777348]
private theorem words3729_eq : (List.range' 3729 64).map threshold = words3729 := by decide
private def words3793 : List Nat := [30736798, 30696312, 30655891, 30615533, 30575239, 30535008, 30494841, 30454737, 30414697, 30374720, 30334805, 30294954, 30255166, 30215440, 30175777, 30136176, 30096637, 30057161, 30017747, 29978395, 29939105, 29899877, 29860710, 29821605, 29782561, 29743579, 29704657, 29665797, 29626998, 29588260, 29549583, 29510966, 29472409, 29433914, 29395478, 29357103, 29318788, 29280532, 29242337, 29204202, 29166126, 29128109, 29090153, 29052255, 29014417, 28976638, 28938917, 28901256, 28863654, 28826110, 28788625, 28751198, 28713830, 28676520, 28639268, 28602074, 28564938, 28527860, 28490840, 28453877, 28416972, 28380124, 28343334, 28306600]
private theorem words3793_eq : (List.range' 3793 64).map threshold = words3793 := by decide
private def words3857 : List Nat := [28269924, 28233305, 28196743, 28160238, 28123789, 28087397, 28051061, 28014782, 27978559, 27942393, 27906282, 27870227, 27834229, 27798286, 27762398, 27726567, 27690791, 27655070, 27619404, 27583794, 27548239, 27512738, 27477293, 27441902, 27406566, 27371285, 27336058, 27300886, 27265767, 27230703, 27195693, 27160738, 27125836, 27090987, 27056193, 27021452, 26986765, 26952131, 26917550, 26883023, 26848548, 26814127, 26779759, 26745444, 26711181, 26676971, 26642813, 26608708, 26574656, 26540656, 26506707, 26472811, 26438967, 26405175, 26371435, 26337746, 26304109, 26270524, 26236990, 26203507, 26170076, 26136696, 26103367, 26070088]
private theorem words3857_eq : (List.range' 3857 64).map threshold = words3857 := by decide
private def words3921 : List Nat := [26036861, 26003685, 25970559, 25937484, 25904459, 25871485, 25838562, 25805688, 25772865, 25740092, 25707368, 25674695, 25642072, 25609498, 25576974, 25544499, 25512074, 25479698, 25447372, 25415095, 25382867, 25350687, 25318557, 25286476, 25254443, 25222460, 25190524, 25158638, 25126799, 25095009, 25063268, 25031574, 24999929, 24968331, 24936782, 24905280, 24873826, 24842419, 24811061, 24779749, 24748486, 24717269, 24686100, 24654978, 24623902, 24592874, 24561893, 24530959, 24500071, 24469230, 24438436, 24407688, 24376986, 24346331, 24315722, 24285160, 24254643, 24224172, 24193748, 24163369, 24133036, 24102748, 24072506, 24042310]
private theorem words3921_eq : (List.range' 3921 64).map threshold = words3921 := by decide
private def words3985 : List Nat := [24012159, 23982054, 23951993, 23921978, 23892008, 23862084, 23832204, 23802369, 23772578, 23742833, 23713132, 23683476, 23653864, 23624297, 23594774, 23565295, 23535861, 23506470, 23477124, 23447821, 23418563, 23389348, 23360177, 23331050, 23301966, 23272925, 23243928, 23214975, 23186065, 23157197, 23128373, 23099593, 23070855, 23042159, 23013507, 22984898, 22956331, 22927807, 22899325, 22870886, 22842489, 22814134, 22785822, 22757551, 22729323, 22701137, 22672993, 22644890, 22616830, 22588811, 22560834, 22532898, 22505004, 22477151, 22449340, 22421570, 22393841, 22366153, 22338506, 22310901, 22283336, 22255812, 22228329, 22200887]
private theorem words3985_eq : (List.range' 3985 64).map threshold = words3985 := by decide
private def words4049 : List Nat := [22173485, 22146124, 22118803, 22091523, 22064283, 22037084, 22009924, 21982805, 21955726, 21928687, 21901688, 21874729, 21847809, 21820929, 21794089, 21767289, 21740528, 21713807, 21687125, 21660482, 21633879, 21607315, 21580789, 21554303, 21527856, 21501448, 21475079, 21448749, 21422457, 21396204, 21369990, 21343814, 21317676, 21291577, 21265517, 21239494, 21213510, 21187564, 21161656, 21135786, 21109954, 21084160, 21058403, 21032685, 21007004, 20981361, 20955755, 20930187, 20904656, 20879162, 20853706, 20828287, 20802905, 20777561, 20752253, 20726982, 20701749, 20676552, 20651392, 20626268, 20601182, 20576132, 20551118, 20526141]
private theorem words4049_eq : (List.range' 4049 64).map threshold = words4049 := by decide
private def words4113 : List Nat := [20501200, 20476296, 20451428, 20426596, 20401801, 20377041, 20352318, 20327631, 20302979, 20278363, 20253784, 20229240, 20204731, 20180258, 20155821, 20131419, 20107053, 20082722, 20058427, 20034166, 20009941, 19985751, 19961596, 19937477, 19913392, 19889342, 19865327, 19841346, 19817401, 19793490, 19769613, 19745771, 19721964, 19698191, 19674453, 19650749, 19627079, 19603443, 19579842, 19556274, 19532741, 19509241, 19485776, 19462344, 19438946, 19415582, 19392252, 19368955, 19345692, 19322462, 19299266, 19276103, 19252973, 19229877, 19206814, 19183785, 19160788, 19137824, 19114894, 19091996, 19069132, 19046300, 19023501, 19000735]
private theorem words4113_eq : (List.range' 4113 64).map threshold = words4113 := by decide
private def words4177 : List Nat := [18978001, 18955300, 18932632, 18909996, 18887392, 18864821, 18842283, 18819776, 18797302, 18774861, 18752451, 18730073, 18707728, 18685414, 18663132, 18640883, 18618665, 18596478, 18574324, 18552201, 18530110, 18508050, 18486022, 18464025, 18442060, 18420126, 18398223, 18376352, 18354512, 18332703, 18310925, 18289178, 18267462, 18245777, 18224123, 18202499, 18180907, 18159345, 18137814, 18116314, 18094844, 18073404, 18051995, 18030617, 18009269, 17987951, 17966663, 17945406, 17924179, 17902982, 17881815, 17860678, 17839571, 17818494, 17797447, 17776430, 17755442, 17734485, 17713556, 17692658, 17671789, 17650950, 17630140, 17609359]
private theorem words4177_eq : (List.range' 4177 64).map threshold = words4177 := by decide
private def words4241 : List Nat := [17588608, 17567887, 17547194, 17526531, 17505897, 17485292, 17464716, 17444170, 17423652, 17403163, 17382703, 17362272, 17341870, 17321497, 17301152, 17280836, 17260548, 17240290, 17220059, 17199857, 17179684, 17159539, 17139422, 17119334, 17099274, 17079242, 17059238, 17039262, 17019315, 16999395, 16979503, 16959640, 16939804, 16919996, 16900216, 16880463, 16860738, 16841041, 16821372, 16801730, 16782115, 16762528, 16742969, 16723437, 16703932, 16684454, 16665004, 16645581, 16626185, 16606816, 16587474, 16568160, 16548872, 16529611, 16510377, 16491170, 16471990, 16452837, 16433710, 16414610, 16395536, 16376489, 16357469, 16338475]
private theorem words4241_eq : (List.range' 4241 64).map threshold = words4241 := by decide
private def words4305 : List Nat := [16319508, 16300567, 16281652, 16262764, 16243902, 16225067, 16206257, 16187474, 16168717, 16149985, 16131280, 16112601, 16093948, 16075321, 16056719, 16038144, 16019594, 16001070, 15982572, 15964099, 15945652, 15927230, 15908835, 15890464, 15872119, 15853799, 15835505, 15817236, 15798993, 15780774, 15762581, 15744413, 15726270, 15708152, 15690059, 15671992, 15653949, 15635931, 15617938, 15599970, 15582026, 15564108, 15546214, 15528345, 15510500, 15492680, 15474885, 15457114, 15439367, 15421646, 15403948, 15386275, 15368626, 15351001, 15333401, 15315825, 15298273, 15280745, 15263241, 15245762, 15228306, 15210875, 15193467, 15176083]
private theorem words4305_eq : (List.range' 4305 64).map threshold = words4305 := by decide
private def words4369 : List Nat := [15158723, 15141387, 15124074, 15106786, 15089521, 15072280, 15055062, 15037868, 15020698, 15003551, 14986427, 14969327, 14952251, 14935198, 14918168, 14901161, 14884178, 14867218, 14850281, 14833367, 14816476, 14799609, 14782764, 14765943, 14749144, 14732369, 14715616, 14698886, 14682179, 14665495, 14648833, 14632194, 14615578, 14598985, 14582414, 14565865, 14549339, 14532836, 14516355, 14499897, 14483461, 14467047, 14450656, 14434287, 14417940, 14401615, 14385312, 14369032, 14352774, 14336538, 14320324, 14304131, 14287961, 14271813, 14255687, 14239582, 14223500, 14207439, 14191400, 14175382, 14159387, 14143413, 14127460, 14111529]
private theorem words4369_eq : (List.range' 4369 64).map threshold = words4369 := by decide
private def words4433 : List Nat := [14095620, 14079732, 14063866, 14048021, 14032198, 14016396, 14000615, 13984856, 13969118, 13953401, 13937705, 13922031, 13906377, 13890745, 13875134, 13859544, 13843975, 13828427, 13812900, 13797394, 13781909, 13766444, 13751001, 13735578, 13720176, 13704794, 13689434, 13674094, 13658774, 13643475, 13628197, 13612939, 13597702, 13582485, 13567289, 13552113, 13536958, 13521822, 13506707, 13491613, 13476538, 13461484, 13446450, 13431436, 13416442, 13401469, 13386515, 13371581, 13356668, 13341774, 13326900, 13312046, 13297212, 13282398, 13267604, 13252829, 13238074, 13223339, 13208624, 13193928, 13179252, 13164595, 13149958, 13135340]
private theorem words4433_eq : (List.range' 4433 64).map threshold = words4433 := by decide
private def words4497 : List Nat := [13120742, 13106164, 13091604, 13077065, 13062544, 13048043, 13033561, 13019099, 13004656, 12990232, 12975827, 12961441, 12947075, 12932728, 12918399, 12904090, 12889800, 12875529, 12861276, 12847043, 12832828, 12818633, 12804456, 12790298, 12776159, 12762038, 12747937, 12733854, 12719789, 12705744, 12691717, 12677708, 12663718, 12649747, 12635794, 12621859, 12607943, 12594046, 12580166, 12566305, 12552463, 12538639, 12524832, 12511045, 12497275, 12483524, 12469790, 12456075, 12442378, 12428699, 12415038, 12401396, 12387771, 12374164, 12360575, 12347004, 12333450, 12319915, 12306397, 12292898, 12279416, 12265951, 12252505, 12239076]
private theorem words4497_eq : (List.range' 4497 64).map threshold = words4497 := by decide
private def words4561 : List Nat := [12225665, 12212271, 12198895, 12185537, 12172196, 12158872, 12145567, 12132278, 12119007, 12105754, 12092518, 12079299, 12066098, 12052913, 12039747, 12026597, 12013465, 12000350, 11987252, 11974171, 11961107, 11948061, 11935031, 11922019, 11909023, 11896045, 11883083, 11870139, 11857211, 11844300, 11831407, 11818529, 11805669, 11792826, 11779999, 11767189, 11754396, 11741620, 11728860, 11716117, 11703390, 11690680, 11677986, 11665309, 11652649, 11640005, 11627378, 11614767, 11602172, 11589594, 11577032, 11564486, 11551957, 11539444, 11526947, 11514467, 11502003, 11489555, 11477123, 11464707, 11452307, 11439924, 11427556, 11415205]
private theorem words4561_eq : (List.range' 4561 64).map threshold = words4561 := by decide
private def words4625 : List Nat := [11402870, 11390550, 11378247, 11365959, 11353687, 11341432, 11329192, 11316968, 11304760, 11292567, 11280391, 11268230, 11256085, 11243956, 11231842, 11219744, 11207661, 11195594, 11183543, 11171508, 11159487, 11147483, 11135494, 11123520, 11111562, 11099619, 11087692, 11075780, 11063883, 11052002, 11040136, 11028285, 11016450, 11004629, 10992824, 10981035, 10969260, 10957500, 10945756, 10934027, 10922313, 10910613, 10898929, 10887260, 10875606, 10863967, 10852343, 10840734, 10829139, 10817560, 10805995, 10794445, 10782910, 10771390, 10759885, 10748394, 10736918, 10725457, 10714010, 10702578, 10691161, 10679758, 10668370, 10656997]
private theorem words4625_eq : (List.range' 4625 64).map threshold = words4625 := by decide
private def words4689 : List Nat := [10645638, 10634293, 10622963, 10611648, 10600347, 10589060, 10577788, 10566530, 10555287, 10544058, 10532843, 10521643, 10510457, 10499285, 10488127, 10476984, 10465855, 10454740, 10443639, 10432552, 10421480, 10410421, 10399377, 10388347, 10377330, 10366328, 10355340, 10344366, 10333405, 10322459, 10311526, 10300608, 10289703, 10278812, 10267935, 10257072, 10246222, 10235387, 10224565, 10213757, 10202962, 10192181, 10181414, 10170661, 10159921, 10149194, 10138482, 10127783, 10117097, 10106425, 10095766, 10085121, 10074490, 10063872, 10053267, 10042676, 10032098, 10021533, 10010982, 10000444, 9989920, 9979408, 9968910, 9958426]
private theorem words4689_eq : (List.range' 4689 64).map threshold = words4689 := by decide
private def words4753 : List Nat := [9947954, 9937496, 9927051, 9916619, 9906200, 9895794, 9885402, 9875022, 9864656, 9854302, 9843962, 9833635, 9823321, 9813019, 9802731, 9792455, 9782193, 9771943, 9761707, 9751483, 9741272, 9731074, 9720888, 9710716, 9700556, 9690409, 9680275, 9670153, 9660044, 9649948, 9639865, 9629794, 9619735, 9609690, 9599657, 9589636, 9579628, 9569633, 9559650, 9549679, 9539721, 9529776, 9519843, 9509922, 9500014, 9490118, 9480235, 9470364, 9460505, 9450658, 9440824, 9431002, 9421193, 9411395, 9401610, 9391837, 9382076, 9372328, 9362591, 9352867, 9343155, 9333454, 9323766, 9314090]
private theorem words4753_eq : (List.range' 4753 64).map threshold = words4753 := by decide
private def words4817 : List Nat := [9304426, 9294775, 9285135, 9275507, 9265891, 9256287, 9246695, 9237115, 9227547, 9217990, 9208446, 9198913, 9189393, 9179884, 9170387, 9160901, 9151428, 9141966, 9132516, 9123078, 9113651, 9104236, 9094833, 9085441, 9076061, 9066693, 9057336, 9047991, 9038658, 9029336, 9020025, 9010726, 9001439, 8992163, 8982898, 8973645, 8964403, 8955173, 8945954, 8936747, 8927551, 8918366, 8909193, 8900030, 8890880, 8881740, 8872612, 8863495, 8854389, 8845295, 8836212, 8827140, 8818079, 8809029, 8799990, 8790963, 8781946, 8772941, 8763947, 8754964, 8745992, 8737031, 8728081, 8719142]
private theorem words4817_eq : (List.range' 4817 64).map threshold = words4817 := by decide
private def words4881 : List Nat := [8710214, 8701296, 8692390, 8683495, 8674611, 8665737, 8656875, 8648023, 8639183, 8630353, 8621534, 8612725, 8603928, 8595141, 8586365, 8577600, 8568846, 8560102, 8551369, 8542647, 8533935, 8525234, 8516544, 8507864, 8499195, 8490536, 8481888, 8473251, 8464624, 8456008, 8447402, 8438807, 8430222, 8421648, 8413084, 8404531, 8395988, 8387455, 8378933, 8370421, 8361920, 8353429, 8344949, 8336478, 8328018, 8319569, 8311129, 8302700, 8294281, 8285872, 8277474, 8269086, 8260708, 8252340, 8243982, 8235635, 8227298, 8218970, 8210653, 8202346, 8194049, 8185762, 8177486, 8169219]
private theorem words4881_eq : (List.range' 4881 64).map threshold = words4881 := by decide
private def words4945 : List Nat := [8160962, 8152715, 8144479, 8136252, 8128035, 8119828, 8111631, 8103444, 8095267, 8087100, 8078943, 8070796, 8062658, 8054530, 8046413, 8038305, 8030206, 8022118, 8014039, 8005970, 7997911, 7989862, 7981822, 7973792, 7965772, 7957761, 7949760, 7941769, 7933787, 7925815, 7917853, 7909900, 7901957, 7894023, 7886099, 7878184, 7870279, 7862384, 7854497, 7846621, 7838754, 7830896, 7823048, 7815209, 7807380, 7799560, 7791750, 7783949, 7776157, 7768374, 7760601, 7752838, 7745083, 7737338, 7729602, 7721876, 7714159, 7706451, 7698752, 7691062, 7683382, 7675711, 7668049, 7660396]
private theorem words4945_eq : (List.range' 4945 64).map threshold = words4945 := by decide
private def words5009 : List Nat := [7652753, 7645118, 7637493, 7629877, 7622270, 7614672, 7607083, 7599503, 7591932, 7584371, 7576818, 7569274, 7561740, 7554214, 7546698, 7539190, 7531691, 7524202, 7516721, 7509249, 7501786, 7494332, 7486887, 7479450, 7472023, 7464604, 7457194, 7449793, 7442401, 7435018, 7427643, 7420278, 7412921, 7405572, 7398233, 7390902, 7383580, 7376267, 7368962, 7361666, 7354379, 7347100, 7339830, 7332569, 7325316, 7318072, 7310836, 7303609, 7296391, 7289181, 7281979, 7274787, 7267602, 7260427, 7253259, 7246101, 7238950, 7231808, 7224675, 7217550, 7210434, 7203326, 7196226, 7189135]
private theorem words5009_eq : (List.range' 5009 64).map threshold = words5009 := by decide
private def words5073 : List Nat := [7182052, 7174977, 7167911, 7160853, 7153804, 7146763, 7139730, 7132705, 7125689, 7118681, 7111681, 7104690, 7097707, 7090732, 7083765, 7076807, 7069856, 7062914, 7055980, 7049054, 7042137, 7035227, 7028326, 7021433, 7014548, 7007671, 7000802, 6993941, 6987088, 6980243, 6973407, 6966578, 6959758, 6952945, 6946140, 6939344, 6932555, 6925774, 6919002, 6912237, 6905480, 6898731, 6891990, 6885257, 6878532, 6871815, 6865105, 6858404, 6851710, 6845024, 6838346, 6831676, 6825013, 6818358, 6811712, 6805073, 6798441, 6791818, 6785202, 6778594, 6771993, 6765401, 6758816, 6752238]
private theorem words5073_eq : (List.range' 5073 64).map threshold = words5073 := by decide
private def words5137 : List Nat := [6745669, 6739107, 6732553, 6726006, 6719467, 6712936, 6706412, 6699896, 6693387, 6686886, 6680393, 6673907, 6667429, 6660958, 6654495, 6648039, 6641591, 6635150, 6628717, 6622292, 6615873, 6609463, 6603059, 6596664, 6590275, 6583894, 6577521, 6571154, 6564796, 6558444, 6552100, 6545764, 6539434, 6533112, 6526798, 6520490, 6514190, 6507898, 6501612, 6495334, 6489063, 6482800, 6476543, 6470294, 6464053, 6457818, 6451591, 6445370, 6439157, 6432952, 6426753, 6420561, 6414377, 6408200, 6402030, 6395867, 6389711, 6383562, 6377421, 6371286, 6365159, 6359039, 6352925, 6346819]
private theorem words5137_eq : (List.range' 5137 64).map threshold = words5137 := by decide
private def words5201 : List Nat := [6340720, 6334628, 6328543, 6322465, 6316393, 6310329, 6304272, 6298222, 6292179, 6286143, 6280113, 6274091, 6268075, 6262067, 6256065, 6250071, 6244083, 6238102, 6232128, 6226161, 6220200, 6214247, 6208300, 6202360, 6196427, 6190501, 6184582, 6178669, 6172763, 6166864, 6160972, 6155087, 6149208, 6143336, 6137470, 6131612, 6125760, 6119915, 6114076, 6108244, 6102419, 6096601, 6090789, 6084984, 6079185, 6073393, 6067608, 6061829, 6056057, 6050292, 6044533, 6038781, 6033035, 6027296, 6021563, 6015837, 6010117, 6004404, 5998698, 5992998, 5987304, 5981617, 5975937, 5970263]
private theorem words5201_eq : (List.range' 5201 64).map threshold = words5201 := by decide
private def words5265 : List Nat := [5964595, 5958934, 5953279, 5947631, 5941989, 5936354, 5930725, 5925102, 5919486, 5913876, 5908273, 5902675, 5897085, 5891500, 5885922, 5880351, 5874785, 5869226, 5863674, 5858127, 5852587, 5847053, 5841526, 5836004, 5830489, 5824981, 5819478, 5813982, 5808492, 5803008, 5797530, 5792059, 5786594, 5781134, 5775682, 5770235, 5764794, 5759360, 5753932, 5748510, 5743094, 5737684, 5732280, 5726882, 5721491, 5716105, 5710726, 5705353, 5699986, 5694624, 5689269, 5683920, 5678577, 5673240, 5667909, 5662584, 5657265, 5651952, 5646645, 5641344, 5636049, 5630760, 5625477, 5620200]
private theorem words5265_eq : (List.range' 5265 64).map threshold = words5265 := by decide
private def words5329 : List Nat := [5614929, 5609663, 5604404, 5599150, 5593903, 5588661, 5583425, 5578196, 5572972, 5567753, 5562541, 5557335, 5552134, 5546939, 5541751, 5536567, 5531390, 5526219, 5521053, 5515893, 5510739, 5505591, 5500448, 5495312, 5490181, 5485055, 5479936, 5474822, 5469714, 5464612, 5459515, 5454424, 5449339, 5444259, 5439185, 5434117, 5429055, 5423998, 5418947, 5413901, 5408861, 5403827, 5398798, 5393775, 5388757, 5383746, 5378739, 5373739, 5368744, 5363754, 5358770, 5353792, 5348819, 5343851, 5338890, 5333933, 5328983, 5324037, 5319098, 5314163, 5309235, 5304311, 5299394, 5294481]
private theorem words5329_eq : (List.range' 5329 64).map threshold = words5329 := by decide
private def words5393 : List Nat := [5289575, 5284673, 5279777, 5274887, 5270002, 5265122, 5260248, 5255379, 5250516, 5245658, 5240805, 5235958, 5231116, 5226280, 5221448, 5216623, 5211802, 5206987, 5202178, 5197373, 5192574, 5187780, 5182992, 5178209, 5173431, 5168658, 5163891, 5159129, 5154373, 5149621, 5144875, 5140134, 5135398, 5130668, 5125943, 5121223, 5116508, 5111798, 5107094, 5102394, 5097700, 5093012, 5088328, 5083649, 5078976, 5074308, 5069645, 5064987, 5060334, 5055687, 5051044, 5046407, 5041775, 5037147, 5032525, 5027908, 5023296, 5018690, 5014088, 5009491, 5004899, 5000313, 4995731, 4991155]
private theorem words5393_eq : (List.range' 5393 64).map threshold = words5393 := by decide
private def words5457 : List Nat := [4986583, 4982017, 4977455, 4972899, 4968347, 4963801, 4959260, 4954723, 4950192, 4945665, 4941144, 4936627, 4932115, 4927609, 4923107, 4918610, 4914118, 4909631, 4905149, 4900672, 4896200, 4891733, 4887270, 4882812, 4878360, 4873912, 4869469, 4865031, 4860598, 4856169, 4851746, 4847327, 4842913, 4838504, 4834100, 4829700, 4825306, 4820916, 4816531, 4812151, 4807775, 4803405, 4799039, 4794677, 4790321, 4785969, 4781622, 4777280, 4772943, 4768610, 4764282, 4759959, 4755640, 4751326, 4747017, 4742712, 4738413, 4734117, 4729827, 4725541, 4721260, 4716984, 4712712, 4708444]
private theorem words5457_eq : (List.range' 5457 64).map threshold = words5457 := by decide
private def words5521 : List Nat := [4704182, 4699924, 4695671, 4691422, 4687178, 4682938, 4678703, 4674473, 4670247, 4666026, 4661810, 4657598, 4653390, 4649188, 4644989, 4640796, 4636606, 4632422, 4628242, 4624066, 4619895, 4615728, 4611566, 4607409, 4603256, 4599107, 4594963, 4590823, 4586688, 4582558, 4578431, 4574310, 4570192, 4566079, 4561971, 4557867, 4553768, 4549672, 4545582, 4541495, 4537414, 4533336, 4529263, 4525194, 4521130, 4517070, 4513015, 4508963, 4504917, 4500874, 4496836, 4492802, 4488773, 4484748, 4480727, 4476711, 4472698, 4468691, 4464687, 4460688, 4456693, 4452702, 4448716, 4444734]
private theorem words5521_eq : (List.range' 5521 64).map threshold = words5521 := by decide
private def words5585 : List Nat := [4440756, 4436783, 4432814, 4428849, 4424888, 4420932, 4416979, 4413031, 4409088, 4405148, 4401213, 4397282, 4393355, 4389432, 4385514, 4381600, 4377690, 4373784, 4369882, 4365985, 4362091, 4358202, 4354317, 4350436, 4346560, 4342687, 4338819, 4334954, 4331094, 4327238, 4323386, 4319538, 4315695, 4311855, 4308020, 4304188, 4300361, 4296538, 4292719, 4288904, 4285093, 4281286, 4277483, 4273684, 4269889, 4266098, 4262312, 4258529, 4254750, 4250976, 4247205, 4243439, 4239676, 4235917, 4232163, 4228412, 4224666, 4220923, 4217184, 4213450, 4209719, 4205992, 4202270, 4198551]
private theorem words5585_eq : (List.range' 5585 64).map threshold = words5585 := by decide
private def words5649 : List Nat := [4194836, 4191125, 4187418, 4183715, 4180016, 4176320, 4172629, 4168942, 4165258, 4161579, 4157903, 4154231, 4150564, 4146900, 4143239, 4139583, 4135931, 4132282, 4128638, 4124997, 4121360, 4117727, 4114098, 4110472, 4106851, 4103233, 4099619, 4096009, 4092403, 4088800, 4085202, 4081607, 4078016, 4074428, 4070845, 4067265, 4063689, 4060117, 4056549, 4052984, 4049423, 4045866, 4042313, 4038763, 4035217, 4031675, 4028137, 4024602, 4021071, 4017544, 4014020, 4010500, 4006984, 4003472, 3999963, 3996458, 3992957, 3989459, 3985965, 3982475, 3978988, 3975505, 3972026, 3968550]
private theorem words5649_eq : (List.range' 5649 64).map threshold = words5649 := by decide
private def words5713 : List Nat := [3965078, 3961609, 3958145, 3954684, 3951226, 3947772, 3944322, 3940875, 3937432, 3933993, 3930557, 3927125, 3923696, 3920271, 3916850, 3913432, 3910018, 3906607, 3903200, 3899796, 3896396, 3893000, 3889607, 3886218, 3882832, 3879450, 3876071, 3872696, 3869324, 3865956, 3862591, 3859230, 3855873, 3852518, 3849168, 3845821, 3842477, 3839137, 3835800, 3832467, 3829138, 3825811, 3822489, 3819169, 3815854, 3812541, 3809232, 3805927, 3802625, 3799326, 3796031, 3792739, 3789451, 3786166, 3782885, 3779606, 3776332, 3773061, 3769793, 3766528, 3763267, 3760010, 3756755, 3753504]
private theorem words5713_eq : (List.range' 5713 64).map threshold = words5713 := by decide
private def words5777 : List Nat := [3750257, 3747013, 3743772, 3740534, 3737300, 3734070, 3730842, 3727618, 3724397, 3721180, 3717966, 3714755, 3711548, 3708344, 3705143, 3701946, 3698752, 3695561, 3692374, 3689189, 3686009, 3682831, 3679657, 3676486, 3673318, 3670153, 3666992, 3663834, 3660680, 3657528, 3654380, 3651235, 3648093, 3644955, 3641820, 3638688, 3635559, 3632434, 3629311, 3626192, 3623077, 3619964, 3616855, 3613748, 3610645, 3607546, 3604449, 3601356, 3598265, 3595178, 3592094, 3589014, 3585936, 3582862, 3579791, 3576723, 3573658, 3570596, 3567537, 3564482, 3561430, 3558381, 3555334, 3552292]
private theorem words5777_eq : (List.range' 5777 64).map threshold = words5777 := by decide
private def words5841 : List Nat := [3549252, 3546215, 3543182, 3540151, 3537124, 3534100, 3531078, 3528060, 3525046, 3522034, 3519025, 3516019, 3513017, 3510017, 3507021, 3504027, 3501037, 3498050, 3495066, 3492085, 3489107, 3486132, 3483160, 3480191, 3477225, 3474262, 3471302, 3468345, 3465391, 3462441, 3459493, 3456548, 3453606, 3450668, 3447732, 3444799, 3441869, 3438943, 3436019, 3433098, 3430180, 3427265, 3424354, 3421445, 3418539, 3415636, 3412736, 3409839, 3406945, 3404053, 3401165, 3398280, 3395398, 3392518, 3389642, 3386768, 3383898, 3381030, 3378165, 3375303, 3372444, 3369588, 3366735, 3363885]
private theorem words5841_eq : (List.range' 5841 64).map threshold = words5841 := by decide
private def words5905 : List Nat := [3361037, 3358193, 3355351, 3352513, 3349677, 3346844, 3344014, 3341186, 3338362, 3335541, 3332722, 3329906, 3327093, 3324283, 3321476, 3318672, 3315870, 3313072, 3310276, 3307483, 3304693, 3301905, 3299121, 3296339, 3293560, 3290784, 3288011, 3285240, 3282473, 3279708, 3276946, 3274186, 3271430, 3268676, 3265925, 3263177, 3260431, 3257689, 3254949, 3252212, 3249478, 3246746, 3244017, 3241291, 3238568, 3235847, 3233129, 3230414, 3227702, 3224992, 3222285, 3219581, 3216880, 3214181, 3211485, 3208792, 3206101, 3203413, 3200728, 3198046, 3195366, 3192689, 3190014, 3187343]
private theorem words5905_eq : (List.range' 5905 64).map threshold = words5905 := by decide
private def words5969 : List Nat := [3184674, 3182007, 3179344, 3176683, 3174024, 3171369, 3168716, 3166066, 3163418, 3160773, 3158131, 3155491, 3152854, 3150219, 3147588, 3144958, 3142332, 3139708, 3137087, 3134468, 3131852, 3129239, 3126628, 3124020, 3121415, 3118812, 3116211, 3113614, 3111019, 3108426, 3105836, 3103249, 3100664, 3098082, 3095502, 3092925, 3090351, 3087779, 3085210, 3082643, 3080079, 3077517, 3074958, 3072402, 3069848, 3067296, 3064747, 3062201, 3059657, 3057116, 3054577, 3052041, 3049507, 3046976, 3044448, 3041922, 3039398, 3036877, 3034358, 3031842, 3029329, 3026818, 3024309, 3021803]
private theorem words5969_eq : (List.range' 5969 64).map threshold = words5969 := by decide
private def words6033 : List Nat := [3019300, 3016799, 3014300, 3011804, 3009310, 3006819, 3004330, 3001844, 2999360, 2996879, 2994400, 2991924, 2989450, 2986979, 2984510, 2982043, 2979579, 2977117, 2974658, 2972201, 2969747, 2967295, 2964846, 2962399, 2959954, 2957512, 2955072, 2952635, 2950200, 2947767, 2945337, 2942909, 2940484, 2938061, 2935640, 2933222, 2930807, 2928393, 2925982, 2923574, 2921167, 2918763, 2916362, 2913963, 2911566, 2909172, 2906780, 2904390, 2902003, 2899618, 2897235, 2894855, 2892477, 2890102, 2887728, 2885357, 2882989, 2880623, 2878259, 2875897, 2873538, 2871181, 2868827, 2866474]
private theorem words6033_eq : (List.range' 6033 64).map threshold = words6033 := by decide
private def words6097 : List Nat := [2864124, 2861777, 2859431, 2857088, 2854748, 2852409, 2850073, 2847739, 2845408, 2843078, 2840751, 2838427, 2836104, 2833784, 2831466, 2829151, 2826838, 2824527, 2822218, 2819911, 2817607, 2815305, 2813005, 2810708, 2808413, 2806120, 2803829, 2801541, 2799254, 2796970, 2794689, 2792409, 2790132, 2787857, 2785584, 2783313, 2781045, 2778779, 2776515, 2774253, 2771994, 2769736, 2767481, 2765228, 2762978, 2760729, 2758483, 2756239, 2753997, 2751757, 2749519, 2747284, 2745051, 2742820, 2740591, 2738364, 2736140, 2733917, 2731697, 2729479, 2727263, 2725050, 2722838, 2720629]
private theorem words6097_eq : (List.range' 6097 64).map threshold = words6097 := by decide
private def words6161 : List Nat := [2718421, 2716216, 2714013, 2711813, 2709614, 2707418, 2705223, 2703031, 2700841, 2698653, 2696467, 2694283, 2692102, 2689922, 2687745, 2685570, 2683396, 2681225, 2679056, 2676890, 2674725, 2672562, 2670402, 2668243, 2666087, 2663933, 2661781, 2659631, 2657483, 2655337, 2653193, 2651051, 2648911, 2646774, 2644638, 2642505, 2640373, 2638244, 2636117, 2633992, 2631868, 2629747, 2627628, 2625511, 2623396, 2621283, 2619173, 2617064, 2614957, 2612852, 2610749, 2608649, 2606550, 2604453, 2602359, 2600266, 2598176, 2596087, 2594001, 2591916, 2589833, 2587753, 2585674, 2583598]
private theorem words6161_eq : (List.range' 6161 64).map threshold = words6161 := by decide
private def words6225 : List Nat := [2581523, 2579451, 2577380, 2575312, 2573245, 2571181, 2569118, 2567058, 2564999, 2562942, 2560888, 2558835, 2556784, 2554736, 2552689, 2550644, 2548601, 2546561, 2544522, 2542485, 2540450, 2538417, 2536386, 2534357, 2532330, 2530304, 2528281, 2526260, 2524240, 2522223, 2520207, 2518194, 2516182, 2514172, 2512165, 2510159, 2508155, 2506153, 2504153, 2502154, 2500158, 2498164, 2496171, 2494181, 2492192, 2490205, 2488220, 2486237, 2484256, 2482277, 2480300, 2478324, 2476351, 2474379, 2472410, 2470442, 2468476, 2466512, 2464549, 2462589, 2460631, 2458674, 2456719, 2454766]
private theorem words6225_eq : (List.range' 6225 64).map threshold = words6225 := by decide
private def words6289 : List Nat := [2452815, 2450866, 2448919, 2446974, 2445030, 2443088, 2441148, 2439210, 2437274, 2435340, 2433407, 2431477, 2429548, 2427621, 2425696, 2423772, 2421851, 2419931, 2418013, 2416097, 2414183, 2412271, 2410360, 2408451, 2406544, 2404639, 2402736, 2400835, 2398935, 2397037, 2395141, 2393247, 2391354, 2389463, 2387574, 2385687, 2383802, 2381919, 2380037, 2378157, 2376279, 2374402, 2372528, 2370655, 2368784, 2366914, 2365047, 2363181, 2361317, 2359455, 2357594, 2355736, 2353879, 2352023, 2350170, 2348318, 2346468, 2344620, 2342774, 2340929, 2339086, 2337245, 2335405, 2333568]
private theorem words6289_eq : (List.range' 6289 64).map threshold = words6289 := by decide
private def words6353 : List Nat := [2331732, 2329897, 2328065, 2326234, 2324405, 2322578, 2320752, 2318928, 2317106, 2315285, 2313467, 2311649, 2309834, 2308021, 2306209, 2304398, 2302590, 2300783, 2298978, 2297175, 2295373, 2293573, 2291775, 2289978, 2288183, 2286390, 2284598, 2282808, 2281020, 2279234, 2277449, 2275666, 2273884, 2272104, 2270326, 2268550, 2266775, 2265002, 2263230, 2261461, 2259692, 2257926, 2256161, 2254398, 2252636, 2250876, 2249118, 2247362, 2245607, 2243853, 2242102, 2240352, 2238603, 2236857, 2235112, 2233368, 2231626, 2229886, 2228148, 2226411, 2224675, 2222942, 2221210, 2219479]
private theorem words6353_eq : (List.range' 6353 64).map threshold = words6353 := by decide
private def words6417 : List Nat := [2217750, 2216023, 2214297, 2212573, 2210851, 2209130, 2207411, 2205694, 2203978, 2202263, 2200551, 2198839, 2197130, 2195422, 2193715, 2192011, 2190307, 2188606, 2186906, 2185207, 2183511, 2181815, 2180122, 2178429, 2176739, 2175050, 2173363, 2171677, 2169992, 2168310, 2166629, 2164949, 2163271, 2161595, 2159920, 2158247, 2156575, 2154905, 2153236, 2151569, 2149903, 2148239, 2146577, 2144916, 2143256, 2141599, 2139942, 2138288, 2136634, 2134983, 2133332, 2131684, 2130037, 2128391, 2126747, 2125105, 2123464, 2121824, 2120186, 2118550, 2116915, 2115281, 2113649, 2112019]
private theorem words6417_eq : (List.range' 6417 64).map threshold = words6417 := by decide
private def words6481 : List Nat := [2110390, 2108763, 2107137, 2105512, 2103890, 2102268, 2100648, 2099030, 2097413, 2095798, 2094184, 2092571, 2090960, 2089351, 2087743, 2086137, 2084532, 2082928, 2081326, 2079726, 2078127, 2076529, 2074933, 2073338, 2071745, 2070153, 2068563, 2066974, 2065387, 2063801, 2062217, 2060634, 2059053, 2057473, 2055894, 2054317, 2052741, 2051167, 2049594, 2048023, 2046453, 2044885, 2043318, 2041752, 2040188, 2038626, 2037064, 2035505, 2033946, 2032389, 2030834, 2029280, 2027727, 2026176, 2024626, 2023078, 2021531, 2019986, 2018441, 2016899, 2015357, 2013818, 2012279, 2010742]
private theorem words6481_eq : (List.range' 6481 64).map threshold = words6481 := by decide
private def words6545 : List Nat := [2009207, 2007672, 2006140, 2004608, 2003078, 2001550, 2000022, 1998497, 1996972, 1995449, 1993927, 1992407, 1990888, 1989371, 1987855, 1986340, 1984827, 1983315, 1981805, 1980295, 1978788, 1977281, 1975776, 1974273, 1972770, 1971269, 1969770, 1968272, 1966775, 1965280, 1963786, 1962293, 1960802, 1959312, 1957823, 1956336, 1954850, 1953365, 1951882, 1950400, 1948920, 1947441, 1945963, 1944486, 1943011, 1941537, 1940065, 1938594, 1937124, 1935656, 1934189, 1932723, 1931259, 1929795, 1928334, 1926873, 1925414, 1923956, 1922500, 1921045, 1919591, 1918139, 1916687, 1915238]
private theorem words6545_eq : (List.range' 6545 64).map threshold = words6545 := by decide
private def words6609 : List Nat := [1913789, 1912342, 1910896, 1909451, 1908008, 1906566, 1905126, 1903686, 1902248, 1900811, 1899376, 1897942, 1896509, 1895077, 1893647, 1892218, 1890791, 1889364, 1887939, 1886515, 1885093, 1883672, 1882252, 1880833, 1879416, 1878000, 1876585, 1875171, 1873759, 1872348, 1870938, 1869530, 1868123, 1866717, 1865312, 1863909, 1862507, 1861106, 1859707, 1858308, 1856911, 1855516, 1854121, 1852728, 1851336, 1849945, 1848556, 1847167, 1845781, 1844395, 1843010, 1841627, 1840245, 1838864, 1837485, 1836107, 1834730, 1833354, 1831979, 1830606, 1829234, 1827863, 1826494, 1825125]
private theorem words6609_eq : (List.range' 6609 64).map threshold = words6609 := by decide
private def words6673 : List Nat := [1823758, 1822392, 1821027, 1819664, 1818302, 1816941, 1815581, 1814222, 1812865, 1811509, 1810154, 1808800, 1807448, 1806097, 1804747, 1803398, 1802050, 1800704, 1799358, 1798014, 1796672, 1795330, 1793990, 1792650, 1791312, 1789976, 1788640, 1787306, 1785972, 1784640, 1783310, 1781980, 1780651, 1779324, 1777998, 1776673, 1775350, 1774027, 1772706, 1771386, 1770067, 1768749, 1767432, 1766117, 1764802, 1763489, 1762177, 1760867, 1759557, 1758249, 1756941, 1755635, 1754330, 1753027, 1751724, 1750423, 1749122, 1747823, 1746525, 1745229, 1743933, 1742638, 1741345, 1740053]
private theorem words6673_eq : (List.range' 6673 64).map threshold = words6673 := by decide
private def words6737 : List Nat := [1738762, 1737472, 1736183, 1734896, 1733609, 1732324, 1731040, 1729757, 1728475, 1727194, 1725915, 1724636, 1723359, 1722083, 1720808, 1719534, 1718261, 1716989, 1715719, 1714449, 1713181, 1711914, 1710648, 1709383, 1708119, 1706856, 1705595, 1704335, 1703075, 1701817, 1700560, 1699304, 1698049, 1696795, 1695543, 1694291, 1693041, 1691792, 1690543, 1689296, 1688050, 1686806, 1685562, 1684319, 1683078, 1681837, 1680598, 1679359, 1678122, 1676886, 1675651, 1674417, 1673184, 1671953, 1670722, 1669492, 1668264, 1667037, 1665810, 1664585, 1663361, 1662138, 1660916, 1659695]
private theorem words6737_eq : (List.range' 6737 64).map threshold = words6737 := by decide
private def words6801 : List Nat := [1658475, 1657256, 1656039, 1654822, 1653607, 1652392, 1651179, 1649966, 1648755, 1647545, 1646336, 1645128, 1643921, 1642715, 1641510, 1640306, 1639103, 1637902, 1636701, 1635502, 1634303, 1633106, 1631909, 1630714, 1629519, 1628326, 1627134, 1625943, 1624753, 1623564, 1622376, 1621189, 1620003, 1618818, 1617634, 1616451, 1615269, 1614089, 1612909, 1611730, 1610553, 1609376, 1608200, 1607026, 1605852, 1604680, 1603508, 1602338, 1601168, 1600000, 1598833, 1597666, 1596501, 1595337, 1594173, 1593011, 1591850, 1590690, 1589530, 1588372, 1587215, 1586059, 1584904, 1583749]
private theorem words6801_eq : (List.range' 6801 64).map threshold = words6801 := by decide
private def words6865 : List Nat := [1582596, 1581444, 1580293, 1579143, 1577994, 1576846, 1575698, 1574552, 1573407, 1572263, 1571120, 1569978, 1568837, 1567696, 1566557, 1565419, 1564282, 1563146, 1562011, 1560876, 1559743, 1558611, 1557480, 1556350, 1555220, 1554092, 1552965, 1551838, 1550713, 1549589, 1548465, 1547343, 1546222, 1545101, 1543982, 1542863, 1541746, 1540629, 1539513, 1538399, 1537285, 1536172, 1535061, 1533950, 1532840, 1531731, 1530623, 1529517, 1528411, 1527306, 1526202, 1525099, 1523996, 1522895, 1521795, 1520696, 1519598, 1518500, 1517404, 1516308, 1515214, 1514120, 1513028, 1511936]
private theorem words6865_eq : (List.range' 6865 64).map threshold = words6865 := by decide
private def words6929 : List Nat := [1510845, 1509756, 1508667, 1507579, 1506492, 1505406, 1504321, 1503237, 1502154, 1501071, 1499990, 1498910, 1497830, 1496752, 1495674, 1494598, 1493522, 1492447, 1491373, 1490300, 1489228, 1488157, 1487087, 1486018, 1484950, 1483882, 1482816, 1481750, 1480685, 1479622, 1478559, 1477497, 1476436, 1475376, 1474317, 1473259, 1472201, 1471145, 1470090, 1469035, 1467981, 1466929, 1465877, 1464826, 1463776, 1462726, 1461678, 1460631, 1459584, 1458539, 1457494, 1456450, 1455408, 1454366, 1453325, 1452284, 1451245, 1450207, 1449169, 1448133, 1447097, 1446062, 1445028, 1443995]
private theorem words6929_eq : (List.range' 6929 64).map threshold = words6929 := by decide
private def words6993 : List Nat := [1442963, 1441932, 1440901, 1439872, 1438843, 1437815, 1436789, 1435763, 1434738, 1433713, 1432690, 1431667, 1430646, 1429625, 1428605, 1427586, 1426568, 1425551, 1424535, 1423519, 1422504, 1421491, 1420478, 1419466, 1418455, 1417444, 1416435, 1415426, 1414419, 1413412, 1412406, 1411401, 1410396, 1409393, 1408390, 1407389, 1406388, 1405388, 1404389, 1403390, 1402393, 1401396, 1400401, 1399406, 1398412, 1397419, 1396426, 1395435, 1394444, 1393454, 1392465, 1391477, 1390490, 1389504, 1388518, 1387533, 1386549, 1385566, 1384584, 1383602, 1382622, 1381642, 1380663, 1379685]
private theorem words6993_eq : (List.range' 6993 64).map threshold = words6993 := by decide
private def words7057 : List Nat := [1378708, 1377731, 1376756, 1375781, 1374807, 1373834, 1372862, 1371890, 1370920, 1369950, 1368981, 1368013, 1367045, 1366079, 1365113, 1364148, 1363184, 1362221, 1361259, 1360297, 1359336, 1358376, 1357417, 1356459, 1355501, 1354544, 1353588, 1352633, 1351679, 1350726, 1349773, 1348821, 1347870, 1346920, 1345970, 1345021, 1344074, 1343127, 1342180, 1341235, 1340290, 1339346, 1338403, 1337461, 1336519, 1335579, 1334639, 1333700, 1332761, 1331824, 1330887, 1329951, 1329016, 1328082, 1327148, 1326216, 1325284, 1324352, 1323422, 1322492, 1321563, 1320635, 1319708, 1318782]
private theorem words7057_eq : (List.range' 7057 64).map threshold = words7057 := by decide
private def words7121 : List Nat := [1317856, 1316931, 1316007, 1315083, 1314161, 1313239, 1312318, 1311398, 1310478, 1309559, 1308641, 1307724, 1306808, 1305892, 1304977, 1304063, 1303150, 1302237, 1301325, 1300414, 1299504, 1298595, 1297686, 1296778, 1295871, 1294964, 1294059, 1293154, 1292249, 1291346, 1290443, 1289541, 1288640, 1287740, 1286840, 1285941, 1285043, 1284146, 1283249, 1282353, 1281458, 1280564, 1279670, 1278777, 1277885, 1276994, 1276103, 1275213, 1274324, 1273436, 1272548, 1271661, 1270775, 1269890, 1269005, 1268121, 1267238, 1266355, 1265474, 1264593, 1263712, 1262833, 1261954, 1261076]
private theorem words7121_eq : (List.range' 7121 64).map threshold = words7121 := by decide
private def words7185 : List Nat := [1260199, 1259322, 1258446, 1257571, 1256697, 1255823, 1254950, 1254078, 1253206, 1252335, 1251465, 1250596, 1249728, 1248860, 1247992, 1247126, 1246260, 1245395, 1244531, 1243668, 1242805, 1241943, 1241081, 1240221, 1239361, 1238501, 1237643, 1236785, 1235928, 1235072, 1234216, 1233361, 1232507, 1231653, 1230800, 1229948, 1229097, 1228246, 1227396, 1226547, 1225698, 1224850, 1224003, 1223157, 1222311, 1221466, 1220622, 1219778, 1218935, 1218093, 1217251, 1216410, 1215570, 1214731, 1213892, 1213054, 1212216, 1211380, 1210544, 1209708, 1208874, 1208040, 1207206, 1206374]
private theorem words7185_eq : (List.range' 7185 64).map threshold = words7185 := by decide
private def words7249 : List Nat := [1205542, 1204711, 1203880, 1203051, 1202221, 1201393, 1200565, 1199738, 1198912, 1198086, 1197261, 1196437, 1195613, 1194790, 1193968, 1193146, 1192325, 1191505, 1190685, 1189867, 1189048, 1188231, 1187414, 1186598, 1185782, 1184967, 1184153, 1183340, 1182527, 1181715, 1180903, 1180092, 1179282, 1178473, 1177664, 1176856, 1176048, 1175241, 1174435, 1173630, 1172825, 1172020, 1171217, 1170414, 1169612, 1168810, 1168009, 1167209, 1166410, 1165611, 1164812, 1164015, 1163218, 1162422, 1161626, 1160831, 1160037, 1159243, 1158450, 1157658, 1156866, 1156075, 1155284, 1154495]
private theorem words7249_eq : (List.range' 7249 64).map threshold = words7249 := by decide
private def words7313 : List Nat := [1153706, 1152917, 1152129, 1151342, 1150555, 1149770, 1148984, 1148200, 1147416, 1146632, 1145850, 1145068, 1144286, 1143506, 1142725, 1141946, 1141167, 1140389, 1139611, 1138834, 1138058, 1137282, 1136507, 1135733, 1134959, 1134186, 1133414, 1132642, 1131870, 1131100, 1130330, 1129561, 1128792, 1128024, 1127256, 1126489, 1125723, 1124958, 1124193, 1123428, 1122665, 1121901, 1121139, 1120377, 1119616, 1118855, 1118095, 1117336, 1116577, 1115819, 1115062, 1114305, 1113548, 1112793, 1112038, 1111283, 1110529, 1109776, 1109024, 1108272, 1107520, 1106769, 1106019, 1105270]
private theorem words7313_eq : (List.range' 7313 64).map threshold = words7313 := by decide
private def words7377 : List Nat := [1104521, 1103773, 1103025, 1102278, 1101531, 1100785, 1100040, 1099295, 1098551, 1097808, 1097065, 1096323, 1095581, 1094840, 1094100, 1093360, 1092620, 1091882, 1091144, 1090406, 1089669, 1088933, 1088197, 1087462, 1086728, 1085994, 1085261, 1084528, 1083796, 1083064, 1082334, 1081603, 1080873, 1080144, 1079416, 1078688, 1077960, 1077234, 1076508, 1075782, 1075057, 1074332, 1073609, 1072885, 1072163, 1071441, 1070719, 1069998, 1069278, 1068558, 1067839, 1067120, 1066402, 1065685, 1064968, 1064252, 1063536, 1062821, 1062106, 1061392, 1060679, 1059966, 1059254, 1058542]
private theorem words7377_eq : (List.range' 7377 64).map threshold = words7377 := by decide
private def words7441 : List Nat := [1057831, 1057121, 1056411, 1055701, 1054992, 1054284, 1053576, 1052869, 1052163, 1051457, 1050752, 1050047, 1049342, 1048639, 1047936, 1047233, 1046531, 1045830, 1045129, 1044428, 1043729, 1043030, 1042331, 1041633, 1040935, 1040238, 1039542, 1038846, 1038151, 1037456, 1036762, 1036069, 1035376, 1034683, 1033991, 1033300, 1032609, 1031919, 1031229, 1030540, 1029851, 1029163, 1028476, 1027789, 1027103, 1026417, 1025731, 1025047, 1024363, 1023679, 1022996, 1022313, 1021631, 1020950, 1020269, 1019589, 1018909, 1018229, 1017551, 1016873, 1016195, 1015518, 1014841, 1014165]
private theorem words7441_eq : (List.range' 7441 64).map threshold = words7441 := by decide
private def words7505 : List Nat := [1013490, 1012815, 1012140, 1011467, 1010793, 1010120, 1009448, 1008776, 1008105, 1007435, 1006765, 1006095, 1005426, 1004757, 1004089, 1003422, 1002755, 1002089, 1001423, 1000758, 1000093, 999429, 998765, 998102, 997439, 996777, 996115, 995454, 994794, 994134, 993474, 992815, 992157, 991499, 990841, 990184, 989528, 988872, 988217, 987562, 986908, 986254, 985601, 984948, 984296, 983644, 982993, 982342, 981692, 981043, 980394, 979745, 979097, 978449, 977802, 977156, 976510, 975864, 975219, 974575, 973931, 973288, 972645, 972002]
private theorem words7505_eq : (List.range' 7505 64).map threshold = words7505 := by decide
private def words7569 : List Nat := [971360, 970719, 970078, 969437, 968798, 968158, 967519, 966881, 966243, 965606, 964969, 964333, 963697, 963061, 962426, 961792, 961158, 960525, 959892, 959260, 958628, 957997, 957366, 956735, 956106, 955476, 954847, 954219, 953591, 952964, 952337, 951711, 951085, 950459, 949834, 949210, 948586, 947963, 947340, 946717, 946095, 945474, 944853, 944232, 943613, 942993, 942374, 941755, 941137, 940520, 939903, 939286, 938670, 938055, 937439, 936825, 936211, 935597, 934984, 934371, 933759, 933147, 932536, 931925]
private theorem words7569_eq : (List.range' 7569 64).map threshold = words7569 := by decide
private def words7633 : List Nat := [931315, 930705, 930096, 929487, 928878, 928271, 927663, 927056, 926450, 925844, 925238, 924633, 924029, 923424, 922821, 922218, 921615, 921013, 920411, 919810, 919209, 918609, 918009, 917409, 916811, 916212, 915614, 915017, 914420, 913823, 913227, 912631, 912036, 911441, 910847, 910253, 909660, 909067, 908475, 907883, 907292, 906701, 906110, 905520, 904930, 904341, 903752, 903164, 902576, 901989, 901402, 900816, 900230, 899645, 899060, 898475, 897891, 897307, 896724, 896141, 895559, 894977, 894396, 893815]
private theorem words7633_eq : (List.range' 7633 64).map threshold = words7633 := by decide
private def words7697 : List Nat := [893234, 892654, 892075, 891496, 890917, 890339, 889761, 889184, 888607, 888030, 887454, 886879, 886304, 885729, 885155, 884581, 884008, 883435, 882863, 882291, 881719, 881148, 880578, 880007, 879438, 878868, 878300, 877731, 877163, 876596, 876029, 875462, 874896, 874330, 873765, 873200, 872635, 872071, 871508, 870945, 870382, 869820, 869258, 868696, 868135, 867575, 867015, 866455, 865896, 865337, 864779, 864221, 863663, 863106, 862550, 861994, 861438, 860882, 860328, 859773, 859219, 858665, 858112, 857559]
private theorem words7697_eq : (List.range' 7697 64).map threshold = words7697 := by decide
private def words7761 : List Nat := [857007, 856455, 855904, 855353, 854802, 854252, 853702, 853153, 852604, 852055, 851507, 850959, 850412, 849865, 849319, 848773, 848227, 847682, 847138, 846593, 846049, 845506, 844963, 844420, 843878, 843336, 842795, 842254, 841714, 841173, 840634, 840094, 839556, 839017, 838479, 837941, 837404, 836867, 836331, 835795, 835260, 834724, 834190, 833655, 833121, 832588, 832055, 831522, 830990, 830458, 829927, 829395, 828865, 828335, 827805, 827275, 826746, 826218, 825690, 825162, 824634, 824107, 823581, 823055]
private theorem words7761_eq : (List.range' 7761 64).map threshold = words7761 := by decide
private def words7825 : List Nat := [822529, 822003, 821478, 820954, 820430, 819906, 819383, 818860, 818337, 817815, 817293, 816772, 816251, 815730, 815210, 814690, 814171, 813652, 813133, 812615, 812097, 811580, 811063, 810546, 810030, 809514, 808999, 808484, 807969, 807455, 806941, 806428, 805915, 805402, 804890, 804378, 803866, 803355, 802845, 802334, 801824, 801315, 800806, 800297, 799788, 799280, 798773, 798266, 797759, 797252, 796746, 796241, 795735, 795230, 794726, 794222, 793718, 793215, 792712, 792209, 791707, 791205, 790703, 790202]
private theorem words7825_eq : (List.range' 7825 64).map threshold = words7825 := by decide
private def words7889 : List Nat := [789702, 789201, 788701, 788202, 787703, 787204, 786705, 786207, 785710, 785212, 784716, 784219, 783723, 783227, 782732, 782237, 781742, 781248, 780754, 780260, 779767, 779274, 778782, 778290, 777798, 777307, 776816, 776326, 775835, 775346, 774856, 774367, 773878, 773390, 772902, 772415, 771927, 771441, 770954, 770468, 769982, 769497, 769012, 768527, 768043, 767559, 767076, 766592, 766110, 765627, 765145, 764663, 764182, 763701, 763221, 762740, 762260, 761781, 761302, 760823, 760344, 759866, 759389, 758911]
private theorem words7889_eq : (List.range' 7889 64).map threshold = words7889 := by decide
private def words7953 : List Nat := [758434, 757958, 757481, 757005, 756530, 756055, 755580, 755105, 754631, 754157, 753684, 753211, 752738, 752266, 751794, 751322, 750851, 750380, 749909, 749439, 748969, 748500, 748031, 747562, 747093, 746625, 746158, 745690, 745223, 744756, 744290, 743824, 743358, 742893, 742428, 741964, 741499, 741035, 740572, 740109, 739646, 739183, 738721, 738259, 737798, 737337, 736876, 736415, 735955, 735496, 735036, 734577, 734118, 733660, 733202, 732744, 732287, 731830, 731373, 730917, 730461, 730006, 729550, 729095]
private theorem words7953_eq : (List.range' 7953 64).map threshold = words7953 := by decide
private def words8017 : List Nat := [728641, 728186, 727733, 727279, 726826, 726373, 725920, 725468, 725016, 724565, 724113, 723662, 723212, 722762, 722312, 721862, 721413, 720964, 720516, 720067, 719620, 719172, 718725, 718278, 717832, 717385, 716939, 716494, 716049, 715604, 715159, 714715, 714271, 713828, 713385, 712942, 712499, 712057, 711615, 711173, 710732, 710291, 709851, 709411, 708971, 708531, 708092, 707653, 707214, 706776, 706338, 705900, 705463, 705026, 704589, 704153, 703717, 703281, 702846, 702411, 701976, 701542, 701108, 700674]
private theorem words8017_eq : (List.range' 8017 64).map threshold = words8017 := by decide
private def words8081 : List Nat := [700241, 699808, 699375, 698942, 698510, 698078, 697647, 697216, 696785, 696354, 695924, 695494, 695065, 694635, 694206, 693778, 693349, 692921, 692494, 692066, 691639, 691213, 690786, 690360, 689934, 689509, 689084, 688659, 688234, 687810, 687386, 686963, 686539, 686116, 685694, 685271, 684849, 684428, 684006, 683585, 683164, 682744, 682324, 681904, 681485, 681065, 680646, 680228, 679809, 679392, 678974, 678556, 678139, 677723, 677306, 676890, 676474, 676059, 675643, 675229, 674814, 674400, 673986, 673572]
private theorem words8081_eq : (List.range' 8081 64).map threshold = words8081 := by decide
private def words8145 : List Nat := [673159, 672746, 672333, 671920, 671508, 671096, 670685, 670273, 669862, 669452, 669041, 668631, 668222, 667812, 667403, 666994, 666586, 666177, 665769, 665362, 664954, 664547, 664141, 663734, 663328, 662922, 662517, 662111, 661706, 661302, 660897, 660493, 660090, 659686, 659283, 658880, 658477, 658075, 657673, 657271, 656870, 656469, 656068, 655668, 655267, 654867, 654468, 654068, 653669, 653270, 652872, 652474, 652076, 651678, 651281, 650884, 650487, 650091, 649695, 649299, 648903, 648508, 648113, 647718]
private theorem words8145_eq : (List.range' 8145 64).map threshold = words8145 := by decide
private def words8209 : List Nat := [647324, 646930, 646536, 646142, 645749, 645356, 644963, 644571, 644179, 643787, 643395, 643004, 642613, 642222, 641832, 641442, 641052, 640663, 640273, 639884, 639496, 639107, 638719, 638331, 637944, 637556, 637169, 636783, 636396, 636010, 635624, 635238, 634853, 634468, 634083, 633699, 633315, 632931, 632547, 632164, 631781, 631398, 631015, 630633, 630251, 629869, 629488, 629107, 628726, 628345, 627965, 627585, 627205, 626826, 626447, 626068, 625689, 625311, 624933, 624555, 624177, 623800, 623423, 623046]
private theorem words8209_eq : (List.range' 8209 64).map threshold = words8209 := by decide
private def words8273 : List Nat := [622670, 622293, 621918, 621542, 621167, 620791, 620417, 620042, 619668, 619294, 618920, 618547, 618173, 617800, 617428, 617055, 616683, 616311, 615940, 615568, 615197, 614827, 614456, 614086, 613716, 613346, 612977, 612608, 612239, 611870, 611502, 611134, 610766, 610398, 610031, 609664, 609297, 608930, 608564, 608198, 607833, 607467, 607102, 606737, 606372, 606008, 605644, 605280, 604916, 604553, 604190, 603827, 603464, 603102, 602740, 602378, 602017, 601655, 601294, 600934, 600573, 600213, 599853, 599493]
private theorem words8273_eq : (List.range' 8273 64).map threshold = words8273 := by decide
private def words8337 : List Nat := [599134, 598775, 598416, 598057, 597699, 597340, 596983, 596625, 596267, 595910, 595553, 595197, 594841, 594484, 594129, 593773, 593418, 593063, 592708, 592353, 591999, 591645, 591291, 590937, 590584, 590231, 589878, 589526, 589173, 588821, 588470, 588118, 587767, 587416, 587065, 586714, 586364, 586014, 585664, 585315, 584966, 584616, 584268, 583919, 583571, 583223, 582875, 582528, 582180, 581833, 581486, 581140, 580794, 580448, 580102, 579756, 579411, 579066, 578721, 578377, 578032, 577688, 577344, 577001]
private theorem words8337_eq : (List.range' 8337 64).map threshold = words8337 := by decide
private def words8401 : List Nat := [576657, 576314, 575972, 575629, 575287, 574944, 574603, 574261, 573920, 573578, 573238, 572897, 572557, 572216, 571876, 571537, 571197, 570858, 570519, 570181, 569842, 569504, 569166, 568828, 568491, 568153, 567816, 567480, 567143, 566807, 566471, 566135, 565799, 565464, 565129, 564794, 564459, 564125, 563791, 563457, 563123, 562790, 562456, 562123, 561791, 561458, 561126, 560794, 560462, 560131, 559799, 559468, 559137, 558807, 558476, 558146, 557816, 557487, 557157, 556828, 556499, 556170, 555842, 555513]
private theorem words8401_eq : (List.range' 8401 64).map threshold = words8401 := by decide
private def words8465 : List Nat := [555185, 554858, 554530, 554203, 553876, 553549, 553222, 552896, 552569, 552243, 551918, 551592, 551267, 550942, 550617, 550292, 549968, 549644, 549320, 548996, 548673, 548350, 548027, 547704, 547382, 547059, 546737, 546415, 546094, 545772, 545451, 545130, 544810, 544489, 544169, 543849, 543529, 543209, 542890, 542571, 542252, 541933, 541615, 541297, 540979, 540661, 540343, 540026, 539709, 539392, 539075, 538759, 538443, 538127, 537811, 537496, 537180, 536865, 536550, 536236, 535921, 535607, 535293, 534979]
private theorem words8465_eq : (List.range' 8465 64).map threshold = words8465 := by decide
private def words8529 : List Nat := [534666, 534352, 534039, 533726, 533414, 533101, 532789, 532477, 532165, 531854, 531542, 531231, 530920, 530609, 530299, 529989, 529679, 529369, 529059, 528750, 528441, 528132, 527823, 527514, 527206, 526898, 526590, 526283, 525975, 525668, 525361, 525054, 524747, 524441, 524135, 523829, 523523, 523218, 522912, 522607, 522303, 521998, 521693, 521389, 521085, 520781, 520478, 520174, 519871, 519568, 519266, 518963, 518661, 518359, 518057, 517755, 517454, 517152, 516851, 516550, 516250, 515949, 515649, 515349]
private theorem words8529_eq : (List.range' 8529 64).map threshold = words8529 := by decide
private def words8593 : List Nat := [515049, 514750, 514450, 514151, 513852, 513553, 513255, 512957, 512658, 512361, 512063, 511765, 511468, 511171, 510874, 510577, 510281, 509985, 509689, 509393, 509097, 508802, 508506, 508211, 507917, 507622, 507328, 507033, 506739, 506446, 506152, 505859, 505565, 505272, 504980, 504687, 504395, 504103, 503811, 503519, 503227, 502936, 502645, 502354, 502063, 501772, 501482, 501192, 500902, 500612, 500323, 500033, 499744, 499455, 499167, 498878, 498590, 498302, 498014, 497726, 497438, 497151, 496864, 496577]
private theorem words8593_eq : (List.range' 8593 64).map threshold = words8593 := by decide
private def words8657 : List Nat := [496290, 496004, 495717, 495431, 495145, 494860, 494574, 494289, 494003, 493719, 493434, 493149, 492865, 492581, 492297, 492013, 491729, 491446, 491163, 490880, 490597, 490314, 490032, 489750, 489468, 489186, 488904, 488623, 488342, 488061, 487780, 487499, 487219, 486938, 486658, 486378, 486099, 485819, 485540, 485261, 484982, 484703, 484425, 484146, 483868, 483590, 483312, 483035, 482757, 482480, 482203, 481926, 481650, 481373, 481097, 480821, 480545, 480270, 479994, 479719, 479444, 479169, 478894, 478620]
private theorem words8657_eq : (List.range' 8657 64).map threshold = words8657 := by decide
private def words8721 : List Nat := [478345, 478071, 477797, 477523, 477250, 476976, 476703, 476430, 476157, 475885, 475612, 475340, 475068, 474796, 474524, 474253, 473981, 473710, 473439, 473168, 472898, 472627, 472357, 472087, 471817, 471548, 471278, 471009, 470740, 470471, 470202, 469933, 469665, 469397, 469129, 468861, 468593, 468326, 468059, 467791, 467525, 467258, 466991, 466725, 466459, 466193, 465927, 465661, 465396, 465131, 464865, 464601, 464336, 464071, 463807, 463543, 463279, 463015, 462751, 462488, 462224, 461961, 461698, 461436]
private theorem words8721_eq : (List.range' 8721 64).map threshold = words8721 := by decide
private def words8785 : List Nat := [461173, 460911, 460649, 460387, 460125, 459863, 459602, 459340, 459079, 458818, 458557, 458297, 458036, 457776, 457516, 457256, 456996, 456737, 456477, 456218, 455959, 455700, 455442, 455183, 454925, 454667, 454409, 454151, 453894, 453636, 453379, 453122, 452865, 452608, 452352, 452095, 451839, 451583, 451327, 451071, 450816, 450561, 450305, 450050, 449796, 449541, 449287, 449032, 448778, 448524, 448270, 448017, 447763, 447510, 447257, 447004, 446751, 446499, 446246, 445994, 445742, 445490, 445238, 444987]
private theorem words8785_eq : (List.range' 8785 64).map threshold = words8785 := by decide
private def words8849 : List Nat := [444736, 444484, 444233, 443982, 443732, 443481, 443231, 442981, 442731, 442481, 442231, 441982, 441732, 441483, 441234, 440985, 440737, 440488, 440240, 439992, 439744, 439496, 439248, 439001, 438753, 438506, 438259, 438012, 437766, 437519, 437273, 437027, 436781, 436535, 436289, 436044, 435798, 435553, 435308, 435063, 434819, 434574, 434330, 434086, 433842, 433598, 433354, 433111, 432867, 432624, 432381, 432138, 431896, 431653, 431411, 431169, 430927, 430685, 430443, 430201, 429960, 429719, 429478, 429237]
private theorem words8849_eq : (List.range' 8849 64).map threshold = words8849 := by decide
private def words8913 : List Nat := [428996, 428755, 428515, 428275, 428035, 427795, 427555, 427315, 427076, 426837, 426598, 426359, 426120, 425881, 425643, 425404, 425166, 424928, 424690, 424453, 424215, 423978, 423741, 423504, 423267, 423030, 422793, 422557, 422321, 422085, 421849, 421613, 421377, 421142, 420907, 420671, 420436, 420202, 419967, 419732, 419498, 419264, 419030, 418796, 418562, 418329, 418095, 417862, 417629, 417396, 417163, 416930, 416698, 416466, 416233, 416001, 415770, 415538, 415306, 415075, 414844, 414613, 414382, 414151]
private theorem words8913_eq : (List.range' 8913 64).map threshold = words8913 := by decide
private def words8977 : List Nat := [413920, 413690, 413460, 413229, 412999, 412769, 412540, 412310, 412081, 411852, 411623, 411394, 411165, 410936, 410708, 410479, 410251, 410023, 409795, 409568, 409340, 409113, 408885, 408658, 408431, 408205, 407978, 407751, 407525, 407299, 407073, 406847, 406621, 406395, 406170, 405945, 405720, 405495, 405270, 405045, 404820, 404596, 404372, 404148, 403924, 403700, 403476, 403253, 403029, 402806, 402583, 402360, 402138, 401915, 401692, 401470, 401248, 401026, 400804, 400582, 400361, 400139, 399918, 399697]
private theorem words8977_eq : (List.range' 8977 64).map threshold = words8977 := by decide
private def words9041 : List Nat := [399476, 399255, 399034, 398814, 398593, 398373, 398153, 397933, 397713, 397493, 397274, 397054, 396835, 396616, 396397, 396178, 395960, 395741, 395523, 395305, 395086, 394869, 394651, 394433, 394216, 393998, 393781, 393564, 393347, 393130, 392914, 392697, 392481, 392264, 392048, 391832, 391617, 391401, 391186, 390970, 390755, 390540, 390325, 390110, 389895, 389681, 389467, 389252, 389038, 388824, 388611, 388397, 388183, 387970, 387757, 387544, 387331, 387118, 386905, 386693, 386480, 386268, 386056, 385844]
private theorem words9041_eq : (List.range' 9041 64).map threshold = words9041 := by decide
private def words9105 : List Nat := [385632, 385420, 385209, 384997, 384786, 384575, 384364, 384153, 383942, 383732, 383521, 383311, 383101, 382891, 382681, 382471, 382262, 382052, 381843, 381633, 381424, 381215, 381007, 380798, 380590, 380381, 380173, 379965, 379757, 379549, 379341, 379134, 378926, 378719, 378512, 378305, 378098, 377891, 377685, 377478, 377272, 377066, 376859, 376654, 376448, 376242, 376037, 375831, 375626, 375421, 375216, 375011, 374806, 374602, 374397, 374193, 373989, 373785, 373581, 373377, 373173, 372970, 372766, 372563]
private theorem words9105_eq : (List.range' 9105 64).map threshold = words9105 := by decide
private def words9169 : List Nat := [372360, 372157, 371954, 371751, 371549, 371346, 371144, 370942, 370740, 370538, 370336, 370134, 369933, 369731, 369530, 369329, 369128, 368927, 368726, 368526, 368325, 368125, 367925, 367725, 367525, 367325, 367125, 366926, 366726, 366527, 366328, 366129, 365930, 365731, 365532, 365334, 365135, 364937, 364739, 364541, 364343, 364145, 363948, 363750, 363553, 363356, 363158, 362961, 362765, 362568, 362371, 362175, 361978, 361782, 361586, 361390, 361194, 360999, 360803, 360608, 360412, 360217, 360022, 359827]
private theorem words9169_eq : (List.range' 9169 64).map threshold = words9169 := by decide
private def words9233 : List Nat := [359632, 359438, 359243, 359049, 358854, 358660, 358466, 358272, 358078, 357885, 357691, 357498, 357304, 357111, 356918, 356725, 356532, 356340, 356147, 355955, 355762, 355570, 355378, 355186, 354994, 354803, 354611, 354420, 354228, 354037, 353846, 353655, 353464, 353274, 353083, 352893, 352702, 352512, 352322, 352132, 351942, 351753, 351563, 351374, 351184, 350995, 350806, 350617, 350428, 350239, 350051, 349862, 349674, 349486, 349298, 349110, 348922, 348734, 348546, 348359, 348171, 347984, 347797, 347610]
private theorem words9233_eq : (List.range' 9233 64).map threshold = words9233 := by decide
private def words9297 : List Nat := [347423, 347236, 347050, 346863, 346677, 346490, 346304, 346118, 345932, 345746, 345561, 345375, 345190, 345004, 344819, 344634, 344449, 344264, 344079, 343895, 343710, 343526, 343341, 343157, 342973, 342789, 342606, 342422, 342238, 342055, 341872, 341688, 341505, 341322, 341139, 340957, 340774, 340592, 340409, 340227, 340045, 339863, 339681, 339499, 339317, 339136, 338954, 338773, 338592, 338411, 338230, 338049, 337868, 337687, 337507, 337326, 337146, 336966, 336786, 336606, 336426, 336246, 336067, 335887]
private theorem words9297_eq : (List.range' 9297 64).map threshold = words9297 := by decide
private def words9361 : List Nat := [335708, 335529, 335350, 335171, 334992, 334813, 334634, 334456, 334277, 334099, 333921, 333742, 333564, 333387, 333209, 333031, 332854, 332676, 332499, 332322, 332145, 331968, 331791, 331614, 331437, 331261, 331084, 330908, 330732, 330556, 330380, 330204, 330028, 329853, 329677, 329502, 329327, 329151, 328976, 328801, 328626, 328452, 328277, 328103, 327928, 327754, 327580, 327406, 327232, 327058, 326884, 326711, 326537, 326364, 326190, 326017, 325844, 325671, 325498, 325326, 325153, 324981, 324808, 324636]
private theorem words9361_eq : (List.range' 9361 64).map threshold = words9361 := by decide
private def words9425 : List Nat := [324464, 324292, 324120, 323948, 323776, 323604, 323433, 323261, 323090, 322919, 322748, 322577, 322406, 322235, 322065, 321894, 321724, 321553, 321383, 321213, 321043, 320873, 320703, 320533, 320364, 320194, 320025, 319856, 319687, 319518, 319349, 319180, 319011, 318843, 318674, 318506, 318337, 318169, 318001, 317833, 317665, 317498, 317330, 317162, 316995, 316828, 316660, 316493, 316326, 316159, 315992, 315826, 315659, 315493, 315326, 315160, 314994, 314828, 314662, 314496, 314330, 314165, 313999, 313834]
private theorem words9425_eq : (List.range' 9425 64).map threshold = words9425 := by decide
private def words9489 : List Nat := [313668, 313503, 313338, 313173, 313008, 312843, 312678, 312514, 312349, 312185, 312021, 311857, 311692, 311528, 311365, 311201, 311037, 310874, 310710, 310547, 310383, 310220, 310057, 309894, 309731, 309569, 309406, 309244, 309081, 308919, 308757, 308594, 308432, 308270, 308109, 307947, 307785, 307624, 307462, 307301, 307140, 306979, 306818, 306657, 306496, 306335, 306175, 306014, 305854, 305694, 305533, 305373, 305213, 305053, 304894, 304734, 304574, 304415, 304255, 304096, 303937, 303778, 303619, 303460]
private theorem words9489_eq : (List.range' 9489 64).map threshold = words9489 := by decide
private def words9553 : List Nat := [303301, 303142, 302984, 302825, 302667, 302509, 302350, 302192, 302034, 301876, 301719, 301561, 301403, 301246, 301088, 300931, 300774, 300617, 300460, 300303, 300146, 299989, 299833, 299676, 299520, 299363, 299207, 299051, 298895, 298739, 298583, 298427, 298272, 298116, 297961, 297805, 297650, 297495, 297340, 297185, 297030, 296875, 296721, 296566, 296412, 296257, 296103, 295949, 295795, 295641, 295487, 295333, 295179, 295026, 294872, 294719, 294565, 294412, 294259, 294106, 293953, 293800, 293648, 293495]
private theorem words9553_eq : (List.range' 9553 64).map threshold = words9553 := by decide
private def words9617 : List Nat := [293342, 293190, 293038, 292885, 292733, 292581, 292429, 292277, 292125, 291974, 291822, 291670, 291519, 291368, 291216, 291065, 290914, 290763, 290612, 290462, 290311, 290160, 290010, 289860, 289709, 289559, 289409, 289259, 289109, 288959, 288809, 288660, 288510, 288361, 288211, 288062, 287913, 287764, 287615, 287466, 287317, 287169, 287020, 286871, 286723, 286575, 286426, 286278, 286130, 285982, 285834, 285686, 285539, 285391, 285244, 285096, 284949, 284802, 284654, 284507, 284360, 284214, 284067, 283920]
private theorem words9617_eq : (List.range' 9617 64).map threshold = words9617 := by decide
private def words9681 : List Nat := [283773, 283627, 283480, 283334, 283188, 283042, 282896, 282750, 282604, 282458, 282312, 282167, 282021, 281876, 281730, 281585, 281440, 281295, 281150, 281005, 280860, 280716, 280571, 280426, 280282, 280138, 279993, 279849, 279705, 279561, 279417, 279273, 279130, 278986, 278842, 278699, 278556, 278412, 278269, 278126, 277983, 277840, 277697, 277554, 277412, 277269, 277127, 276984, 276842, 276700, 276558, 276415, 276273, 276132, 275990, 275848, 275706, 275565, 275424, 275282, 275141, 275000, 274859, 274718]
private theorem words9681_eq : (List.range' 9681 64).map threshold = words9681 := by decide
private def words9745 : List Nat := [274577, 274436, 274295, 274154, 274014, 273873, 273733, 273593, 273452, 273312, 273172, 273032, 272892, 272753, 272613, 272473, 272334, 272194, 272055, 271916, 271776, 271637, 271498, 271359, 271220, 271082, 270943, 270804, 270666, 270527, 270389, 270251, 270113, 269974, 269836, 269699, 269561, 269423, 269285, 269148, 269010, 268873, 268735, 268598, 268461, 268324, 268187, 268050, 267913, 267776, 267640, 267503, 267367, 267230, 267094, 266958, 266822, 266685, 266549, 266414, 266278, 266142, 266006, 265871]
private theorem words9745_eq : (List.range' 9745 64).map threshold = words9745 := by decide
private def words9809 : List Nat := [265735, 265600, 265465, 265329, 265194, 265059, 264924, 264789, 264654, 264520, 264385, 264250, 264116, 263981, 263847, 263713, 263579, 263444, 263310, 263176, 263043, 262909, 262775, 262642, 262508, 262375, 262241, 262108, 261975, 261842, 261709, 261576, 261443, 261310, 261177, 261045, 260912, 260780, 260647, 260515, 260383, 260251, 260119, 259987, 259855, 259723, 259591, 259459, 259328, 259196, 259065, 258934, 258802, 258671, 258540, 258409, 258278, 258147, 258016, 257886, 257755, 257624, 257494, 257364]
private theorem words9809_eq : (List.range' 9809 64).map threshold = words9809 := by decide
private def words9873 : List Nat := [257233, 257103, 256973, 256843, 256713, 256583, 256453, 256323, 256194, 256064, 255935, 255805, 255676, 255546, 255417, 255288, 255159, 255030, 254901, 254772, 254644, 254515, 254386, 254258, 254129, 254001, 253873, 253745, 253617, 253488, 253361, 253233, 253105, 252977, 252849, 252722, 252594, 252467, 252340, 252212, 252085, 251958, 251831, 251704, 251577, 251450, 251324, 251197, 251070, 250944, 250818, 250691, 250565, 250439, 250313, 250187, 250061, 249935, 249809, 249683, 249558, 249432, 249306, 249181]
private theorem words9873_eq : (List.range' 9873 64).map threshold = words9873 := by decide
private def words9937 : List Nat := [249056, 248930, 248805, 248680, 248555, 248430, 248305, 248180, 248056, 247931, 247806, 247682, 247557, 247433, 247309, 247184, 247060, 246936, 246812, 246688, 246564, 246441, 246317, 246193, 246070, 245946, 245823, 245699, 245576, 245453, 245330, 245207, 245084, 244961, 244838, 244716, 244593, 244470, 244348, 244225, 244103, 243981, 243858, 243736, 243614, 243492, 243370, 243248, 243127, 243005, 242883, 242762, 242640, 242519, 242397, 242276, 242155, 242034, 241913, 241792, 241671, 241550, 241429, 241309]
private theorem words9937_eq : (List.range' 9937 64).map threshold = words9937 := by decide
private def words10001 : List Nat := [241188, 241067, 240947, 240827, 240706, 240586, 240466, 240346, 240226, 240106, 239986, 239866, 239746, 239627, 239507, 239387, 239268, 239149, 239029, 238910, 238791, 238672, 238553, 238434, 238315, 238196, 238077, 237958, 237840, 237721, 237603, 237484, 237366, 237248, 237130, 237012, 236894, 236776, 236658, 236540, 236422, 236304, 236187, 236069, 235952, 235834, 235717, 235600, 235482, 235365, 235248, 235131, 235014, 234898, 234781, 234664, 234547, 234431, 234314, 234198, 234082, 233965, 233849, 233733]
private theorem words10001_eq : (List.range' 10001 64).map threshold = words10001 := by decide
private def words10065 : List Nat := [233617, 233501, 233385, 233269, 233153, 233037, 232922, 232806, 232691, 232575, 232460, 232344, 232229, 232114, 231999, 231884, 231769, 231654, 231539, 231424, 231309, 231195, 231080, 230966, 230851, 230737, 230623, 230508, 230394, 230280, 230166, 230052, 229938, 229824, 229711, 229597, 229483, 229370, 229256, 229143, 229029, 228916, 228803, 228690, 228577, 228464, 228351, 228238, 228125, 228012, 227900, 227787, 227674, 227562, 227449, 227337, 227225, 227113, 227000, 226888, 226776, 226664, 226552, 226441]
private theorem words10065_eq : (List.range' 10065 64).map threshold = words10065 := by decide
private def words10129 : List Nat := [226329, 226217, 226106, 225994, 225883, 225771, 225660, 225548, 225437, 225326, 225215, 225104, 224993, 224882, 224771, 224660, 224550, 224439, 224329, 224218, 224108, 223997, 223887, 223777, 223666, 223556, 223446, 223336, 223226, 223117, 223007, 222897, 222787, 222678, 222568, 222459, 222349, 222240, 222131, 222022, 221912, 221803, 221694, 221585, 221476, 221368, 221259, 221150, 221042, 220933, 220825, 220716, 220608, 220499, 220391, 220283, 220175, 220067, 219959, 219851, 219743, 219635, 219527, 219420]
private theorem words10129_eq : (List.range' 10129 64).map threshold = words10129 := by decide
private def words10193 : List Nat := [219312, 219205, 219097, 218990, 218882, 218775, 218668, 218561, 218454, 218347, 218240, 218133, 218026, 217919, 217812, 217706, 217599, 217492, 217386, 217280, 217173, 217067, 216961, 216854, 216748, 216642, 216536, 216430, 216325, 216219, 216113, 216007, 215902, 215796, 215691, 215585, 215480, 215375, 215269, 215164, 215059, 214954, 214849, 214744, 214639, 214535, 214430, 214325, 214220, 214116, 214011, 213907, 213803, 213698, 213594, 213490, 213386, 213282, 213178, 213074, 212970, 212866, 212762, 212659]
private theorem words10193_eq : (List.range' 10193 64).map threshold = words10193 := by decide
private def words10257 : List Nat := [212555, 212451, 212348, 212244, 212141, 212038, 211934, 211831, 211728, 211625, 211522, 211419, 211316, 211213, 211110, 211007, 210905, 210802, 210700, 210597, 210495, 210392, 210290, 210188, 210085, 209983, 209881, 209779, 209677, 209575, 209474, 209372, 209270, 209168, 209067, 208965, 208864, 208762, 208661, 208560, 208458, 208357, 208256, 208155, 208054, 207953, 207852, 207751, 207650, 207550, 207449, 207348, 207248, 207147, 207047, 206947, 206846, 206746, 206646, 206546, 206446, 206346, 206246, 206146]
private theorem words10257_eq : (List.range' 10257 64).map threshold = words10257 := by decide
private def words10321 : List Nat := [206046, 205946, 205846, 205747, 205647, 205548, 205448, 205349, 205249, 205150, 205051, 204951, 204852, 204753, 204654, 204555, 204456, 204357, 204259, 204160, 204061, 203962, 203864, 203765, 203667, 203568, 203470, 203372, 203274, 203175, 203077, 202979, 202881, 202783, 202685, 202587, 202490, 202392, 202294, 202197, 202099, 202002, 201904, 201807, 201709, 201612, 201515, 201418, 201321, 201224, 201127, 201030, 200933, 200836, 200739, 200643, 200546, 200449, 200353, 200256, 200160, 200063, 199967, 199871]
private theorem words10321_eq : (List.range' 10321 64).map threshold = words10321 := by decide
private def words10385 : List Nat := [199775, 199678, 199582, 199486, 199390, 199294, 199199, 199103, 199007, 198911, 198816, 198720, 198624, 198529, 198433, 198338, 198243, 198147, 198052, 197957, 197862, 197767, 197672, 197577, 197482, 197387, 197293, 197198, 197103, 197009, 196914, 196819, 196725, 196631, 196536, 196442, 196348, 196254, 196159, 196065, 195971, 195877, 195783, 195690, 195596, 195502, 195408, 195315, 195221, 195128, 195034, 194941, 194847, 194754, 194661, 194568, 194474, 194381, 194288, 194195, 194102, 194009, 193917, 193824]
private theorem words10385_eq : (List.range' 10385 64).map threshold = words10385 := by decide
private def words10449 : List Nat := [193731, 193638, 193546, 193453, 193361, 193268, 193176, 193083, 192991, 192899, 192807, 192715, 192622, 192530, 192438, 192346, 192255, 192163, 192071, 191979, 191888, 191796, 191704, 191613, 191521, 191430, 191339, 191247, 191156, 191065, 190974, 190883, 190792, 190701, 190610, 190519, 190428, 190337, 190246, 190156, 190065, 189975, 189884, 189794, 189703, 189613, 189522, 189432, 189342, 189252, 189162, 189072, 188982, 188892, 188802, 188712, 188622, 188532, 188443, 188353, 188263, 188174, 188084, 187995]
private theorem words10449_eq : (List.range' 10449 64).map threshold = words10449 := by decide
private def words10513 : List Nat := [187906, 187816, 187727, 187638, 187548, 187459, 187370, 187281, 187192, 187103, 187014, 186926, 186837, 186748, 186659, 186571, 186482, 186394, 186305, 186217, 186128, 186040, 185952, 185863, 185775, 185687, 185599, 185511, 185423, 185335, 185247, 185159, 185072, 184984, 184896, 184809, 184721, 184634, 184546, 184459, 184371, 184284, 184197, 184109, 184022, 183935, 183848, 183761, 183674, 183587, 183500, 183413, 183327, 183240, 183153, 183066, 182980, 182893, 182807, 182720, 182634, 182548, 182461, 182375]
private theorem words10513_eq : (List.range' 10513 64).map threshold = words10513 := by decide
private def words10577 : List Nat := [182289, 182203, 182117, 182031, 181945, 181859, 181773, 181687, 181601, 181515, 181430, 181344, 181258, 181173, 181087, 181002, 180916, 180831, 180746, 180660, 180575, 180490, 180405, 180320, 180235, 180150, 180065, 179980, 179895, 179810, 179726, 179641, 179556, 179472, 179387, 179303, 179218, 179134, 179049, 178965, 178881, 178797, 178712, 178628, 178544, 178460, 178376, 178292, 178208, 178125, 178041, 177957, 177873, 177790, 177706, 177623, 177539, 177456, 177372, 177289, 177205, 177122, 177039, 176956]
private theorem words10577_eq : (List.range' 10577 64).map threshold = words10577 := by decide
private def words10641 : List Nat := [176873, 176790, 176707, 176624, 176541, 176458, 176375, 176292, 176209, 176127, 176044, 175961, 175879, 175796, 175714, 175631, 175549, 175467, 175384, 175302, 175220, 175138, 175056, 174973, 174891, 174809, 174728, 174646, 174564, 174482, 174400, 174319, 174237, 174155, 174074, 173992, 173911, 173829, 173748, 173667, 173585, 173504, 173423, 173342, 173261, 173180, 173099, 173018, 172937, 172856, 172775, 172694, 172614, 172533, 172452, 172372, 172291, 172211, 172130, 172050, 171969, 171889, 171809, 171728]
private theorem words10641_eq : (List.range' 10641 64).map threshold = words10641 := by decide
private def words10705 : List Nat := [171648, 171568, 171488, 171408, 171328, 171248, 171168, 171088, 171008, 170929, 170849, 170769, 170689, 170610, 170530, 170451, 170371, 170292, 170212, 170133, 170054, 169975, 169895, 169816, 169737, 169658, 169579, 169500, 169421, 169342, 169263, 169184, 169106, 169027, 168948, 168870, 168791, 168712, 168634, 168555, 168477, 168399, 168320, 168242, 168164, 168086, 168007, 167929, 167851, 167773, 167695, 167617, 167539, 167462, 167384, 167306, 167228, 167151, 167073, 166995, 166918, 166840, 166763, 166685]
private theorem words10705_eq : (List.range' 10705 64).map threshold = words10705 := by decide
private def words10769 : List Nat := [166608, 166531, 166453, 166376, 166299, 166222, 166145, 166068, 165991, 165914, 165837, 165760, 165683, 165606, 165529, 165453, 165376, 165299, 165223, 165146, 165070, 164993, 164917, 164840, 164764, 164688, 164611, 164535, 164459, 164383, 164307, 164231, 164155, 164079, 164003, 163927, 163851, 163775, 163699, 163624, 163548, 163472, 163397, 163321, 163246, 163170, 163095, 163019, 162944, 162869, 162794, 162718, 162643, 162568, 162493, 162418, 162343, 162268, 162193, 162118, 162043, 161968, 161894, 161819]
private theorem words10769_eq : (List.range' 10769 64).map threshold = words10769 := by decide
private def words10833 : List Nat := [161744, 161670, 161595, 161521, 161446, 161372, 161297, 161223, 161148, 161074, 161000, 160926, 160851, 160777, 160703, 160629, 160555, 160481, 160407, 160333, 160260, 160186, 160112, 160038, 159965, 159891, 159817, 159744, 159670, 159597, 159523, 159450, 159376, 159303, 159230, 159157, 159083, 159010, 158937, 158864, 158791, 158718, 158645, 158572, 158499, 158426, 158354, 158281, 158208, 158135, 158063, 157990, 157918, 157845, 157773, 157700, 157628, 157555, 157483, 157411, 157339, 157266, 157194, 157122]
private theorem words10833_eq : (List.range' 10833 64).map threshold = words10833 := by decide
private def words10897 : List Nat := [157050, 156978, 156906, 156834, 156762, 156690, 156618, 156547, 156475, 156403, 156331, 156260, 156188, 156117, 156045, 155974, 155902, 155831, 155759, 155688, 155617, 155545, 155474, 155403, 155332, 155261, 155190, 155119, 155048, 154977, 154906, 154835, 154764, 154693, 154623, 154552, 154481, 154411, 154340, 154270, 154199, 154129, 154058, 153988, 153917, 153847, 153777, 153707, 153636, 153566, 153496, 153426, 153356, 153286, 153216, 153146, 153076, 153006, 152936, 152867, 152797, 152727, 152658, 152588]
private theorem words10897_eq : (List.range' 10897 64).map threshold = words10897 := by decide
private def words10961 : List Nat := [152518, 152449, 152379, 152310, 152240, 152171, 152102, 152032, 151963, 151894, 151824, 151755, 151686, 151617, 151548, 151479, 151410, 151341, 151272, 151203, 151134, 151066, 150997, 150928, 150859, 150791, 150722, 150654, 150585, 150517, 150448, 150380, 150311, 150243, 150175, 150106, 150038, 149970, 149902, 149834, 149766, 149698, 149630, 149562, 149494, 149426, 149358, 149290, 149222, 149154, 149087, 149019, 148951, 148884, 148816, 148749, 148681, 148614, 148546, 148479, 148412, 148344, 148277, 148210]
private theorem words10961_eq : (List.range' 10961 64).map threshold = words10961 := by decide
private def words11025 : List Nat := [148143, 148075, 148008, 147941, 147874, 147807, 147740, 147673, 147606, 147539, 147473, 147406, 147339, 147272, 147206, 147139, 147072, 147006, 146939, 146873, 146806, 146740, 146673, 146607, 146541, 146474, 146408, 146342, 146276, 146209, 146143, 146077, 146011, 145945, 145879, 145813, 145747, 145682, 145616, 145550, 145484, 145418, 145353, 145287, 145221, 145156, 145090, 145025, 144959, 144894, 144829, 144763, 144698, 144633, 144567, 144502, 144437, 144372, 144307, 144242, 144176, 144111, 144046, 143982]
private theorem words11025_eq : (List.range' 11025 64).map threshold = words11025 := by decide
private def words11089 : List Nat := [143917, 143852, 143787, 143722, 143657, 143593, 143528, 143463, 143399, 143334, 143269, 143205, 143140, 143076, 143012, 142947, 142883, 142819, 142754, 142690, 142626, 142562, 142497, 142433, 142369, 142305, 142241, 142177, 142113, 142049, 141986, 141922, 141858, 141794, 141730, 141667, 141603, 141539, 141476, 141412, 141349, 141285, 141222, 141158, 141095, 141032, 140968, 140905, 140842, 140779, 140715, 140652, 140589, 140526, 140463, 140400, 140337, 140274, 140211, 140148, 140086, 140023, 139960, 139897]
private theorem words11089_eq : (List.range' 11089 64).map threshold = words11089 := by decide
private def words11153 : List Nat := [139834, 139772, 139709, 139647, 139584, 139521, 139459, 139396, 139334, 139272, 139209, 139147, 139085, 139022, 138960, 138898, 138836, 138774, 138712, 138649, 138587, 138525, 138463, 138402, 138340, 138278, 138216, 138154, 138092, 138031, 137969, 137907, 137846, 137784, 137722, 137661, 137599, 137538, 137476, 137415, 137354, 137292, 137231, 137170, 137109, 137047, 136986, 136925, 136864, 136803, 136742, 136681, 136620, 136559, 136498, 136437, 136376, 136315, 136255, 136194, 136133, 136072, 136012, 135951]
private theorem words11153_eq : (List.range' 11153 64).map threshold = words11153 := by decide
private def words11217 : List Nat := [135891, 135830, 135769, 135709, 135649, 135588, 135528, 135467, 135407, 135347, 135286, 135226, 135166, 135106, 135046, 134986, 134926, 134865, 134805, 134745, 134686, 134626, 134566, 134506, 134446, 134386, 134327, 134267, 134207, 134147, 134088, 134028, 133969, 133909, 133850, 133790, 133731, 133671, 133612, 133553, 133493, 133434, 133375, 133316, 133256, 133197, 133138, 133079, 133020, 132961, 132902, 132843, 132784, 132725, 132666, 132607, 132549, 132490, 132431, 132372, 132314, 132255, 132196, 132138]
private theorem words11217_eq : (List.range' 11217 64).map threshold = words11217 := by decide
private def words11281 : List Nat := [132079, 132021, 131962, 131904, 131845, 131787, 131729, 131670, 131612, 131554, 131495, 131437, 131379, 131321, 131263, 131205, 131147, 131089, 131031, 130973, 130915, 130857, 130799, 130741, 130683, 130625, 130568, 130510, 130452, 130395, 130337, 130279, 130222, 130164, 130107, 130049, 129992, 129934, 129877, 129820, 129762, 129705, 129648, 129591, 129533, 129476, 129419, 129362, 129305, 129248, 129191, 129134, 129077, 129020, 128963, 128906, 128849, 128793, 128736, 128679, 128622, 128566, 128509, 128452]
private theorem words11281_eq : (List.range' 11281 64).map threshold = words11281 := by decide
private def words11345 : List Nat := [128396, 128339, 128283, 128226, 128170, 128113, 128057, 128000, 127944, 127888, 127831, 127775, 127719, 127663, 127606, 127550, 127494, 127438, 127382, 127326, 127270, 127214, 127158, 127102, 127046, 126990, 126934, 126879, 126823, 126767, 126711, 126656, 126600, 126544, 126489, 126433, 126378, 126322, 126267, 126211, 126156, 126101, 126045, 125990, 125935, 125879, 125824, 125769, 125714, 125658, 125603, 125548, 125493, 125438, 125383, 125328, 125273, 125218, 125163, 125108, 125054, 124999, 124944, 124889]
private theorem words11345_eq : (List.range' 11345 64).map threshold = words11345 := by decide
private def words11409 : List Nat := [124835, 124780, 124725, 124671, 124616, 124561, 124507, 124452, 124398, 124343, 124289, 124235, 124180, 124126, 124071, 124017, 123963, 123909, 123854, 123800, 123746, 123692, 123638, 123584, 123530, 123476, 123422, 123368, 123314, 123260, 123206, 123152, 123099, 123045, 122991, 122937, 122884, 122830, 122776, 122723, 122669, 122616, 122562, 122508, 122455, 122402, 122348, 122295, 122241, 122188, 122135, 122081, 122028, 121975, 121922, 121869, 121815, 121762, 121709, 121656, 121603, 121550, 121497, 121444]
private theorem words11409_eq : (List.range' 11409 64).map threshold = words11409 := by decide
private def words11473 : List Nat := [121391, 121338, 121286, 121233, 121180, 121127, 121074, 121022, 120969, 120916, 120864, 120811, 120759, 120706, 120653, 120601, 120548, 120496, 120444, 120391, 120339, 120286, 120234, 120182, 120130, 120077, 120025, 119973, 119921, 119869, 119817, 119765, 119713, 119661, 119609, 119557, 119505, 119453, 119401, 119349, 119297, 119245, 119194, 119142, 119090, 119039, 118987, 118935, 118884, 118832, 118780, 118729, 118677, 118626, 118575, 118523, 118472, 118420, 118369, 118318, 118266, 118215, 118164, 118113]
private theorem words11473_eq : (List.range' 11473 64).map threshold = words11473 := by decide
private def words11537 : List Nat := [118062, 118010, 117959, 117908, 117857, 117806, 117755, 117704, 117653, 117602, 117551, 117500, 117449, 117399, 117348, 117297, 117246, 117196, 117145, 117094, 117043, 116993, 116942, 116892, 116841, 116791, 116740, 116690, 116639, 116589, 116538, 116488, 116438, 116387, 116337, 116287, 116237, 116186, 116136, 116086, 116036, 115986, 115936, 115886, 115836, 115786, 115736, 115686, 115636, 115586, 115536, 115486, 115436, 115387, 115337, 115287, 115237, 115188, 115138, 115088, 115039, 114989, 114940, 114890]
private theorem words11537_eq : (List.range' 11537 64).map threshold = words11537 := by decide
private def words11601 : List Nat := [114841, 114791, 114742, 114692, 114643, 114594, 114544, 114495, 114446, 114396, 114347, 114298, 114249, 114199, 114150, 114101, 114052, 114003, 113954, 113905, 113856, 113807, 113758, 113709, 113660, 113611, 113562, 113514, 113465, 113416, 113367, 113319, 113270, 113221, 113172, 113124, 113075, 113027, 112978, 112930, 112881, 112833, 112784, 112736, 112687, 112639, 112591, 112542, 112494, 112446, 112398, 112349, 112301, 112253, 112205, 112157, 112109, 112061, 112012, 111964, 111916, 111868, 111821, 111773]
private theorem words11601_eq : (List.range' 11601 64).map threshold = words11601 := by decide
private def words11665 : List Nat := [111725, 111677, 111629, 111581, 111533, 111486, 111438, 111390, 111342, 111295, 111247, 111199, 111152, 111104, 111057, 111009, 110962, 110914, 110867, 110819, 110772, 110724, 110677, 110630, 110582, 110535, 110488, 110441, 110393, 110346, 110299, 110252, 110205, 110158, 110111, 110064, 110017, 109970, 109923, 109876, 109829, 109782, 109735, 109688, 109641, 109594, 109548, 109501, 109454, 109407, 109361, 109314, 109267, 109221, 109174, 109128, 109081, 109035, 108988, 108942, 108895, 108849, 108802, 108756]
private theorem words11665_eq : (List.range' 11665 64).map threshold = words11665 := by decide
private def words11729 : List Nat := [108710, 108663, 108617, 108571, 108524, 108478, 108432, 108386, 108340, 108293, 108247, 108201, 108155, 108109, 108063, 108017, 107971, 107925, 107879, 107833, 107787, 107742, 107696, 107650, 107604, 107558, 107513, 107467, 107421, 107376, 107330, 107284, 107239, 107193, 107148, 107102, 107057, 107011, 106966, 106920, 106875, 106829, 106784, 106739, 106693, 106648, 106603, 106557, 106512, 106467, 106422, 106377, 106332, 106286, 106241, 106196, 106151, 106106, 106061, 106016, 105971, 105926, 105881, 105837]
private theorem words11729_eq : (List.range' 11729 64).map threshold = words11729 := by decide
private def words11793 : List Nat := [105792, 105747, 105702, 105657, 105612, 105568, 105523, 105478, 105434, 105389, 105344, 105300, 105255, 105210, 105166, 105121, 105077, 105032, 104988, 104944, 104899, 104855, 104810, 104766, 104722, 104677, 104633, 104589, 104545, 104500, 104456, 104412, 104368, 104324, 104280, 104236, 104192, 104148, 104104, 104060, 104016, 103972, 103928, 103884, 103840, 103796, 103752, 103708, 103665, 103621, 103577, 103533, 103490, 103446, 103402, 103359, 103315, 103272, 103228, 103185, 103141, 103098, 103054, 103011]
private theorem words11793_eq : (List.range' 11793 64).map threshold = words11793 := by decide
private def words11857 : List Nat := [102967, 102924, 102880, 102837, 102794, 102750, 102707, 102664, 102621, 102577, 102534, 102491, 102448, 102405, 102361, 102318, 102275, 102232, 102189, 102146, 102103, 102060, 102017, 101974, 101931, 101888, 101846, 101803, 101760, 101717, 101674, 101632, 101589, 101546, 101503, 101461, 101418, 101376, 101333, 101290, 101248, 101205, 101163, 101120, 101078, 101035, 100993, 100950, 100908, 100866, 100823, 100781, 100739, 100696, 100654, 100612, 100570, 100527, 100485, 100443, 100401, 100359, 100317, 100275]
private theorem words11857_eq : (List.range' 11857 64).map threshold = words11857 := by decide
private def words11921 : List Nat := [100233, 100191, 100149, 100107, 100065, 100023, 99981, 99939, 99897, 99855, 99813, 99772, 99730, 99688, 99646, 99604, 99563, 99521, 99479, 99438, 99396, 99354, 99313, 99271, 99230, 99188, 99147, 99105, 99064, 99022, 98981, 98940, 98898, 98857, 98815, 98774, 98733, 98692, 98650, 98609, 98568, 98527, 98486, 98444, 98403, 98362, 98321, 98280, 98239, 98198, 98157, 98116, 98075, 98034, 97993, 97952, 97911, 97870, 97830, 97789, 97748, 97707, 97666, 97626]
private theorem words11921_eq : (List.range' 11921 64).map threshold = words11921 := by decide
private def words11985 : List Nat := [97585, 97544, 97504, 97463, 97422, 97382, 97341, 97300, 97260, 97219, 97179, 97138, 97098, 97057, 97017, 96977, 96936, 96896, 96855, 96815, 96775, 96734, 96694, 96654, 96614, 96573, 96533, 96493, 96453, 96413, 96373, 96333, 96293, 96252, 96212, 96172, 96132, 96092, 96052, 96013, 95973, 95933, 95893, 95853, 95813, 95773, 95734, 95694, 95654, 95614, 95575, 95535, 95495, 95456, 95416, 95376, 95337, 95297, 95258, 95218, 95178, 95139, 95100, 95060]
private theorem words11985_eq : (List.range' 11985 64).map threshold = words11985 := by decide
private def words12049 : List Nat := [95021, 94981, 94942, 94902, 94863, 94824, 94784, 94745, 94706, 94667, 94627, 94588, 94549, 94510, 94470, 94431, 94392, 94353, 94314, 94275, 94236, 94197, 94158, 94119, 94080, 94041, 94002, 93963, 93924, 93885, 93846, 93808, 93769, 93730, 93691, 93652, 93614, 93575, 93536, 93498, 93459, 93420, 93382, 93343, 93304, 93266, 93227, 93189, 93150, 93112, 93073, 93035, 92996, 92958, 92920, 92881, 92843, 92805, 92766, 92728, 92690, 92651, 92613, 92575]
private theorem words12049_eq : (List.range' 12049 64).map threshold = words12049 := by decide
private def words12113 : List Nat := [92537, 92499, 92460, 92422, 92384, 92346, 92308, 92270, 92232, 92194, 92156, 92118, 92080, 92042, 92004, 91966, 91928, 91890, 91852, 91814, 91777, 91739, 91701, 91663, 91625, 91588, 91550, 91512, 91475, 91437, 91399, 91362, 91324, 91286, 91249, 91211, 91174, 91136, 91099, 91061, 91024, 90986, 90949, 90912, 90874, 90837, 90800, 90762, 90725, 90688, 90650, 90613, 90576, 90539, 90501, 90464, 90427, 90390, 90353, 90316, 90279, 90242, 90204, 90167]
private theorem words12113_eq : (List.range' 12113 64).map threshold = words12113 := by decide
private def words12177 : List Nat := [90130, 90093, 90056, 90019, 89983, 89946, 89909, 89872, 89835, 89798, 89761, 89724, 89688, 89651, 89614, 89577, 89541, 89504, 89467, 89431, 89394, 89357, 89321, 89284, 89247, 89211, 89174, 89138, 89101, 89065, 89028, 88992, 88955, 88919, 88883, 88846, 88810, 88773, 88737, 88701, 88665, 88628, 88592, 88556, 88520, 88483, 88447, 88411, 88375, 88339, 88303, 88266, 88230, 88194, 88158, 88122, 88086, 88050, 88014, 87978, 87942, 87906, 87871, 87835]
private theorem words12177_eq : (List.range' 12177 64).map threshold = words12177 := by decide
private def words12241 : List Nat := [87799, 87763, 87727, 87691, 87655, 87620, 87584, 87548, 87512, 87477, 87441, 87405, 87370, 87334, 87298, 87263, 87227, 87192, 87156, 87121, 87085, 87050, 87014, 86979, 86943, 86908, 86872, 86837, 86801, 86766, 86731, 86695, 86660, 86625, 86590, 86554, 86519, 86484, 86449, 86413, 86378, 86343, 86308, 86273, 86238, 86203, 86168, 86132, 86097, 86062, 86027, 85992, 85957, 85922, 85888, 85853, 85818, 85783, 85748, 85713, 85678, 85643, 85609, 85574]
private theorem words12241_eq : (List.range' 12241 64).map threshold = words12241 := by decide
private def words12305 : List Nat := [85539, 85504, 85470, 85435, 85400, 85366, 85331, 85296, 85262, 85227, 85192, 85158, 85123, 85089, 85054, 85020, 84985, 84951, 84916, 84882, 84847, 84813, 84779, 84744, 84710, 84675, 84641, 84607, 84573, 84538, 84504, 84470, 84435, 84401, 84367, 84333, 84299, 84265, 84230, 84196, 84162, 84128, 84094, 84060, 84026, 83992, 83958, 83924, 83890, 83856, 83822, 83788, 83754, 83721, 83687, 83653, 83619, 83585, 83551, 83518, 83484, 83450, 83416, 83383]
private theorem words12305_eq : (List.range' 12305 64).map threshold = words12305 := by decide
private def words12369 : List Nat := [83349, 83315, 83282, 83248, 83214, 83181, 83147, 83113, 83080, 83046, 83013, 82979, 82946, 82912, 82879, 82845, 82812, 82778, 82745, 82712, 82678, 82645, 82612, 82578, 82545, 82512, 82478, 82445, 82412, 82379, 82345, 82312, 82279, 82246, 82213, 82180, 82146, 82113, 82080, 82047, 82014, 81981, 81948, 81915, 81882, 81849, 81816, 81783, 81750, 81717, 81685, 81652, 81619, 81586, 81553, 81520, 81487, 81455, 81422, 81389, 81356, 81324, 81291, 81258]
private theorem words12369_eq : (List.range' 12369 64).map threshold = words12369 := by decide
private def words12433 : List Nat := [81226, 81193, 81160, 81128, 81095, 81063, 81030, 80997, 80965, 80932, 80900, 80867, 80835, 80802, 80770, 80737, 80705, 80673, 80640, 80608, 80575, 80543, 80511, 80478, 80446, 80414, 80382, 80349, 80317, 80285, 80253, 80221, 80188, 80156, 80124, 80092, 80060, 80028, 79996, 79964, 79932, 79900, 79867, 79835, 79804, 79772, 79740, 79708, 79676, 79644, 79612, 79580, 79548, 79516, 79484, 79453, 79421, 79389, 79357, 79326, 79294, 79262, 79230, 79199]
private theorem words12433_eq : (List.range' 12433 64).map threshold = words12433 := by decide
private def words12497 : List Nat := [79167, 79135, 79104, 79072, 79040, 79009, 78977, 78946, 78914, 78883, 78851, 78819, 78788, 78756, 78725, 78694, 78662, 78631, 78599, 78568, 78537, 78505, 78474, 78442, 78411, 78380, 78349, 78317, 78286, 78255, 78224, 78192, 78161, 78130, 78099, 78068, 78036, 78005, 77974, 77943, 77912, 77881, 77850, 77819, 77788, 77757, 77726, 77695, 77664, 77633, 77602, 77571, 77540, 77509, 77478, 77448, 77417, 77386, 77355, 77324, 77294, 77263, 77232, 77201]
private theorem words12497_eq : (List.range' 12497 64).map threshold = words12497 := by decide
private def words12561 : List Nat := [77171, 77140, 77109, 77078, 77048, 77017, 76987, 76956, 76925, 76895, 76864, 76834, 76803, 76772, 76742, 76711, 76681, 76650, 76620, 76590, 76559, 76529, 76498, 76468, 76438, 76407, 76377, 76347, 76316, 76286, 76256, 76225, 76195, 76165, 76135, 76104, 76074, 76044, 76014, 75984, 75953, 75923, 75893, 75863, 75833, 75803, 75773, 75743, 75713, 75683, 75653, 75623, 75593, 75563, 75533, 75503, 75473, 75443, 75413, 75383, 75354, 75324, 75294, 75264]
private theorem words12561_eq : (List.range' 12561 64).map threshold = words12561 := by decide
private def words12625 : List Nat := [75234, 75205, 75175, 75145, 75115, 75086, 75056, 75026, 74996, 74967, 74937, 74907, 74878, 74848, 74819, 74789, 74759, 74730, 74700, 74671, 74641, 74612, 74582, 74553, 74523, 74494, 74464, 74435, 74406, 74376, 74347, 74317, 74288, 74259, 74229, 74200, 74171, 74141, 74112, 74083, 74054, 74024, 73995, 73966, 73937, 73908, 73879, 73849, 73820, 73791, 73762, 73733, 73704, 73675, 73646, 73617, 73588, 73559, 73530, 73501, 73472, 73443, 73414, 73385]
private theorem words12625_eq : (List.range' 12625 64).map threshold = words12625 := by decide
private def words12689 : List Nat := [73356, 73327, 73298, 73269, 73241, 73212, 73183, 73154, 73125, 73096, 73068, 73039, 73010, 72981, 72953, 72924, 72895, 72867, 72838, 72809, 72781, 72752, 72723, 72695, 72666, 72638, 72609, 72581, 72552, 72523, 72495, 72466, 72438, 72410, 72381, 72353, 72324, 72296, 72267, 72239, 72211, 72182, 72154, 72126, 72097, 72069, 72041, 72012, 71984, 71956, 71928, 71899, 71871, 71843, 71815, 71787, 71759, 71730, 71702, 71674, 71646, 71618, 71590, 71562]
private theorem words12689_eq : (List.range' 12689 64).map threshold = words12689 := by decide
private def words12753 : List Nat := [71534, 71506, 71478, 71450, 71422, 71394, 71366, 71338, 71310, 71282, 71254, 71226, 71198, 71170, 71142, 71115, 71087, 71059, 71031, 71003, 70975, 70948, 70920, 70892, 70864, 70837, 70809, 70781, 70754, 70726, 70698, 70671, 70643, 70615, 70588, 70560, 70533, 70505, 70477, 70450, 70422, 70395, 70367, 70340, 70312, 70285, 70257, 70230, 70203, 70175, 70148, 70120, 70093, 70066, 70038, 70011, 69984, 69956, 69929, 69902, 69874, 69847, 69820, 69793]
private theorem words12753_eq : (List.range' 12753 64).map threshold = words12753 := by decide
private def words12817 : List Nat := [69766, 69738, 69711, 69684, 69657, 69630, 69602, 69575, 69548, 69521, 69494, 69467, 69440, 69413, 69386, 69359, 69332, 69305, 69278, 69251, 69224, 69197, 69170, 69143, 69116, 69089, 69062, 69035, 69008, 68982, 68955, 68928, 68901, 68874, 68848, 68821, 68794, 68767, 68740, 68714, 68687, 68660, 68634, 68607, 68580, 68554, 68527, 68500, 68474, 68447, 68421, 68394, 68367, 68341, 68314, 68288, 68261, 68235, 68208, 68182, 68155, 68129, 68102, 68076]
private theorem words12817_eq : (List.range' 12817 64).map threshold = words12817 := by decide
private def words12881 : List Nat := [68050, 68023, 67997, 67970, 67944, 67918, 67891, 67865, 67839, 67812, 67786, 67760, 67733, 67707, 67681, 67655, 67628, 67602, 67576, 67550, 67524, 67497, 67471, 67445, 67419, 67393, 67367, 67341, 67315, 67289, 67263, 67237, 67210, 67184, 67158, 67132, 67106, 67081, 67055, 67029, 67003, 66977, 66951, 66925, 66899, 66873, 66847, 66821, 66796, 66770, 66744, 66718, 66692, 66667, 66641, 66615, 66589, 66564, 66538, 66512, 66487, 66461, 66435, 66410]
private theorem words12881_eq : (List.range' 12881 64).map threshold = words12881 := by decide
private def words12945 : List Nat := [66384, 66358, 66333, 66307, 66281, 66256, 66230, 66205, 66179, 66154, 66128, 66103, 66077, 66052, 66026, 66001, 65975, 65950, 65924, 65899, 65873, 65848, 65823, 65797, 65772, 65747, 65721, 65696, 65671, 65645, 65620, 65595, 65569, 65544, 65519, 65494, 65468, 65443, 65418, 65393, 65368, 65343, 65317, 65292, 65267, 65242, 65217, 65192, 65167, 65142, 65117, 65092, 65066, 65041, 65016, 64991, 64966, 64941, 64916, 64892, 64867, 64842, 64817, 64792]
private theorem words12945_eq : (List.range' 12945 64).map threshold = words12945 := by decide
private def words13009 : List Nat := [64767, 64742, 64717, 64692, 64667, 64643, 64618, 64593, 64568, 64543, 64519, 64494, 64469, 64444, 64420, 64395, 64370, 64345, 64321, 64296, 64271, 64247, 64222, 64197, 64173, 64148, 64124, 64099, 64074, 64050, 64025, 64001, 63976, 63952, 63927, 63903, 63878, 63854, 63829, 63805, 63780, 63756, 63731, 63707, 63683, 63658, 63634, 63610, 63585, 63561, 63536, 63512, 63488, 63464, 63439, 63415, 63391, 63366, 63342, 63318, 63294, 63270, 63245, 63221]
private theorem words13009_eq : (List.range' 13009 64).map threshold = words13009 := by decide
private def words13073 : List Nat := [63197, 63173, 63149, 63125, 63100, 63076, 63052, 63028, 63004, 62980, 62956, 62932, 62908, 62884, 62860, 62836, 62812, 62788, 62764, 62740, 62716, 62692, 62668, 62644, 62620, 62596, 62572, 62548, 62525, 62501, 62477, 62453, 62429, 62405, 62382, 62358, 62334, 62310, 62286, 62263, 62239, 62215, 62192, 62168, 62144, 62120, 62097, 62073, 62049, 62026, 62002, 61979, 61955, 61931, 61908, 61884, 61861, 61837, 61814, 61790, 61767, 61743, 61720, 61696]
private theorem words13073_eq : (List.range' 13073 64).map threshold = words13073 := by decide
private def words13137 : List Nat := [61673, 61649, 61626, 61602, 61579, 61555, 61532, 61508, 61485, 61462, 61438, 61415, 61392, 61368, 61345, 61322, 61298, 61275, 61252, 61228, 61205, 61182, 61159, 61135, 61112, 61089, 61066, 61043, 61019, 60996, 60973, 60950, 60927, 60904, 60881, 60858, 60834, 60811, 60788, 60765, 60742, 60719, 60696, 60673, 60650, 60627, 60604, 60581, 60558, 60535, 60512, 60489, 60466, 60443, 60420, 60398, 60375, 60352, 60329, 60306, 60283, 60260, 60238, 60215]
private theorem words13137_eq : (List.range' 13137 64).map threshold = words13137 := by decide
private def words13201 : List Nat := [60192, 60169, 60146, 60124, 60101, 60078, 60055, 60033, 60010, 59987, 59965, 59942, 59919, 59896, 59874, 59851, 59829, 59806, 59783, 59761, 59738, 59716, 59693, 59670, 59648, 59625, 59603, 59580, 59558, 59535, 59513, 59490, 59468, 59445, 59423, 59400, 59378, 59355, 59333, 59311, 59288, 59266, 59244, 59221, 59199, 59176, 59154, 59132, 59110, 59087, 59065, 59043, 59020, 58998, 58976, 58954, 58931, 58909, 58887, 58865, 58843, 58820, 58798, 58776]
private theorem words13201_eq : (List.range' 13201 64).map threshold = words13201 := by decide
private def words13265 : List Nat := [58754, 58732, 58710, 58687, 58665, 58643, 58621, 58599, 58577, 58555, 58533, 58511, 58489, 58467, 58445, 58423, 58401, 58379, 58357, 58335, 58313, 58291, 58269, 58247, 58225, 58203, 58181, 58160, 58138, 58116, 58094, 58072, 58050, 58028, 58007, 57985, 57963, 57941, 57920, 57898, 57876, 57854, 57833, 57811, 57789, 57767, 57746, 57724, 57702, 57681, 57659, 57637, 57616, 57594, 57572, 57551, 57529, 57508, 57486, 57465, 57443, 57421, 57400, 57378]
private theorem words13265_eq : (List.range' 13265 64).map threshold = words13265 := by decide
private def words13329 : List Nat := [57357, 57335, 57314, 57292, 57271, 57249, 57228, 57206, 57185, 57164, 57142, 57121, 57099, 57078, 57057, 57035, 57014, 56992, 56971, 56950, 56928, 56907, 56886, 56864, 56843, 56822, 56801, 56779, 56758, 56737, 56716, 56694, 56673, 56652, 56631, 56610, 56588, 56567, 56546, 56525, 56504, 56483, 56462, 56441, 56419, 56398, 56377, 56356, 56335, 56314, 56293, 56272, 56251, 56230, 56209, 56188, 56167, 56146, 56125, 56104, 56083, 56062, 56041, 56020]
private theorem words13329_eq : (List.range' 13329 64).map threshold = words13329 := by decide
private def words13393 : List Nat := [55999, 55979, 55958, 55937, 55916, 55895, 55874, 55853, 55832, 55812, 55791, 55770, 55749, 55728, 55708, 55687, 55666, 55645, 55625, 55604, 55583, 55562, 55542, 55521, 55500, 55480, 55459, 55438, 55418, 55397, 55376, 55356, 55335, 55315, 55294, 55273, 55253, 55232, 55212, 55191, 55171, 55150, 55130, 55109, 55089, 55068, 55048, 55027, 55007, 54986, 54966, 54945, 54925, 54904, 54884, 54864, 54843, 54823, 54802, 54782, 54762, 54741, 54721, 54701]
private theorem words13393_eq : (List.range' 13393 64).map threshold = words13393 := by decide
private def words13457 : List Nat := [54680, 54660, 54640, 54619, 54599, 54579, 54559, 54538, 54518, 54498, 54478, 54457, 54437, 54417, 54397, 54377, 54356, 54336, 54316, 54296, 54276, 54256, 54236, 54215, 54195, 54175, 54155, 54135, 54115, 54095, 54075, 54055, 54035, 54015, 53995, 53975, 53955, 53935, 53915, 53895, 53875, 53855, 53835, 53815, 53795, 53775, 53755, 53735, 53716, 53696, 53676, 53656, 53636, 53616, 53596, 53577, 53557, 53537, 53517, 53497, 53478, 53458, 53438, 53418]
private theorem words13457_eq : (List.range' 13457 64).map threshold = words13457 := by decide
private def words13521 : List Nat := [53398, 53379, 53359, 53339, 53320, 53300, 53280, 53260, 53241, 53221, 53201, 53182, 53162, 53142, 53123, 53103, 53084, 53064, 53044, 53025, 53005, 52986, 52966, 52947, 52927, 52908, 52888, 52868, 52849, 52829, 52810, 52791, 52771, 52752, 52732, 52713, 52693, 52674, 52654, 52635, 52616, 52596, 52577, 52557, 52538, 52519, 52499, 52480, 52461, 52441, 52422, 52403, 52383, 52364, 52345, 52326, 52306, 52287, 52268, 52249, 52229, 52210, 52191, 52172]
private theorem words13521_eq : (List.range' 13521 64).map threshold = words13521 := by decide
private def words13585 : List Nat := [52152, 52133, 52114, 52095, 52076, 52057, 52037, 52018, 51999, 51980, 51961, 51942, 51923, 51904, 51885, 51865, 51846, 51827, 51808, 51789, 51770, 51751, 51732, 51713, 51694, 51675, 51656, 51637, 51618, 51599, 51580, 51561, 51543, 51524, 51505, 51486, 51467, 51448, 51429, 51410, 51391, 51373, 51354, 51335, 51316, 51297, 51278, 51260, 51241, 51222, 51203, 51184, 51166, 51147, 51128, 51109, 51091, 51072, 51053, 51035, 51016, 50997, 50978, 50960]
private theorem words13585_eq : (List.range' 13585 64).map threshold = words13585 := by decide
private def words13649 : List Nat := [50941, 50922, 50904, 50885, 50867, 50848, 50829, 50811, 50792, 50774, 50755, 50736, 50718, 50699, 50681, 50662, 50644, 50625, 50607, 50588, 50570, 50551, 50533, 50514, 50496, 50477, 50459, 50440, 50422, 50403, 50385, 50367, 50348, 50330, 50311, 50293, 50275, 50256, 50238, 50220, 50201, 50183, 50165, 50146, 50128, 50110, 50091, 50073, 50055, 50037, 50018, 50000, 49982, 49964, 49945, 49927, 49909, 49891, 49872, 49854, 49836, 49818, 49800, 49782]
private theorem words13649_eq : (List.range' 13649 64).map threshold = words13649 := by decide
private def words13713 : List Nat := [49763, 49745, 49727, 49709, 49691, 49673, 49655, 49637, 49619, 49600, 49582, 49564, 49546, 49528, 49510, 49492, 49474, 49456, 49438, 49420, 49402, 49384, 49366, 49348, 49330, 49312, 49294, 49276, 49258, 49241, 49223, 49205, 49187, 49169, 49151, 49133, 49115, 49097, 49080, 49062, 49044, 49026, 49008, 48991, 48973, 48955, 48937, 48919, 48902, 48884, 48866, 48848, 48831, 48813, 48795, 48777, 48760, 48742, 48724, 48707, 48689, 48671, 48654, 48636]
private theorem words13713_eq : (List.range' 13713 64).map threshold = words13713 := by decide
private def words13777 : List Nat := [48618, 48601, 48583, 48565, 48548, 48530, 48513, 48495, 48477, 48460, 48442, 48425, 48407, 48390, 48372, 48354, 48337, 48319, 48302, 48284, 48267, 48249, 48232, 48214, 48197, 48180, 48162, 48145, 48127, 48110, 48092, 48075, 48058, 48040, 48023, 48005, 47988, 47971, 47953, 47936, 47919, 47901, 47884, 47867, 47849, 47832, 47815, 47797, 47780, 47763, 47746, 47728, 47711, 47694, 47677, 47659, 47642, 47625, 47608, 47590, 47573, 47556, 47539, 47522]
private theorem words13777_eq : (List.range' 13777 64).map threshold = words13777 := by decide
private def words13841 : List Nat := [47505, 47487, 47470, 47453, 47436, 47419, 47402, 47385, 47368, 47350, 47333, 47316, 47299, 47282, 47265, 47248, 47231, 47214, 47197, 47180, 47163, 47146, 47129, 47112, 47095, 47078, 47061, 47044, 47027, 47010, 46993, 46976, 46959, 46942, 46925, 46908, 46892, 46875, 46858, 46841, 46824, 46807, 46790, 46773, 46757, 46740, 46723, 46706, 46689, 46673, 46656, 46639, 46622, 46605, 46589, 46572, 46555, 46538, 46522, 46505, 46488, 46471, 46455, 46438]
private theorem words13841_eq : (List.range' 13841 64).map threshold = words13841 := by decide
private def words13905 : List Nat := [46421, 46405, 46388, 46371, 46355, 46338, 46321, 46305, 46288, 46271, 46255, 46238, 46222, 46205, 46188, 46172, 46155, 46139, 46122, 46106, 46089, 46072, 46056, 46039, 46023, 46006, 45990, 45973, 45957, 45940, 45924, 45907, 45891, 45874, 45858, 45842, 45825, 45809, 45792, 45776, 45759, 45743, 45727, 45710, 45694, 45677, 45661, 45645, 45628, 45612, 45596, 45579, 45563, 45547, 45530, 45514, 45498, 45481, 45465, 45449, 45433, 45416, 45400, 45384]
private theorem words13905_eq : (List.range' 13905 64).map threshold = words13905 := by decide
private def words13969 : List Nat := [45368, 45351, 45335, 45319, 45303, 45287, 45270, 45254, 45238, 45222, 45206, 45189, 45173, 45157, 45141, 45125, 45109, 45093, 45076, 45060, 45044, 45028, 45012, 44996, 44980, 44964, 44948, 44932, 44916, 44900, 44884, 44868, 44852, 44836, 44820, 44804, 44788, 44772, 44756, 44740, 44724, 44708, 44692, 44676, 44660, 44644, 44628, 44612, 44596, 44580, 44564, 44548, 44533, 44517, 44501, 44485, 44469, 44453, 44437, 44422, 44406, 44390, 44374, 44358]
private theorem words13969_eq : (List.range' 13969 64).map threshold = words13969 := by decide
private def words14033 : List Nat := [44343, 44327, 44311, 44295, 44279, 44264, 44248, 44232, 44216, 44201, 44185, 44169, 44153, 44138, 44122, 44106, 44091, 44075, 44059, 44044, 44028, 44012, 43997, 43981, 43965, 43950, 43934, 43918, 43903, 43887, 43872, 43856, 43840, 43825, 43809, 43794, 43778, 43763, 43747, 43731, 43716, 43700, 43685, 43669, 43654, 43638, 43623, 43607, 43592, 43576, 43561, 43545, 43530, 43515, 43499, 43484, 43468, 43453, 43437, 43422, 43407, 43391, 43376, 43360]
private theorem words14033_eq : (List.range' 14033 64).map threshold = words14033 := by decide
private def words14097 : List Nat := [43345, 43330, 43314, 43299, 43284, 43268, 43253, 43238, 43222, 43207, 43192, 43176, 43161, 43146, 43130, 43115, 43100, 43085, 43069, 43054, 43039, 43024, 43008, 42993, 42978, 42963, 42948, 42932, 42917, 42902, 42887, 42872, 42856, 42841, 42826, 42811, 42796, 42781, 42766, 42750, 42735, 42720, 42705, 42690, 42675, 42660, 42645, 42630, 42615, 42600, 42584, 42569, 42554, 42539, 42524, 42509, 42494, 42479, 42464, 42449, 42434, 42419, 42404, 42389]
private theorem words14097_eq : (List.range' 14097 64).map threshold = words14097 := by decide
private def words14161 : List Nat := [42374, 42359, 42344, 42330, 42315, 42300, 42285, 42270, 42255, 42240, 42225, 42210, 42195, 42180, 42166, 42151, 42136, 42121, 42106, 42091, 42076, 42062, 42047, 42032, 42017, 42002, 41987, 41973, 41958, 41943, 41928, 41914, 41899, 41884, 41869, 41855, 41840, 41825, 41810, 41796, 41781, 41766, 41752, 41737, 41722, 41707, 41693, 41678, 41663, 41649, 41634, 41619, 41605, 41590, 41576, 41561, 41546, 41532, 41517, 41503, 41488, 41473, 41459, 41444]
private theorem words14161_eq : (List.range' 14161 64).map threshold = words14161 := by decide
private def words14225 : List Nat := [41430, 41415, 41401, 41386, 41371, 41357, 41342, 41328, 41313, 41299, 41284, 41270, 41255, 41241, 41226, 41212, 41197, 41183, 41169, 41154, 41140, 41125, 41111, 41096, 41082, 41068, 41053, 41039, 41024, 41010, 40996, 40981, 40967, 40952, 40938, 40924, 40909, 40895, 40881, 40866, 40852, 40838, 40823, 40809, 40795, 40781, 40766, 40752, 40738, 40723, 40709, 40695, 40681, 40666, 40652, 40638, 40624, 40610, 40595, 40581, 40567, 40553, 40538, 40524]
private theorem words14225_eq : (List.range' 14225 64).map threshold = words14225 := by decide
private def words14289 : List Nat := [40510, 40496, 40482, 40468, 40453, 40439, 40425, 40411, 40397, 40383, 40369, 40355, 40340, 40326, 40312, 40298, 40284, 40270, 40256, 40242, 40228, 40214, 40200, 40186, 40172, 40158, 40144, 40130, 40116, 40102, 40088, 40074, 40060, 40046, 40032, 40018, 40004, 39990, 39976, 39962, 39948, 39934, 39920, 39906, 39892, 39878, 39864, 39850, 39837, 39823, 39809, 39795, 39781, 39767, 39753, 39739, 39726, 39712, 39698, 39684, 39670, 39656, 39643, 39629]
private theorem words14289_eq : (List.range' 14289 64).map threshold = words14289 := by decide
private def words14353 : List Nat := [39615, 39601, 39587, 39574, 39560, 39546, 39532, 39519, 39505, 39491, 39477, 39464, 39450, 39436, 39422, 39409, 39395, 39381, 39368, 39354, 39340, 39326, 39313, 39299, 39285, 39272, 39258, 39244, 39231, 39217, 39204, 39190, 39176, 39163, 39149, 39135, 39122, 39108, 39095, 39081, 39068, 39054, 39040, 39027, 39013, 39000, 38986, 38973, 38959, 38946, 38932, 38919, 38905, 38892, 38878, 38865, 38851, 38838, 38824, 38811, 38797, 38784, 38770, 38757]
private theorem words14353_eq : (List.range' 14353 64).map threshold = words14353 := by decide
private def words14417 : List Nat := [38743, 38730, 38717, 38703, 38690, 38676, 38663, 38650, 38636, 38623, 38609, 38596, 38583, 38569, 38556, 38543, 38529, 38516, 38502, 38489, 38476, 38463, 38449, 38436, 38423, 38409, 38396, 38383, 38369, 38356, 38343, 38330, 38316, 38303, 38290, 38277, 38263, 38250, 38237, 38224, 38210, 38197, 38184, 38171, 38158, 38144, 38131, 38118, 38105, 38092, 38079, 38065, 38052, 38039, 38026, 38013, 38000, 37987, 37973, 37960, 37947, 37934, 37921, 37908]
private theorem words14417_eq : (List.range' 14417 64).map threshold = words14417 := by decide
private def words14481 : List Nat := [37895, 37882, 37869, 37856, 37843, 37829, 37816, 37803, 37790, 37777, 37764, 37751, 37738, 37725, 37712, 37699, 37686, 37673, 37660, 37647, 37634, 37621, 37608, 37595, 37582, 37569, 37556, 37544, 37531, 37518, 37505, 37492, 37479, 37466, 37453, 37440, 37427, 37414, 37402, 37389, 37376, 37363, 37350, 37337, 37324, 37311, 37299, 37286, 37273, 37260, 37247, 37235, 37222, 37209, 37196, 37183, 37171, 37158, 37145, 37132, 37119, 37107, 37094, 37081]
private theorem words14481_eq : (List.range' 14481 64).map threshold = words14481 := by decide
private def words14545 : List Nat := [37068, 37056, 37043, 37030, 37018, 37005, 36992, 36979, 36967, 36954, 36941, 36929, 36916, 36903, 36891, 36878, 36865, 36853, 36840, 36827, 36815, 36802, 36789, 36777, 36764, 36752, 36739, 36726, 36714, 36701, 36689, 36676, 36663, 36651, 36638, 36626, 36613, 36601, 36588, 36575, 36563, 36550, 36538, 36525, 36513, 36500, 36488, 36475, 36463, 36450, 36438, 36425, 36413, 36400, 36388, 36375, 36363, 36351, 36338, 36326, 36313, 36301, 36288, 36276]
private theorem words14545_eq : (List.range' 14545 64).map threshold = words14545 := by decide
private def words14609 : List Nat := [36264, 36251, 36239, 36226, 36214, 36202, 36189, 36177, 36164, 36152, 36140, 36127, 36115, 36103, 36090, 36078, 36066, 36053, 36041, 36029, 36016, 36004, 35992, 35979, 35967, 35955, 35943, 35930, 35918, 35906, 35893, 35881, 35869, 35857, 35845, 35832, 35820, 35808, 35796, 35783, 35771, 35759, 35747, 35735, 35722, 35710, 35698, 35686, 35674, 35661, 35649, 35637, 35625, 35613, 35601, 35589, 35576, 35564, 35552, 35540, 35528, 35516, 35504, 35492]
private theorem words14609_eq : (List.range' 14609 64).map threshold = words14609 := by decide
private def words14673 : List Nat := [35480, 35467, 35455, 35443, 35431, 35419, 35407, 35395, 35383, 35371, 35359, 35347, 35335, 35323, 35311, 35299, 35287, 35275, 35263, 35251, 35239, 35227, 35215, 35203, 35191, 35179, 35167, 35155, 35143, 35131, 35119, 35107, 35095, 35083, 35071, 35059, 35048, 35036, 35024, 35012, 35000, 34988, 34976, 34964, 34952, 34940, 34929, 34917, 34905, 34893, 34881, 34869, 34858, 34846, 34834, 34822, 34810, 34798, 34787, 34775, 34763, 34751, 34739, 34728]
private theorem words14673_eq : (List.range' 14673 64).map threshold = words14673 := by decide
private def words14737 : List Nat := [34716, 34704, 34692, 34681, 34669, 34657, 34645, 34633, 34622, 34610, 34598, 34587, 34575, 34563, 34551, 34540, 34528, 34516, 34505, 34493, 34481, 34470, 34458, 34446, 34435, 34423, 34411, 34400, 34388, 34376, 34365, 34353, 34341, 34330, 34318, 34306, 34295, 34283, 34272, 34260, 34248, 34237, 34225, 34214, 34202, 34191, 34179, 34167, 34156, 34144, 34133, 34121, 34110, 34098, 34087, 34075, 34064, 34052, 34041, 34029, 34018, 34006, 33995, 33983]
private theorem words14737_eq : (List.range' 14737 64).map threshold = words14737 := by decide
private def words14801 : List Nat := [33972, 33960, 33949, 33937, 33926, 33914, 33903, 33892, 33880, 33869, 33857, 33846, 33834, 33823, 33812, 33800, 33789, 33777, 33766, 33755, 33743, 33732, 33720, 33709, 33698, 33686, 33675, 33664, 33652, 33641, 33630, 33618, 33607, 33596, 33584, 33573, 33562, 33550, 33539, 33528, 33516, 33505, 33494, 33483, 33471, 33460, 33449, 33437, 33426, 33415, 33404, 33392, 33381, 33370, 33359, 33348, 33336, 33325, 33314, 33303, 33291, 33280, 33269, 33258]
private theorem words14801_eq : (List.range' 14801 64).map threshold = words14801 := by decide
private def words14865 : List Nat := [33247, 33235, 33224, 33213, 33202, 33191, 33180, 33169, 33157, 33146, 33135, 33124, 33113, 33102, 33091, 33079, 33068, 33057, 33046, 33035, 33024, 33013, 33002, 32991, 32980, 32969, 32957, 32946, 32935, 32924, 32913, 32902, 32891, 32880, 32869, 32858, 32847, 32836, 32825, 32814, 32803, 32792, 32781, 32770, 32759]
private theorem words14865_eq : (List.range' 14865 45).map threshold = words14865 := by decide
private def part0 := words17 ++ words81
private theorem part0_eq : (List.range' 17 128).map threshold = part0 := join (s:=17) (m:=64) (n:=64) words17_eq words81_eq
private def part1 := words145 ++ words209
private theorem part1_eq : (List.range' 145 128).map threshold = part1 := join (s:=145) (m:=64) (n:=64) words145_eq words209_eq
private def part2 := words273 ++ words337
private theorem part2_eq : (List.range' 273 128).map threshold = part2 := join (s:=273) (m:=64) (n:=64) words273_eq words337_eq
private def part3 := words401 ++ words465
private theorem part3_eq : (List.range' 401 128).map threshold = part3 := join (s:=401) (m:=64) (n:=64) words401_eq words465_eq
private def part4 := words529 ++ words593
private theorem part4_eq : (List.range' 529 128).map threshold = part4 := join (s:=529) (m:=64) (n:=64) words529_eq words593_eq
private def part5 := words657 ++ words721
private theorem part5_eq : (List.range' 657 128).map threshold = part5 := join (s:=657) (m:=64) (n:=64) words657_eq words721_eq
private def part6 := words785 ++ words849
private theorem part6_eq : (List.range' 785 128).map threshold = part6 := join (s:=785) (m:=64) (n:=64) words785_eq words849_eq
private def part7 := words913 ++ words977
private theorem part7_eq : (List.range' 913 128).map threshold = part7 := join (s:=913) (m:=64) (n:=64) words913_eq words977_eq
private def part8 := words1041 ++ words1105
private theorem part8_eq : (List.range' 1041 128).map threshold = part8 := join (s:=1041) (m:=64) (n:=64) words1041_eq words1105_eq
private def part9 := words1169 ++ words1233
private theorem part9_eq : (List.range' 1169 128).map threshold = part9 := join (s:=1169) (m:=64) (n:=64) words1169_eq words1233_eq
private def part10 := words1297 ++ words1361
private theorem part10_eq : (List.range' 1297 128).map threshold = part10 := join (s:=1297) (m:=64) (n:=64) words1297_eq words1361_eq
private def part11 := words1425 ++ words1489
private theorem part11_eq : (List.range' 1425 128).map threshold = part11 := join (s:=1425) (m:=64) (n:=64) words1425_eq words1489_eq
private def part12 := words1553 ++ words1617
private theorem part12_eq : (List.range' 1553 128).map threshold = part12 := join (s:=1553) (m:=64) (n:=64) words1553_eq words1617_eq
private def part13 := words1681 ++ words1745
private theorem part13_eq : (List.range' 1681 128).map threshold = part13 := join (s:=1681) (m:=64) (n:=64) words1681_eq words1745_eq
private def part14 := words1809 ++ words1873
private theorem part14_eq : (List.range' 1809 128).map threshold = part14 := join (s:=1809) (m:=64) (n:=64) words1809_eq words1873_eq
private def part15 := words1937 ++ words2001
private theorem part15_eq : (List.range' 1937 128).map threshold = part15 := join (s:=1937) (m:=64) (n:=64) words1937_eq words2001_eq
private def part16 := words2065 ++ words2129
private theorem part16_eq : (List.range' 2065 128).map threshold = part16 := join (s:=2065) (m:=64) (n:=64) words2065_eq words2129_eq
private def part17 := words2193 ++ words2257
private theorem part17_eq : (List.range' 2193 128).map threshold = part17 := join (s:=2193) (m:=64) (n:=64) words2193_eq words2257_eq
private def part18 := words2321 ++ words2385
private theorem part18_eq : (List.range' 2321 128).map threshold = part18 := join (s:=2321) (m:=64) (n:=64) words2321_eq words2385_eq
private def part19 := words2449 ++ words2513
private theorem part19_eq : (List.range' 2449 128).map threshold = part19 := join (s:=2449) (m:=64) (n:=64) words2449_eq words2513_eq
private def part20 := words2577 ++ words2641
private theorem part20_eq : (List.range' 2577 128).map threshold = part20 := join (s:=2577) (m:=64) (n:=64) words2577_eq words2641_eq
private def part21 := words2705 ++ words2769
private theorem part21_eq : (List.range' 2705 128).map threshold = part21 := join (s:=2705) (m:=64) (n:=64) words2705_eq words2769_eq
private def part22 := words2833 ++ words2897
private theorem part22_eq : (List.range' 2833 128).map threshold = part22 := join (s:=2833) (m:=64) (n:=64) words2833_eq words2897_eq
private def part23 := words2961 ++ words3025
private theorem part23_eq : (List.range' 2961 128).map threshold = part23 := join (s:=2961) (m:=64) (n:=64) words2961_eq words3025_eq
private def part24 := words3089 ++ words3153
private theorem part24_eq : (List.range' 3089 128).map threshold = part24 := join (s:=3089) (m:=64) (n:=64) words3089_eq words3153_eq
private def part25 := words3217 ++ words3281
private theorem part25_eq : (List.range' 3217 128).map threshold = part25 := join (s:=3217) (m:=64) (n:=64) words3217_eq words3281_eq
private def part26 := words3345 ++ words3409
private theorem part26_eq : (List.range' 3345 128).map threshold = part26 := join (s:=3345) (m:=64) (n:=64) words3345_eq words3409_eq
private def part27 := words3473 ++ words3537
private theorem part27_eq : (List.range' 3473 128).map threshold = part27 := join (s:=3473) (m:=64) (n:=64) words3473_eq words3537_eq
private def part28 := words3601 ++ words3665
private theorem part28_eq : (List.range' 3601 128).map threshold = part28 := join (s:=3601) (m:=64) (n:=64) words3601_eq words3665_eq
private def part29 := words3729 ++ words3793
private theorem part29_eq : (List.range' 3729 128).map threshold = part29 := join (s:=3729) (m:=64) (n:=64) words3729_eq words3793_eq
private def part30 := words3857 ++ words3921
private theorem part30_eq : (List.range' 3857 128).map threshold = part30 := join (s:=3857) (m:=64) (n:=64) words3857_eq words3921_eq
private def part31 := words3985 ++ words4049
private theorem part31_eq : (List.range' 3985 128).map threshold = part31 := join (s:=3985) (m:=64) (n:=64) words3985_eq words4049_eq
private def part32 := words4113 ++ words4177
private theorem part32_eq : (List.range' 4113 128).map threshold = part32 := join (s:=4113) (m:=64) (n:=64) words4113_eq words4177_eq
private def part33 := words4241 ++ words4305
private theorem part33_eq : (List.range' 4241 128).map threshold = part33 := join (s:=4241) (m:=64) (n:=64) words4241_eq words4305_eq
private def part34 := words4369 ++ words4433
private theorem part34_eq : (List.range' 4369 128).map threshold = part34 := join (s:=4369) (m:=64) (n:=64) words4369_eq words4433_eq
private def part35 := words4497 ++ words4561
private theorem part35_eq : (List.range' 4497 128).map threshold = part35 := join (s:=4497) (m:=64) (n:=64) words4497_eq words4561_eq
private def part36 := words4625 ++ words4689
private theorem part36_eq : (List.range' 4625 128).map threshold = part36 := join (s:=4625) (m:=64) (n:=64) words4625_eq words4689_eq
private def part37 := words4753 ++ words4817
private theorem part37_eq : (List.range' 4753 128).map threshold = part37 := join (s:=4753) (m:=64) (n:=64) words4753_eq words4817_eq
private def part38 := words4881 ++ words4945
private theorem part38_eq : (List.range' 4881 128).map threshold = part38 := join (s:=4881) (m:=64) (n:=64) words4881_eq words4945_eq
private def part39 := words5009 ++ words5073
private theorem part39_eq : (List.range' 5009 128).map threshold = part39 := join (s:=5009) (m:=64) (n:=64) words5009_eq words5073_eq
private def part40 := words5137 ++ words5201
private theorem part40_eq : (List.range' 5137 128).map threshold = part40 := join (s:=5137) (m:=64) (n:=64) words5137_eq words5201_eq
private def part41 := words5265 ++ words5329
private theorem part41_eq : (List.range' 5265 128).map threshold = part41 := join (s:=5265) (m:=64) (n:=64) words5265_eq words5329_eq
private def part42 := words5393 ++ words5457
private theorem part42_eq : (List.range' 5393 128).map threshold = part42 := join (s:=5393) (m:=64) (n:=64) words5393_eq words5457_eq
private def part43 := words5521 ++ words5585
private theorem part43_eq : (List.range' 5521 128).map threshold = part43 := join (s:=5521) (m:=64) (n:=64) words5521_eq words5585_eq
private def part44 := words5649 ++ words5713
private theorem part44_eq : (List.range' 5649 128).map threshold = part44 := join (s:=5649) (m:=64) (n:=64) words5649_eq words5713_eq
private def part45 := words5777 ++ words5841
private theorem part45_eq : (List.range' 5777 128).map threshold = part45 := join (s:=5777) (m:=64) (n:=64) words5777_eq words5841_eq
private def part46 := words5905 ++ words5969
private theorem part46_eq : (List.range' 5905 128).map threshold = part46 := join (s:=5905) (m:=64) (n:=64) words5905_eq words5969_eq
private def part47 := words6033 ++ words6097
private theorem part47_eq : (List.range' 6033 128).map threshold = part47 := join (s:=6033) (m:=64) (n:=64) words6033_eq words6097_eq
private def part48 := words6161 ++ words6225
private theorem part48_eq : (List.range' 6161 128).map threshold = part48 := join (s:=6161) (m:=64) (n:=64) words6161_eq words6225_eq
private def part49 := words6289 ++ words6353
private theorem part49_eq : (List.range' 6289 128).map threshold = part49 := join (s:=6289) (m:=64) (n:=64) words6289_eq words6353_eq
private def part50 := words6417 ++ words6481
private theorem part50_eq : (List.range' 6417 128).map threshold = part50 := join (s:=6417) (m:=64) (n:=64) words6417_eq words6481_eq
private def part51 := words6545 ++ words6609
private theorem part51_eq : (List.range' 6545 128).map threshold = part51 := join (s:=6545) (m:=64) (n:=64) words6545_eq words6609_eq
private def part52 := words6673 ++ words6737
private theorem part52_eq : (List.range' 6673 128).map threshold = part52 := join (s:=6673) (m:=64) (n:=64) words6673_eq words6737_eq
private def part53 := words6801 ++ words6865
private theorem part53_eq : (List.range' 6801 128).map threshold = part53 := join (s:=6801) (m:=64) (n:=64) words6801_eq words6865_eq
private def part54 := words6929 ++ words6993
private theorem part54_eq : (List.range' 6929 128).map threshold = part54 := join (s:=6929) (m:=64) (n:=64) words6929_eq words6993_eq
private def part55 := words7057 ++ words7121
private theorem part55_eq : (List.range' 7057 128).map threshold = part55 := join (s:=7057) (m:=64) (n:=64) words7057_eq words7121_eq
private def part56 := words7185 ++ words7249
private theorem part56_eq : (List.range' 7185 128).map threshold = part56 := join (s:=7185) (m:=64) (n:=64) words7185_eq words7249_eq
private def part57 := words7313 ++ words7377
private theorem part57_eq : (List.range' 7313 128).map threshold = part57 := join (s:=7313) (m:=64) (n:=64) words7313_eq words7377_eq
private def part58 := words7441 ++ words7505
private theorem part58_eq : (List.range' 7441 128).map threshold = part58 := join (s:=7441) (m:=64) (n:=64) words7441_eq words7505_eq
private def part59 := words7569 ++ words7633
private theorem part59_eq : (List.range' 7569 128).map threshold = part59 := join (s:=7569) (m:=64) (n:=64) words7569_eq words7633_eq
private def part60 := words7697 ++ words7761
private theorem part60_eq : (List.range' 7697 128).map threshold = part60 := join (s:=7697) (m:=64) (n:=64) words7697_eq words7761_eq
private def part61 := words7825 ++ words7889
private theorem part61_eq : (List.range' 7825 128).map threshold = part61 := join (s:=7825) (m:=64) (n:=64) words7825_eq words7889_eq
private def part62 := words7953 ++ words8017
private theorem part62_eq : (List.range' 7953 128).map threshold = part62 := join (s:=7953) (m:=64) (n:=64) words7953_eq words8017_eq
private def part63 := words8081 ++ words8145
private theorem part63_eq : (List.range' 8081 128).map threshold = part63 := join (s:=8081) (m:=64) (n:=64) words8081_eq words8145_eq
private def part64 := words8209 ++ words8273
private theorem part64_eq : (List.range' 8209 128).map threshold = part64 := join (s:=8209) (m:=64) (n:=64) words8209_eq words8273_eq
private def part65 := words8337 ++ words8401
private theorem part65_eq : (List.range' 8337 128).map threshold = part65 := join (s:=8337) (m:=64) (n:=64) words8337_eq words8401_eq
private def part66 := words8465 ++ words8529
private theorem part66_eq : (List.range' 8465 128).map threshold = part66 := join (s:=8465) (m:=64) (n:=64) words8465_eq words8529_eq
private def part67 := words8593 ++ words8657
private theorem part67_eq : (List.range' 8593 128).map threshold = part67 := join (s:=8593) (m:=64) (n:=64) words8593_eq words8657_eq
private def part68 := words8721 ++ words8785
private theorem part68_eq : (List.range' 8721 128).map threshold = part68 := join (s:=8721) (m:=64) (n:=64) words8721_eq words8785_eq
private def part69 := words8849 ++ words8913
private theorem part69_eq : (List.range' 8849 128).map threshold = part69 := join (s:=8849) (m:=64) (n:=64) words8849_eq words8913_eq
private def part70 := words8977 ++ words9041
private theorem part70_eq : (List.range' 8977 128).map threshold = part70 := join (s:=8977) (m:=64) (n:=64) words8977_eq words9041_eq
private def part71 := words9105 ++ words9169
private theorem part71_eq : (List.range' 9105 128).map threshold = part71 := join (s:=9105) (m:=64) (n:=64) words9105_eq words9169_eq
private def part72 := words9233 ++ words9297
private theorem part72_eq : (List.range' 9233 128).map threshold = part72 := join (s:=9233) (m:=64) (n:=64) words9233_eq words9297_eq
private def part73 := words9361 ++ words9425
private theorem part73_eq : (List.range' 9361 128).map threshold = part73 := join (s:=9361) (m:=64) (n:=64) words9361_eq words9425_eq
private def part74 := words9489 ++ words9553
private theorem part74_eq : (List.range' 9489 128).map threshold = part74 := join (s:=9489) (m:=64) (n:=64) words9489_eq words9553_eq
private def part75 := words9617 ++ words9681
private theorem part75_eq : (List.range' 9617 128).map threshold = part75 := join (s:=9617) (m:=64) (n:=64) words9617_eq words9681_eq
private def part76 := words9745 ++ words9809
private theorem part76_eq : (List.range' 9745 128).map threshold = part76 := join (s:=9745) (m:=64) (n:=64) words9745_eq words9809_eq
private def part77 := words9873 ++ words9937
private theorem part77_eq : (List.range' 9873 128).map threshold = part77 := join (s:=9873) (m:=64) (n:=64) words9873_eq words9937_eq
private def part78 := words10001 ++ words10065
private theorem part78_eq : (List.range' 10001 128).map threshold = part78 := join (s:=10001) (m:=64) (n:=64) words10001_eq words10065_eq
private def part79 := words10129 ++ words10193
private theorem part79_eq : (List.range' 10129 128).map threshold = part79 := join (s:=10129) (m:=64) (n:=64) words10129_eq words10193_eq
private def part80 := words10257 ++ words10321
private theorem part80_eq : (List.range' 10257 128).map threshold = part80 := join (s:=10257) (m:=64) (n:=64) words10257_eq words10321_eq
private def part81 := words10385 ++ words10449
private theorem part81_eq : (List.range' 10385 128).map threshold = part81 := join (s:=10385) (m:=64) (n:=64) words10385_eq words10449_eq
private def part82 := words10513 ++ words10577
private theorem part82_eq : (List.range' 10513 128).map threshold = part82 := join (s:=10513) (m:=64) (n:=64) words10513_eq words10577_eq
private def part83 := words10641 ++ words10705
private theorem part83_eq : (List.range' 10641 128).map threshold = part83 := join (s:=10641) (m:=64) (n:=64) words10641_eq words10705_eq
private def part84 := words10769 ++ words10833
private theorem part84_eq : (List.range' 10769 128).map threshold = part84 := join (s:=10769) (m:=64) (n:=64) words10769_eq words10833_eq
private def part85 := words10897 ++ words10961
private theorem part85_eq : (List.range' 10897 128).map threshold = part85 := join (s:=10897) (m:=64) (n:=64) words10897_eq words10961_eq
private def part86 := words11025 ++ words11089
private theorem part86_eq : (List.range' 11025 128).map threshold = part86 := join (s:=11025) (m:=64) (n:=64) words11025_eq words11089_eq
private def part87 := words11153 ++ words11217
private theorem part87_eq : (List.range' 11153 128).map threshold = part87 := join (s:=11153) (m:=64) (n:=64) words11153_eq words11217_eq
private def part88 := words11281 ++ words11345
private theorem part88_eq : (List.range' 11281 128).map threshold = part88 := join (s:=11281) (m:=64) (n:=64) words11281_eq words11345_eq
private def part89 := words11409 ++ words11473
private theorem part89_eq : (List.range' 11409 128).map threshold = part89 := join (s:=11409) (m:=64) (n:=64) words11409_eq words11473_eq
private def part90 := words11537 ++ words11601
private theorem part90_eq : (List.range' 11537 128).map threshold = part90 := join (s:=11537) (m:=64) (n:=64) words11537_eq words11601_eq
private def part91 := words11665 ++ words11729
private theorem part91_eq : (List.range' 11665 128).map threshold = part91 := join (s:=11665) (m:=64) (n:=64) words11665_eq words11729_eq
private def part92 := words11793 ++ words11857
private theorem part92_eq : (List.range' 11793 128).map threshold = part92 := join (s:=11793) (m:=64) (n:=64) words11793_eq words11857_eq
private def part93 := words11921 ++ words11985
private theorem part93_eq : (List.range' 11921 128).map threshold = part93 := join (s:=11921) (m:=64) (n:=64) words11921_eq words11985_eq
private def part94 := words12049 ++ words12113
private theorem part94_eq : (List.range' 12049 128).map threshold = part94 := join (s:=12049) (m:=64) (n:=64) words12049_eq words12113_eq
private def part95 := words12177 ++ words12241
private theorem part95_eq : (List.range' 12177 128).map threshold = part95 := join (s:=12177) (m:=64) (n:=64) words12177_eq words12241_eq
private def part96 := words12305 ++ words12369
private theorem part96_eq : (List.range' 12305 128).map threshold = part96 := join (s:=12305) (m:=64) (n:=64) words12305_eq words12369_eq
private def part97 := words12433 ++ words12497
private theorem part97_eq : (List.range' 12433 128).map threshold = part97 := join (s:=12433) (m:=64) (n:=64) words12433_eq words12497_eq
private def part98 := words12561 ++ words12625
private theorem part98_eq : (List.range' 12561 128).map threshold = part98 := join (s:=12561) (m:=64) (n:=64) words12561_eq words12625_eq
private def part99 := words12689 ++ words12753
private theorem part99_eq : (List.range' 12689 128).map threshold = part99 := join (s:=12689) (m:=64) (n:=64) words12689_eq words12753_eq
private def part100 := words12817 ++ words12881
private theorem part100_eq : (List.range' 12817 128).map threshold = part100 := join (s:=12817) (m:=64) (n:=64) words12817_eq words12881_eq
private def part101 := words12945 ++ words13009
private theorem part101_eq : (List.range' 12945 128).map threshold = part101 := join (s:=12945) (m:=64) (n:=64) words12945_eq words13009_eq
private def part102 := words13073 ++ words13137
private theorem part102_eq : (List.range' 13073 128).map threshold = part102 := join (s:=13073) (m:=64) (n:=64) words13073_eq words13137_eq
private def part103 := words13201 ++ words13265
private theorem part103_eq : (List.range' 13201 128).map threshold = part103 := join (s:=13201) (m:=64) (n:=64) words13201_eq words13265_eq
private def part104 := words13329 ++ words13393
private theorem part104_eq : (List.range' 13329 128).map threshold = part104 := join (s:=13329) (m:=64) (n:=64) words13329_eq words13393_eq
private def part105 := words13457 ++ words13521
private theorem part105_eq : (List.range' 13457 128).map threshold = part105 := join (s:=13457) (m:=64) (n:=64) words13457_eq words13521_eq
private def part106 := words13585 ++ words13649
private theorem part106_eq : (List.range' 13585 128).map threshold = part106 := join (s:=13585) (m:=64) (n:=64) words13585_eq words13649_eq
private def part107 := words13713 ++ words13777
private theorem part107_eq : (List.range' 13713 128).map threshold = part107 := join (s:=13713) (m:=64) (n:=64) words13713_eq words13777_eq
private def part108 := words13841 ++ words13905
private theorem part108_eq : (List.range' 13841 128).map threshold = part108 := join (s:=13841) (m:=64) (n:=64) words13841_eq words13905_eq
private def part109 := words13969 ++ words14033
private theorem part109_eq : (List.range' 13969 128).map threshold = part109 := join (s:=13969) (m:=64) (n:=64) words13969_eq words14033_eq
private def part110 := words14097 ++ words14161
private theorem part110_eq : (List.range' 14097 128).map threshold = part110 := join (s:=14097) (m:=64) (n:=64) words14097_eq words14161_eq
private def part111 := words14225 ++ words14289
private theorem part111_eq : (List.range' 14225 128).map threshold = part111 := join (s:=14225) (m:=64) (n:=64) words14225_eq words14289_eq
private def part112 := words14353 ++ words14417
private theorem part112_eq : (List.range' 14353 128).map threshold = part112 := join (s:=14353) (m:=64) (n:=64) words14353_eq words14417_eq
private def part113 := words14481 ++ words14545
private theorem part113_eq : (List.range' 14481 128).map threshold = part113 := join (s:=14481) (m:=64) (n:=64) words14481_eq words14545_eq
private def part114 := words14609 ++ words14673
private theorem part114_eq : (List.range' 14609 128).map threshold = part114 := join (s:=14609) (m:=64) (n:=64) words14609_eq words14673_eq
private def part115 := words14737 ++ words14801
private theorem part115_eq : (List.range' 14737 128).map threshold = part115 := join (s:=14737) (m:=64) (n:=64) words14737_eq words14801_eq
private def part116 := part0 ++ part1
private theorem part116_eq : (List.range' 17 256).map threshold = part116 := join (s:=17) (m:=128) (n:=128) part0_eq part1_eq
private def part117 := part2 ++ part3
private theorem part117_eq : (List.range' 273 256).map threshold = part117 := join (s:=273) (m:=128) (n:=128) part2_eq part3_eq
private def part118 := part4 ++ part5
private theorem part118_eq : (List.range' 529 256).map threshold = part118 := join (s:=529) (m:=128) (n:=128) part4_eq part5_eq
private def part119 := part6 ++ part7
private theorem part119_eq : (List.range' 785 256).map threshold = part119 := join (s:=785) (m:=128) (n:=128) part6_eq part7_eq
private def part120 := part8 ++ part9
private theorem part120_eq : (List.range' 1041 256).map threshold = part120 := join (s:=1041) (m:=128) (n:=128) part8_eq part9_eq
private def part121 := part10 ++ part11
private theorem part121_eq : (List.range' 1297 256).map threshold = part121 := join (s:=1297) (m:=128) (n:=128) part10_eq part11_eq
private def part122 := part12 ++ part13
private theorem part122_eq : (List.range' 1553 256).map threshold = part122 := join (s:=1553) (m:=128) (n:=128) part12_eq part13_eq
private def part123 := part14 ++ part15
private theorem part123_eq : (List.range' 1809 256).map threshold = part123 := join (s:=1809) (m:=128) (n:=128) part14_eq part15_eq
private def part124 := part16 ++ part17
private theorem part124_eq : (List.range' 2065 256).map threshold = part124 := join (s:=2065) (m:=128) (n:=128) part16_eq part17_eq
private def part125 := part18 ++ part19
private theorem part125_eq : (List.range' 2321 256).map threshold = part125 := join (s:=2321) (m:=128) (n:=128) part18_eq part19_eq
private def part126 := part20 ++ part21
private theorem part126_eq : (List.range' 2577 256).map threshold = part126 := join (s:=2577) (m:=128) (n:=128) part20_eq part21_eq
private def part127 := part22 ++ part23
private theorem part127_eq : (List.range' 2833 256).map threshold = part127 := join (s:=2833) (m:=128) (n:=128) part22_eq part23_eq
private def part128 := part24 ++ part25
private theorem part128_eq : (List.range' 3089 256).map threshold = part128 := join (s:=3089) (m:=128) (n:=128) part24_eq part25_eq
private def part129 := part26 ++ part27
private theorem part129_eq : (List.range' 3345 256).map threshold = part129 := join (s:=3345) (m:=128) (n:=128) part26_eq part27_eq
private def part130 := part28 ++ part29
private theorem part130_eq : (List.range' 3601 256).map threshold = part130 := join (s:=3601) (m:=128) (n:=128) part28_eq part29_eq
private def part131 := part30 ++ part31
private theorem part131_eq : (List.range' 3857 256).map threshold = part131 := join (s:=3857) (m:=128) (n:=128) part30_eq part31_eq
private def part132 := part32 ++ part33
private theorem part132_eq : (List.range' 4113 256).map threshold = part132 := join (s:=4113) (m:=128) (n:=128) part32_eq part33_eq
private def part133 := part34 ++ part35
private theorem part133_eq : (List.range' 4369 256).map threshold = part133 := join (s:=4369) (m:=128) (n:=128) part34_eq part35_eq
private def part134 := part36 ++ part37
private theorem part134_eq : (List.range' 4625 256).map threshold = part134 := join (s:=4625) (m:=128) (n:=128) part36_eq part37_eq
private def part135 := part38 ++ part39
private theorem part135_eq : (List.range' 4881 256).map threshold = part135 := join (s:=4881) (m:=128) (n:=128) part38_eq part39_eq
private def part136 := part40 ++ part41
private theorem part136_eq : (List.range' 5137 256).map threshold = part136 := join (s:=5137) (m:=128) (n:=128) part40_eq part41_eq
private def part137 := part42 ++ part43
private theorem part137_eq : (List.range' 5393 256).map threshold = part137 := join (s:=5393) (m:=128) (n:=128) part42_eq part43_eq
private def part138 := part44 ++ part45
private theorem part138_eq : (List.range' 5649 256).map threshold = part138 := join (s:=5649) (m:=128) (n:=128) part44_eq part45_eq
private def part139 := part46 ++ part47
private theorem part139_eq : (List.range' 5905 256).map threshold = part139 := join (s:=5905) (m:=128) (n:=128) part46_eq part47_eq
private def part140 := part48 ++ part49
private theorem part140_eq : (List.range' 6161 256).map threshold = part140 := join (s:=6161) (m:=128) (n:=128) part48_eq part49_eq
private def part141 := part50 ++ part51
private theorem part141_eq : (List.range' 6417 256).map threshold = part141 := join (s:=6417) (m:=128) (n:=128) part50_eq part51_eq
private def part142 := part52 ++ part53
private theorem part142_eq : (List.range' 6673 256).map threshold = part142 := join (s:=6673) (m:=128) (n:=128) part52_eq part53_eq
private def part143 := part54 ++ part55
private theorem part143_eq : (List.range' 6929 256).map threshold = part143 := join (s:=6929) (m:=128) (n:=128) part54_eq part55_eq
private def part144 := part56 ++ part57
private theorem part144_eq : (List.range' 7185 256).map threshold = part144 := join (s:=7185) (m:=128) (n:=128) part56_eq part57_eq
private def part145 := part58 ++ part59
private theorem part145_eq : (List.range' 7441 256).map threshold = part145 := join (s:=7441) (m:=128) (n:=128) part58_eq part59_eq
private def part146 := part60 ++ part61
private theorem part146_eq : (List.range' 7697 256).map threshold = part146 := join (s:=7697) (m:=128) (n:=128) part60_eq part61_eq
private def part147 := part62 ++ part63
private theorem part147_eq : (List.range' 7953 256).map threshold = part147 := join (s:=7953) (m:=128) (n:=128) part62_eq part63_eq
private def part148 := part64 ++ part65
private theorem part148_eq : (List.range' 8209 256).map threshold = part148 := join (s:=8209) (m:=128) (n:=128) part64_eq part65_eq
private def part149 := part66 ++ part67
private theorem part149_eq : (List.range' 8465 256).map threshold = part149 := join (s:=8465) (m:=128) (n:=128) part66_eq part67_eq
private def part150 := part68 ++ part69
private theorem part150_eq : (List.range' 8721 256).map threshold = part150 := join (s:=8721) (m:=128) (n:=128) part68_eq part69_eq
private def part151 := part70 ++ part71
private theorem part151_eq : (List.range' 8977 256).map threshold = part151 := join (s:=8977) (m:=128) (n:=128) part70_eq part71_eq
private def part152 := part72 ++ part73
private theorem part152_eq : (List.range' 9233 256).map threshold = part152 := join (s:=9233) (m:=128) (n:=128) part72_eq part73_eq
private def part153 := part74 ++ part75
private theorem part153_eq : (List.range' 9489 256).map threshold = part153 := join (s:=9489) (m:=128) (n:=128) part74_eq part75_eq
private def part154 := part76 ++ part77
private theorem part154_eq : (List.range' 9745 256).map threshold = part154 := join (s:=9745) (m:=128) (n:=128) part76_eq part77_eq
private def part155 := part78 ++ part79
private theorem part155_eq : (List.range' 10001 256).map threshold = part155 := join (s:=10001) (m:=128) (n:=128) part78_eq part79_eq
private def part156 := part80 ++ part81
private theorem part156_eq : (List.range' 10257 256).map threshold = part156 := join (s:=10257) (m:=128) (n:=128) part80_eq part81_eq
private def part157 := part82 ++ part83
private theorem part157_eq : (List.range' 10513 256).map threshold = part157 := join (s:=10513) (m:=128) (n:=128) part82_eq part83_eq
private def part158 := part84 ++ part85
private theorem part158_eq : (List.range' 10769 256).map threshold = part158 := join (s:=10769) (m:=128) (n:=128) part84_eq part85_eq
private def part159 := part86 ++ part87
private theorem part159_eq : (List.range' 11025 256).map threshold = part159 := join (s:=11025) (m:=128) (n:=128) part86_eq part87_eq
private def part160 := part88 ++ part89
private theorem part160_eq : (List.range' 11281 256).map threshold = part160 := join (s:=11281) (m:=128) (n:=128) part88_eq part89_eq
private def part161 := part90 ++ part91
private theorem part161_eq : (List.range' 11537 256).map threshold = part161 := join (s:=11537) (m:=128) (n:=128) part90_eq part91_eq
private def part162 := part92 ++ part93
private theorem part162_eq : (List.range' 11793 256).map threshold = part162 := join (s:=11793) (m:=128) (n:=128) part92_eq part93_eq
private def part163 := part94 ++ part95
private theorem part163_eq : (List.range' 12049 256).map threshold = part163 := join (s:=12049) (m:=128) (n:=128) part94_eq part95_eq
private def part164 := part96 ++ part97
private theorem part164_eq : (List.range' 12305 256).map threshold = part164 := join (s:=12305) (m:=128) (n:=128) part96_eq part97_eq
private def part165 := part98 ++ part99
private theorem part165_eq : (List.range' 12561 256).map threshold = part165 := join (s:=12561) (m:=128) (n:=128) part98_eq part99_eq
private def part166 := part100 ++ part101
private theorem part166_eq : (List.range' 12817 256).map threshold = part166 := join (s:=12817) (m:=128) (n:=128) part100_eq part101_eq
private def part167 := part102 ++ part103
private theorem part167_eq : (List.range' 13073 256).map threshold = part167 := join (s:=13073) (m:=128) (n:=128) part102_eq part103_eq
private def part168 := part104 ++ part105
private theorem part168_eq : (List.range' 13329 256).map threshold = part168 := join (s:=13329) (m:=128) (n:=128) part104_eq part105_eq
private def part169 := part106 ++ part107
private theorem part169_eq : (List.range' 13585 256).map threshold = part169 := join (s:=13585) (m:=128) (n:=128) part106_eq part107_eq
private def part170 := part108 ++ part109
private theorem part170_eq : (List.range' 13841 256).map threshold = part170 := join (s:=13841) (m:=128) (n:=128) part108_eq part109_eq
private def part171 := part110 ++ part111
private theorem part171_eq : (List.range' 14097 256).map threshold = part171 := join (s:=14097) (m:=128) (n:=128) part110_eq part111_eq
private def part172 := part112 ++ part113
private theorem part172_eq : (List.range' 14353 256).map threshold = part172 := join (s:=14353) (m:=128) (n:=128) part112_eq part113_eq
private def part173 := part114 ++ part115
private theorem part173_eq : (List.range' 14609 256).map threshold = part173 := join (s:=14609) (m:=128) (n:=128) part114_eq part115_eq
private def part174 := part116 ++ part117
private theorem part174_eq : (List.range' 17 512).map threshold = part174 := join (s:=17) (m:=256) (n:=256) part116_eq part117_eq
private def part175 := part118 ++ part119
private theorem part175_eq : (List.range' 529 512).map threshold = part175 := join (s:=529) (m:=256) (n:=256) part118_eq part119_eq
private def part176 := part120 ++ part121
private theorem part176_eq : (List.range' 1041 512).map threshold = part176 := join (s:=1041) (m:=256) (n:=256) part120_eq part121_eq
private def part177 := part122 ++ part123
private theorem part177_eq : (List.range' 1553 512).map threshold = part177 := join (s:=1553) (m:=256) (n:=256) part122_eq part123_eq
private def part178 := part124 ++ part125
private theorem part178_eq : (List.range' 2065 512).map threshold = part178 := join (s:=2065) (m:=256) (n:=256) part124_eq part125_eq
private def part179 := part126 ++ part127
private theorem part179_eq : (List.range' 2577 512).map threshold = part179 := join (s:=2577) (m:=256) (n:=256) part126_eq part127_eq
private def part180 := part128 ++ part129
private theorem part180_eq : (List.range' 3089 512).map threshold = part180 := join (s:=3089) (m:=256) (n:=256) part128_eq part129_eq
private def part181 := part130 ++ part131
private theorem part181_eq : (List.range' 3601 512).map threshold = part181 := join (s:=3601) (m:=256) (n:=256) part130_eq part131_eq
private def part182 := part132 ++ part133
private theorem part182_eq : (List.range' 4113 512).map threshold = part182 := join (s:=4113) (m:=256) (n:=256) part132_eq part133_eq
private def part183 := part134 ++ part135
private theorem part183_eq : (List.range' 4625 512).map threshold = part183 := join (s:=4625) (m:=256) (n:=256) part134_eq part135_eq
private def part184 := part136 ++ part137
private theorem part184_eq : (List.range' 5137 512).map threshold = part184 := join (s:=5137) (m:=256) (n:=256) part136_eq part137_eq
private def part185 := part138 ++ part139
private theorem part185_eq : (List.range' 5649 512).map threshold = part185 := join (s:=5649) (m:=256) (n:=256) part138_eq part139_eq
private def part186 := part140 ++ part141
private theorem part186_eq : (List.range' 6161 512).map threshold = part186 := join (s:=6161) (m:=256) (n:=256) part140_eq part141_eq
private def part187 := part142 ++ part143
private theorem part187_eq : (List.range' 6673 512).map threshold = part187 := join (s:=6673) (m:=256) (n:=256) part142_eq part143_eq
private def part188 := part144 ++ part145
private theorem part188_eq : (List.range' 7185 512).map threshold = part188 := join (s:=7185) (m:=256) (n:=256) part144_eq part145_eq
private def part189 := part146 ++ part147
private theorem part189_eq : (List.range' 7697 512).map threshold = part189 := join (s:=7697) (m:=256) (n:=256) part146_eq part147_eq
private def part190 := part148 ++ part149
private theorem part190_eq : (List.range' 8209 512).map threshold = part190 := join (s:=8209) (m:=256) (n:=256) part148_eq part149_eq
private def part191 := part150 ++ part151
private theorem part191_eq : (List.range' 8721 512).map threshold = part191 := join (s:=8721) (m:=256) (n:=256) part150_eq part151_eq
private def part192 := part152 ++ part153
private theorem part192_eq : (List.range' 9233 512).map threshold = part192 := join (s:=9233) (m:=256) (n:=256) part152_eq part153_eq
private def part193 := part154 ++ part155
private theorem part193_eq : (List.range' 9745 512).map threshold = part193 := join (s:=9745) (m:=256) (n:=256) part154_eq part155_eq
private def part194 := part156 ++ part157
private theorem part194_eq : (List.range' 10257 512).map threshold = part194 := join (s:=10257) (m:=256) (n:=256) part156_eq part157_eq
private def part195 := part158 ++ part159
private theorem part195_eq : (List.range' 10769 512).map threshold = part195 := join (s:=10769) (m:=256) (n:=256) part158_eq part159_eq
private def part196 := part160 ++ part161
private theorem part196_eq : (List.range' 11281 512).map threshold = part196 := join (s:=11281) (m:=256) (n:=256) part160_eq part161_eq
private def part197 := part162 ++ part163
private theorem part197_eq : (List.range' 11793 512).map threshold = part197 := join (s:=11793) (m:=256) (n:=256) part162_eq part163_eq
private def part198 := part164 ++ part165
private theorem part198_eq : (List.range' 12305 512).map threshold = part198 := join (s:=12305) (m:=256) (n:=256) part164_eq part165_eq
private def part199 := part166 ++ part167
private theorem part199_eq : (List.range' 12817 512).map threshold = part199 := join (s:=12817) (m:=256) (n:=256) part166_eq part167_eq
private def part200 := part168 ++ part169
private theorem part200_eq : (List.range' 13329 512).map threshold = part200 := join (s:=13329) (m:=256) (n:=256) part168_eq part169_eq
private def part201 := part170 ++ part171
private theorem part201_eq : (List.range' 13841 512).map threshold = part201 := join (s:=13841) (m:=256) (n:=256) part170_eq part171_eq
private def part202 := part172 ++ part173
private theorem part202_eq : (List.range' 14353 512).map threshold = part202 := join (s:=14353) (m:=256) (n:=256) part172_eq part173_eq
private def part203 := part174 ++ part175
private theorem part203_eq : (List.range' 17 1024).map threshold = part203 := join (s:=17) (m:=512) (n:=512) part174_eq part175_eq
private def part204 := part176 ++ part177
private theorem part204_eq : (List.range' 1041 1024).map threshold = part204 := join (s:=1041) (m:=512) (n:=512) part176_eq part177_eq
private def part205 := part178 ++ part179
private theorem part205_eq : (List.range' 2065 1024).map threshold = part205 := join (s:=2065) (m:=512) (n:=512) part178_eq part179_eq
private def part206 := part180 ++ part181
private theorem part206_eq : (List.range' 3089 1024).map threshold = part206 := join (s:=3089) (m:=512) (n:=512) part180_eq part181_eq
private def part207 := part182 ++ part183
private theorem part207_eq : (List.range' 4113 1024).map threshold = part207 := join (s:=4113) (m:=512) (n:=512) part182_eq part183_eq
private def part208 := part184 ++ part185
private theorem part208_eq : (List.range' 5137 1024).map threshold = part208 := join (s:=5137) (m:=512) (n:=512) part184_eq part185_eq
private def part209 := part186 ++ part187
private theorem part209_eq : (List.range' 6161 1024).map threshold = part209 := join (s:=6161) (m:=512) (n:=512) part186_eq part187_eq
private def part210 := part188 ++ part189
private theorem part210_eq : (List.range' 7185 1024).map threshold = part210 := join (s:=7185) (m:=512) (n:=512) part188_eq part189_eq
private def part211 := part190 ++ part191
private theorem part211_eq : (List.range' 8209 1024).map threshold = part211 := join (s:=8209) (m:=512) (n:=512) part190_eq part191_eq
private def part212 := part192 ++ part193
private theorem part212_eq : (List.range' 9233 1024).map threshold = part212 := join (s:=9233) (m:=512) (n:=512) part192_eq part193_eq
private def part213 := part194 ++ part195
private theorem part213_eq : (List.range' 10257 1024).map threshold = part213 := join (s:=10257) (m:=512) (n:=512) part194_eq part195_eq
private def part214 := part196 ++ part197
private theorem part214_eq : (List.range' 11281 1024).map threshold = part214 := join (s:=11281) (m:=512) (n:=512) part196_eq part197_eq
private def part215 := part198 ++ part199
private theorem part215_eq : (List.range' 12305 1024).map threshold = part215 := join (s:=12305) (m:=512) (n:=512) part198_eq part199_eq
private def part216 := part200 ++ part201
private theorem part216_eq : (List.range' 13329 1024).map threshold = part216 := join (s:=13329) (m:=512) (n:=512) part200_eq part201_eq
private def part217 := part202 ++ words14865
private theorem part217_eq : (List.range' 14353 557).map threshold = part217 := join (s:=14353) (m:=512) (n:=45) part202_eq words14865_eq
private def part218 := part203 ++ part204
private theorem part218_eq : (List.range' 17 2048).map threshold = part218 := join (s:=17) (m:=1024) (n:=1024) part203_eq part204_eq
private def part219 := part205 ++ part206
private theorem part219_eq : (List.range' 2065 2048).map threshold = part219 := join (s:=2065) (m:=1024) (n:=1024) part205_eq part206_eq
private def part220 := part207 ++ part208
private theorem part220_eq : (List.range' 4113 2048).map threshold = part220 := join (s:=4113) (m:=1024) (n:=1024) part207_eq part208_eq
private def part221 := part209 ++ part210
private theorem part221_eq : (List.range' 6161 2048).map threshold = part221 := join (s:=6161) (m:=1024) (n:=1024) part209_eq part210_eq
private def part222 := part211 ++ part212
private theorem part222_eq : (List.range' 8209 2048).map threshold = part222 := join (s:=8209) (m:=1024) (n:=1024) part211_eq part212_eq
private def part223 := part213 ++ part214
private theorem part223_eq : (List.range' 10257 2048).map threshold = part223 := join (s:=10257) (m:=1024) (n:=1024) part213_eq part214_eq
private def part224 := part215 ++ part216
private theorem part224_eq : (List.range' 12305 2048).map threshold = part224 := join (s:=12305) (m:=1024) (n:=1024) part215_eq part216_eq
private def part225 := part218 ++ part219
private theorem part225_eq : (List.range' 17 4096).map threshold = part225 := join (s:=17) (m:=2048) (n:=2048) part218_eq part219_eq
private def part226 := part220 ++ part221
private theorem part226_eq : (List.range' 4113 4096).map threshold = part226 := join (s:=4113) (m:=2048) (n:=2048) part220_eq part221_eq
private def part227 := part222 ++ part223
private theorem part227_eq : (List.range' 8209 4096).map threshold = part227 := join (s:=8209) (m:=2048) (n:=2048) part222_eq part223_eq
private def part228 := part224 ++ part217
private theorem part228_eq : (List.range' 12305 2605).map threshold = part228 := join (s:=12305) (m:=2048) (n:=557) part224_eq part217_eq
private def part229 := part225 ++ part226
private theorem part229_eq : (List.range' 17 8192).map threshold = part229 := join (s:=17) (m:=4096) (n:=4096) part225_eq part226_eq
private def part230 := part227 ++ part228
private theorem part230_eq : (List.range' 8209 6701).map threshold = part230 := join (s:=8209) (m:=4096) (n:=2605) part227_eq part228_eq
private def part231 := part229 ++ part230
private theorem part231_eq : (List.range' 17 14893).map threshold = part231 := join (s:=17) (m:=8192) (n:=6701) part229_eq part230_eq
def actualLinkedMem (i : Nat) : Nat := (part231[i-17]?).getD 0
theorem table_ok : X86.tableOK actualLinkedMem := by
intro i lo hi
unfold actualLinkedMem
rw [← part231_eq, List.getElem?_map, List.getElem?_range' (show i-17 < 14893 by omega)]
have eqn : 17+1*(i-17)=i := by omega
rw [eqn]
rfl
#print axioms table_ok
end P14LinkedDebit
~~~
#### `asmproof/linked-release/LinkedDebitGame.lean`
~~~lean
import LinkedDebit
import asmproof.GameMachinePrice
namespace P14LinkedDebit
open P14Entry Problem14
theorem scalar_game {n f g hint : ℕ} (hn : 32768≤n) (hu : n<2^64)
(fl : f<2^64) (fh : g<2^64) (s : M.State) (sl sh : R.CPU) (sd : D.State) :
EntryReturns n f g hint 45 4 0 0 actualLinkedMem s sl sh sd (fun z =>
(z.outLo:ℝ)/10^6 ≤ GameComparison.price n ∧ GameComparison.price n ≤ (z.outHi:ℝ)/10^6) :=
machine_encloses_game hn hu 45 4 0 0 fl fh table_ok s sl sh sd
#print axioms scalar_game
end P14LinkedDebit
~~~
#### `cent/formal/CentCutoff.lean`
~~~lean
import asmproof.GameCentral
/-! Exact additive regret debit for the large-deck threshold policy.
If a common envelope bounds both payoffs, and the policy's lower envelope
at a balanced root is the upper envelope minus (P/Q)/5, one cent suffices
exactly when 20 P < Q. GameCentral defines P/Q as a normalized product.
All bounds in this module use unbounded natural numbers. -/
namespace Problem14.CentCutoff
open GameCentral
/-- Clearing denominators in (N+1)^(1/5) > 13.7. For an even N the
first N satisfying this sufficient inequality is 482618. -/
theorem fifth_root_cutoff (n : Nat) :
137^5 < (2*n+1)*10^5 ↔ 241309 ≤ n := by
change 48261724457 < (2*n+1)*100000 ↔ _
omega
/-- For any common baseline h, if v≤h and h-p≤d, regret v-p≤d.
The integer scale is arbitrary; using signed totals also covers negative
values, and multiplying every quantity by a positive common denominator
proves the identical rational statement. -/
theorem cancellation (v p h d : Int) (hi : v ≤ h) (lo : h-p ≤ d) : v-p ≤ d := by omega
def scale : Nat := 10^18
abbrev Encloses (n l u : Nat) :=
l * product 5 n ≤ scale * product 3 n ∧ scale * product 3 n ≤ u * product 5 n
private theorem positive (n : Nat) : 0 < product 5 n := by
induction n with
| zero => decide
| succ n ih => exact Nat.mul_pos (by omega) ih
/-- Outward integer rounding. The upper endpoint can overshoot by a
single unit when the division is exact, which keeps the step simple. -/
def step (n : Nat) (p : Nat × Nat) : Nat × Nat :=
((p.1*(10*n+3))/(10*n+5), (p.2*(10*n+3))/(10*n+5)+1)
theorem step_sound (n l u : Nat) (p : Encloses n l u) :
Encloses (n+1) (step n (l,u)).1 (step n (l,u)).2 := by
let a := 10*n+3
let b := 10*n+5
have hb : 0 < b := by dsimp [b]; omega
have hl := Nat.div_mul_le_self (l*a) b
have hu := Nat.le_of_lt ((Nat.div_lt_iff_lt_mul hb).mp (Nat.lt_succ_self (u*a/b)))
change (l*a/b)*(b*product 5 n) ≤ scale*(a*product 3 n) ∧
scale*(a*product 3 n) ≤ (u*a/b+1)*(b*product 5 n)
constructor
· calc
_ = (l*a/b*b)*product 5 n := by ac_rfl
_ ≤ l*a*product 5 n := Nat.mul_le_mul_right _ hl
_ = (l*product 5 n)*a := by ac_rfl
_ ≤ (scale*product 3 n)*a := Nat.mul_le_mul_right _ p.1
_ = _ := by ac_rfl
· calc
_ = (scale*product 3 n)*a := by ac_rfl
_ ≤ (u*product 5 n)*a := Nat.mul_le_mul_right _ p.2
_ = (u*a)*product 5 n := by ac_rfl
_ ≤ ((u*a/b+1)*b)*product 5 n := Nat.mul_le_mul_right _ hu
_ = _ := by ac_rfl
def run : Nat → Nat → Nat × Nat → Nat × Nat
| 0, _, p => p
| k+1, n, p => run k (n+1) (step n p)
theorem run_sound (k n : Nat) (p : Nat × Nat) (h : Encloses n p.1 p.2) :
Encloses (n+k) (run k n p).1 (run k n p).2 := by
induction k generalizing n p with
| zero => exact h
| succ k ih =>
have h' := ih (n+1) (step n p) (step_sound n p.1 p.2 h)
simpa only [run, Nat.succ_add, Nat.add_succ] using h'
theorem one_cross (n l u : Nat) (h : Encloses n l u) (cross : 20*u < scale) :
20 * product 3 n < product 5 n := by
apply Nat.lt_of_mul_lt_mul_left (a:=scale)
calc
_ = 20 * (scale * product 3 n) := by ac_rfl
_ ≤ 20 * (u * product 5 n) := Nat.mul_le_mul_left _ h.2
_ = (20*u)*product 5 n := by ac_rfl
_ < _ := Nat.mul_lt_mul_of_pos_right cross (positive n)
theorem no_cross (n l u : Nat) (h : Encloses n l u) (hc : scale ≤ 20*l) :
product 5 n ≤ 20 * product 3 n := by
apply Nat.le_of_mul_le_mul_right (c:=scale) _ (by decide)
calc
_ = scale * product 5 n := by ac_rfl
_ ≤ (20*l)*product 5 n := Nat.mul_le_mul_right _ hc
_ = 20*(l*product 5 n) := by ac_rfl
_ ≤ 20*(scale*product 3 n) := Nat.mul_le_mul_left _ h.1
_ = _ := by ac_rfl
private theorem persist (n k : Nat) (h : 20*product 3 n < product 5 n) :
20*product 3 (n+k) < product 5 (n+k) := by
induction k with
| zero => exact h
| succ k ih =>
rw [Nat.add_succ, product.eq_2, product.eq_2]
calc
_ = (10*(n+k)+3)*(20*product 3 (n+k)) := by ac_rfl
_ < (10*(n+k)+3)*product 5 (n+k) := Nat.mul_lt_mul_of_pos_left ih (by omega)
_ ≤ _ := Nat.mul_le_mul_right _ (by omega)
private theorem next_cross (n : Nat) (p : Nat × Nat) (h : Encloses n p.1 p.2)
(near : 20*(step n p).2 < scale) : 20*product 3 (n+1) < product 5 (n+1) := by
cases p with
| mk l u => exact one_cross (n+1) _ _ (step_sound n l u h) near
attribute [irreducible] run
private def start (n : Nat) := run n 0 (scale,scale)
private theorem start_valid (n : Nat) : Encloses n (start n).1 (start n).2 := by
have h := run_sound n 0 (scale,scale) (show Encloses 0 scale scale from ⟨by decide,by decide⟩)
simpa only [Nat.zero_add,start] using h
private def Checked (m : Nat) : Prop :=
scale ≤ 20*(start m).1 ∧ 20*(step m (start m)).2 < scale
private instance (m : Nat) : Decidable (Checked m) := by unfold Checked; infer_instance
private theorem finite_check : Checked 233630 := by native_decide
theorem barrier (m n : Nat) (no : product 5 m ≤ 20*product 3 m)
(yes : 20*product 3 (m+1) < product 5 (m+1)) :
20*product 3 n < product 5 n ↔ m+1≤n := by
constructor
· intro h
by_cases enough : m+1 ≤ n
· exact enough
· exfalso
have eq : n+(m-n)=m := by omega
have c := persist n (m-n) h
rw [eq] at c
exact (Nat.not_lt_of_ge no) c
· intro hn
have eq : m+1+(n-(m+1))=n := by omega
have h := persist (m+1) (n-(m+1)) yes
rw [eq] at h
exact h
private theorem certified (m n : Nat) (c : Checked m) :
20*product 3 n < product 5 n ↔ m+1 ≤ n :=
barrier m n (no_cross m _ _ (start_valid m) c.1)
(next_cross m (start m) (start_valid m) c.2)
theorem exact_debit_threshold (n : Nat) :
20*product 3 n < product 5 n ↔ 233631 ≤ n :=
certified 233630 n finite_check
#print axioms exact_debit_threshold
end Problem14.CentCutoff
~~~
#### `cent/formal/CentPolicy.lean`
~~~lean
import asmproof.GameLower
/-! Constructive sharpening of GameLower.lower_from_cutoff. The payoff in
the conclusion belongs to a specified online rule. Its decisions before
the terminal layer are the stated moving threshold. Below that layer the
player uses the exact finite-deck optimizer. -/
namespace Problem14.CentPolicy
open GameLower Excursions
/-- The wall selects the first stopping black-card column on every time
layer strictly above T. At T or later in play, use the exact finite policy. -/
def rule (R T : Nat) (w : Frontier T) (s : State) : Bool :=
if s.1+s.2 ≤ T then greedy R s else decide (w.column (s.1+s.2) ≤ s.2)
def policyMass (R : Nat) (q : Rule) (r b : Nat) : Int :=
(score R q (deck r b) : Int) - R*(weight (deck r b) : Int)
private theorem greedyBranch (R : Nat) (q : Rule) (s : State) (l r : Tree)
(hl : score R q l = bellman R l) (hr : score R q r = bellman R r)
(hq : q s = decide (bellman R (.branch s l r) = reward R s*weight (.branch s l r))) :
score R q (.branch s l r) = bellman R (.branch s l r) := by
rw [score_branch, hq, hl, hr]
simp only [bellman, weight, paths, List.length_map, List.length_append]
split <;> simp_all <;> omega
theorem exact_endgame (R T : Nat) (w : Frontier T) (r b : Nat) (ht : r+b ≤ T) :
score R (rule R T w) (deck r b) = bellman R (deck r b) := by
induction r, b using deck.induct with
| case1 => simp [score,deck,paths,firstPay,bellman]
| case2 r ih =>
rw [deck]
apply greedyBranch
· exact ih (by omega)
· rfl
· simp only [rule,ht,↓reduceIte,greedy,deck]
| case3 b ih =>
rw [deck]
apply greedyBranch
· rfl
· exact ih (by omega)
· simp only [rule,ht,↓reduceIte,greedy,deck]
| case4 r b ihl ihr =>
rw [deck]
apply greedyBranch
· exact ihl (by omega)
· exact ihr (by omega)
· simp only [rule,ht,↓reduceIte,greedy,deck]
private theorem pay_stop (R : Nat) (q : Rule) (r b : Nat) (hr : r ≤ R)
(hit : q (r,b) = true) : policyMass R q r b = stopMass r b := by
have sc : ((reward R (r,b):Nat):Int) = R+((b:Int)-r) := by
simp only [reward,Int.natCast_add,Int.ofNat_sub hr]; omega
have one (s : State) (l h : Tree) : weight (.branch s l h) = weight l+weight h := by
simp [weight,paths]
cases r <;> cases b
· simp [policyMass,stopMass,deck,score,paths,firstPay,weight]
all_goals simp only [policyMass,stopMass,deck.eq_2,deck.eq_3,deck.eq_4,score_branch,
hit,↓reduceIte,one,Int.natCast_mul,sc,Int.add_mul]; omega
private theorem draw_r (R : Nat) (q : Rule) (r : Nat) (h : q (r+1,0)=false) :
policyMass R q (r+1) 0 = policyMass R q r 0 := by
have wt (s : State) (l : Tree) : weight (.branch s l .empty) = weight l := by simp [weight,paths]
have z : score R q .empty = 0 := rfl
simp only [policyMass,deck.eq_2,score_branch,h,Bool.false_eq_true,↓reduceIte,wt,z,Nat.add_zero]
private theorem draw_rb (R : Nat) (q : Rule) (r b : Nat) (h : q (r+1,b+1)=false) :
policyMass R q (r+1) (b+1) = policyMass R q r (b+1) + policyMass R q (r+1) b := by
have w (s : State) (l h : Tree) : weight (.branch s l h) = weight l+weight h := by simp [weight,paths]
simp only [policyMass,deck.eq_4,score_branch,h,Bool.false_eq_true,↓reduceIte,w,Int.natCast_add,
Int.mul_add]
omega
variable {A : Type} [LE A] [Add A]
/-- A threshold above T can be spliced onto any terminal online strategy
with a certified lower value on the entered states. For a rounded or
approximate terminal solver it is this strategy's payoff that must dominate
the claimed initial numbers. -/
theorem policy_lower_from_terminal (core : OrderedEmbedding A) (T R : Nat)
(wall : Frontier T) (q : Rule) (initial : Nat → A)
(decisions : ∀ r b, T intro r b ht hr hb; exact cut r b ht hr hb
| succ k ih =>
intro r b ht hr hb
have tim : ¬ r+b≤T := by omega
by_cases heq : b = wall.column (T+(k+1))
· have h : q (r,b)=true := by rw [decisions r b (by omega), ht, heq]; simp
rw [pay_stop R _ r b hr h]
exact contact (k+1) r b ht hr heq
have hq : q (r,b)=false := by
rw [decisions r b (by omega), ht, decide_eq_false_iff_not]; omega
have adv := wall.advance (T+k) (by omega)
have phys := wall.physical (T+(k+1)) (by omega)
rw [show T+k+1=T+(k+1) by omega] at adv
have prev : b ≤ wall.column (T+k) := by omega
cases r with
| zero => omega
| succ r =>
cases b with
| zero =>
rw [draw_r _ _ _ hq]
exact ih r 0 (by omega) (by omega) prev
| succ b =>
rw [draw_rb _ _ _ _ hq, core.add]
exact core.addMono (ih r (b+1) (by omega) (by omega) prev)
(ih (r+1) b (by omega) hr (by omega))
/-- For the exact endgame, the original optimal cutoff and contact
premises suffice verbatim. The resulting bound prices the specified policy. -/
theorem policy_lower (core : OrderedEmbedding A) (T R : Nat) (wall : Frontier T)
(initial : Nat → A)
(cut : ∀ r b, r+b=T → r≤R → b
#### `cent/formal/CentPolicyCap.lean`
~~~lean
import CentCutoff
/-! Arithmetic for the policy-specific fractional multiplier.
P/Q is the exact normalized central product. Assumptions on the C cutoff
table and the analytic comparison are needed to interpret the resulting
lambda times P/Q as an upper bound on the player's loss. -/
namespace Problem14.CentPolicyCap
open GameCentral CentCutoff
abbrev lambdaNum : Nat := 197356261
abbrev lambdaDen : Nat := 1000000000
abbrev capNum : Nat := 9804191707
abbrev capDen : Nat := 1000000000000
private def row (n : Nat) := run n 0 (scale,scale)
private theorem valid (n : Nat) : Encloses n (row n).1 (row n).2 := by
have h := run_sound n 0 (scale,scale) (show Encloses 0 scale scale from ⟨by decide,by decide⟩)
simpa only [row,Nat.zero_add] using h
private theorem positive (n : Nat) : 0 decide
| succ n ih => exact Nat.mul_pos (by omega) ih
private theorem low (a b n : Nat) (h : b*scale ≤ a*(row n).1) :
b*product 5 n ≤ a*product 3 n := by
apply Nat.le_of_mul_le_mul_right (c:=scale) _ (by decide)
calc
_ = (b*scale)*product 5 n := by ac_rfl
_ ≤ (a*(row n).1)*product 5 n := Nat.mul_le_mul_right _ h
_ = a*((row n).1*product 5 n) := by ac_rfl
_ ≤ a*(scale*product 3 n) := Nat.mul_le_mul_left _ (valid n).1
_ = _ := by ac_rfl
private theorem high (a b n : Nat) (h : a*(row n).2 < b*scale) :
a*product 3 n < b*product 5 n := by
apply Nat.lt_of_mul_lt_mul_right (a:=scale)
calc
_ = a*(scale*product 3 n) := by ac_rfl
_ ≤ a*((row n).2*product 5 n) := Nat.mul_le_mul_left _ (valid n).2
_ = (a*(row n).2)*product 5 n := by ac_rfl
_ < (b*scale)*product 5 n := Nat.mul_lt_mul_of_pos_right h (positive n)
_ = _ := by ac_rfl
private theorem persists (a b n k : Nat) (h : a*product 3 n < b*product 5 n) :
a*product 3 (n+k) exact h
| succ k ih =>
rw [Nat.add_succ,product.eq_2, product.eq_2]
calc
_ = (10*(n+k)+3)*(a*product 3 (n+k)) := by ac_rfl
_ < (10*(n+k)+3)*(b*product 5 (n+k)) := Nat.mul_lt_mul_of_pos_left ih (by omega)
_ ≤ (10*(n+k)+5)*(b*product 5 (n+k)) := Nat.mul_le_mul_right _ (by omega)
_ = _ := by ac_rfl
private theorem after (a b m n : Nat) (ok : a*(row m).2 < b*scale) (hn : m≤n) :
a*product 3 n < b*product 5 n := by
have h := persists a b m (n-m) (high a b m ok)
rw [show m+(n-m)=n by omega] at h
exact h
private theorem crossing (a b m n : Nat)
(lo : b*scale ≤ a*(row m).1) (hi : a*(row (m+1)).2 < b*scale) :
a*product 3 n < b*product 5 n ↔ m+1≤n := by
constructor
· intro h
by_cases ok : m+1≤n
· exact ok
· exfalso
have bad := persists a b n (m-n) h
rw [show n+(m-n)=m by omega] at bad
exact (Nat.not_lt_of_ge (low a b m lo)) bad
· exact after a b (m+1) n hi
private def Check (m t : Nat) : Prop :=
lambdaDen*scale ≤ (100*lambdaNum)*(row m).1 ∧
(100*lambdaNum)*(row (m+1)).2 < lambdaDen*scale ∧
(capDen*lambdaNum)*(row t).2 < (capNum*lambdaDen)*scale
private instance (m t : Nat) : Decidable (Check m t) := by unfold Check; infer_instance
/-- One compiled decision, covering all finite fixed-point comparisons. -/
private theorem verified : Check 218592 241310 := by native_decide
/-- The exact product debit with multiplier 197356261/10^9, multiplied
by 100, is strictly below one iff n is at least 218593 pairs. -/
theorem first_subcent (n : Nat) :
(100*lambdaNum)*product 3 n < lambdaDen*product 5 n ↔ 218593≤n :=
crossing _ _ 218592 n verified.1 verified.2.1
/-- The actual product debit is strictly below 0.009804191707 dollars
at every n≥241310 pairs. All denominator factors are positive. -/
theorem large_cap (n : Nat) (hn : 241310≤n) :
(capDen*lambdaNum)*product 3 n < (capNum*lambdaDen)*product 5 n :=
after _ _ 241310 n verified.2.2 hn
/-- Finite-sweep cap 2075264/2^32 is also strictly below that amount. -/
theorem small_cap : 2075264*capDen < capNum*2^32 := by decide +kernel
#print axioms first_subcent
#print axioms large_cap
#print axioms small_cap
end Problem14.CentPolicyCap
~~~
#### `cent/formal/CentQuick.lean`
~~~lean
import CentCutoff
/-! A kernel-only, 1,000-factor certificate for the debit crossover. -/
namespace Problem14.CentQuick
open GameCentral CentCutoff
/-- Evaluate a polynomial in ascending powers. -/
private def ev : List Nat → Nat → Nat
| [], _ => 0
| a::p, x => a+x*ev p x
/-- Multiplication by c+d*x, with constant carry b. -/
private def lin (c d : Nat) : Nat → List Nat → List Nat
| b, [] => [b]
| b, a::p => (b+c*a)::lin c d (d*a) p
private theorem evaluate_lin (c d : Nat) (p : List Nat) (b x : Nat) :
ev (lin c d b p) x = b+(c+d*x)*ev p x := by
induction p generalizing b with
| nil => simp [ev,lin]
| cons a p ih =>
simp only [ev,lin,ih,Nat.add_mul,Nat.mul_add]
ac_rfl
private def affinePow (c d : Nat) : Nat → List Nat
| 0 => [1]
| k+1 => lin c d 0 (affinePow c d k)
private theorem evaluate_pow (c d k x : Nat) : ev (affinePow c d k) x = (c+d*x)^k := by
induction k with
| zero => simp [affinePow,ev]
| succ k ih => simp [affinePow, evaluate_lin, ih, Nat.pow_succ,Nat.mul_comm]
/-- Effective componentwise order, for equally long lists. -/
private def chk : List Nat → List Nat → Bool
| [], [] => true
| a::p, b::q => decide (a≤b) && chk p q
| _, _ => false
private theorem eval_mono (p q : List Nat) (x : Nat) (h : chk p q = true) :
ev p x ≤ ev q x := by
induction p generalizing q with
| nil => cases q <;> simp [ev]
| cons a p ih =>
cases q with
| nil => simp [chk] at h
| cons b q =>
obtain ⟨le,rest⟩ := Bool.and_eq_true_iff.mp h
exact Nat.add_le_add (of_decide_eq_true le) (Nat.mul_le_mul_left x (ih q rest))
private def form (s k a : Nat) := lin s k 0 (affinePow a 10 5)
private theorem interpret (s k a x : Nat) :
ev (form s k a) x = (s+k*x)*(a+10*x)^5 := by simp [form,evaluate_lin,evaluate_pow]
private def L (j : Nat) := 9999+10*j
private def U (j : Nat) := 9999001+10000*j
private theorem lowStep (j : Nat) : L j*(10005+10*j)^5 ≤ L (j+1)*(10003+10*j)^5 := by
have h := eval_mono (form 9999 10 10005) (form 10009 10 10003) j (by decide)
rw [interpret, interpret] at h
have e : L (j+1) = 10009+10*j := by unfold L; omega
rw [e]; exact h
private theorem hiStep (j : Nat) : U (j+1)*(10003+10*j)^5 ≤ U j*(10005+10*j)^5 := by
have h := eval_mono (form 10009001 10000 10003) (form 9999001 10000 10005) j (by decide)
rw [interpret, interpret] at h
have e : U (j+1) = 10009001+10000*j := by unfold U; omega
rw [e]; exact h
private def P (j : Nat) := (product 3 (1000+j))^5
private def Q (j : Nat) := (product 5 (1000+j))^5
private theorem factor (a j : Nat) :
(product a (1000+(j+1)))^5 = (10000+a+10*j)^5 * (product a (1000+j))^5 := by
rw [Nat.add_succ, product.eq_2, Nat.mul_pow]
have h : 10*(1000+j)+a=10000+a+10*j := by omega
rw [h]
private theorem positive (j : Nat) : 0 < product 5 j := by
induction j with
| zero => decide
| succ j ih => exact Nat.mul_pos (by omega) ih
private theorem qpos (j : Nat) : 0 exact ⟨Nat.le_refl _,Nat.le_refl _⟩
| succ j ih =>
constructor
· apply trans _ _ _ (Q j) _ _ (qpos _) ih.1
have p : P (j+1)=(10003+10*j)^5*P j := factor 3 j
have q : Q (j+1)=(10005+10*j)^5*Q j := factor 5 j
rw [p,q]
calc
_ = (L j*(10005+10*j)^5)*(P j*Q j) := by ac_rfl
_ ≤ (L (j+1)*(10003+10*j)^5)*(P j*Q j) := Nat.mul_le_mul_right _ (lowStep j)
_ = _ := by ac_rfl
· apply trans _ _ _ (Q j) _ _ (qpos _) _ ih.2
have p : P (j+1)=(10003+10*j)^5*P j := factor 3 j
have q : Q (j+1)=(10005+10*j)^5*Q j := factor 5 j
rw [p,q]
calc
_ = (U (j+1)*(10003+10*j)^5)*(P j*Q j) := by ac_rfl
_ ≤ (U j*(10005+10*j)^5)*(P j*Q j) := Nat.mul_le_mul_right _ (hiStep j)
_ = _ := by ac_rfl
private def Below (j : Nat) : Prop := L j*Q 0 ≤ (L 0*P 0)*20^5
private def Above (j : Nat) : Prop := (U 0*P 0)*20^5 < U j*Q 0
private instance (j : Nat) : Decidable (Below j) := by unfold Below; infer_instance
private instance (j : Nat) : Decidable (Above j) := by unfold Above; infer_instance
set_option maxRecDepth 16000 in
set_option maxHeartbeats 5000000 in
private theorem small_check : Below 232630 ∧ Above 232631 := by decide +kernel
private theorem before (j : Nat) (h : Below j) :
product 5 (1000+j) ≤ 20*product 3 (1000+j) := by
have chain := trans (L j) (20^5) _ (Q 0) _ (Q j) (qpos 0) h (inequalities j).1
rw [Nat.mul_assoc] at chain
have lpos : 0
#### `cent/formal/CentRegret.lean`
~~~lean
import Problem14
/-! Proofs for an additive regret budget, using exact total payoff on the
equiprobable leaves of Problem 14's finite deck tree. A scale of 100 counts
cents. Upper bounds, payments and replication counts below are integers.
Build Problem14.olean first and include its directory in LEAN_PATH. -/
namespace Problem14.CentRegret
/-- A scaled upper bound for every exercise or continuation decision.
The arguments may depend on the entire subtree. -/
def Upper (R k : Nat) (u : Tree → Nat) : Tree → Prop
| .empty => True
| .leaf => k * R ≤ u .leaf
| .branch s l r =>
k * (reward R s * (weight l + weight r)) ≤ u (.branch s l r) ∧
u l + u r ≤ u (.branch s l r) ∧ Upper R k u l ∧ Upper R k u r
theorem upper_bounds_optimum (R k : Nat) (u : Tree → Nat) (t : Tree)
(hu : Upper R k u t) : k * bellman R t ≤ u t := by
induction t with
| empty => simp [bellman]
| leaf => exact hu
| branch s l r hl hr =>
rcases hu with ⟨hs, hc, hul, hur⟩
simp only [bellman]
rcases Nat.le_total (reward R s * (weight l + weight r))
(bellman R l + bellman R r) with h | h
· rw [Nat.max_eq_right h, Nat.mul_add]
exact Nat.le_trans (Nat.add_le_add (hl hul) (hr hur)) hc
· simpa only [Nat.max_eq_left h] using hs
/-- The gap actually charged to the chosen policy: a stop pays once;
continuation pays the defect in the envelope and recurses on each child. -/
def charge (R k : Nat) (q : Rule) (u : Tree → Nat) : Tree → Nat
| .empty => u .empty
| .leaf => u .leaf - k * R
| .branch s l r =>
if q s then u (.branch s l r) - k * (reward R s * (weight l + weight r))
else u (.branch s l r) - (u l + u r) +
charge R k q u l + charge R k q u r
theorem charge_identity (R k : Nat) (q : Rule) (u : Tree → Nat) (t : Tree)
(hu : Upper R k u t) : k * score R q t + charge R k q u t = u t := by
induction t with
| empty => simp [score, paths, charge]
| leaf =>
change k * R ≤ u .leaf at hu
simp [score, paths, firstPay, charge]
omega
| branch s l r hl hr =>
rcases hu with ⟨hs, hc, hul, hur⟩
rw [score_branch]
cases h : q s <;> simp only [charge, h, Bool.false_eq_true, ↓reduceIte]
· rw [Nat.mul_add]
have a := hl hul
have b := hr hur
omega
· omega
/-- Strict expected loss below one cent. The conditioning denominator is
the number of equiprobable completed words. -/
theorem under_one_cent (R : Nat) (q : Rule) (u : Tree → Nat) (t : Tree)
(hu : Upper R 100 u t) (hcharge : charge R 100 q u t < weight t) :
100 * (bellman R t - score R q t) < weight t := by
have ha := charge_identity R 100 q u t hu
have hb := upper_bounds_optimum R 100 u t hu
have hs := score_le_bellman R q t
omega
/-- A check for charging at most e/k once per completed word. A harmonic
envelope incurs no defect on continuation. Stopped subtrees are never visited. -/
def Frontier (R k e : Nat) (q : Rule) (u : Tree → Nat) : Tree → Prop
| .empty => u .empty = 0
| .leaf => u .leaf ≤ k * R + e
| .branch s l r =>
if q s then u (.branch s l r) ≤
k * (reward R s * (weight l + weight r)) + e * (weight l + weight r)
else u (.branch s l r) ≤ u l + u r ∧
Frontier R k e q u l ∧ Frontier R k e q u r
theorem frontier_charge (R k e : Nat) (q : Rule) (u : Tree → Nat) (t : Tree)
(hf : Frontier R k e q u t) : charge R k q u t ≤ e * weight t := by
induction t with
| empty =>
change u .empty = 0 at hf
simp [weight, paths, charge, hf]
| leaf =>
change u .leaf ≤ k * R + e at hf
simp [charge, weight, paths]
omega
| branch s l r hl hr =>
have hw : weight (.branch s l r) = weight l + weight r := by simp [weight, paths]
cases h : q s
· simp only [Frontier, h, Bool.false_eq_true, ↓reduceIte] at hf
rcases hf with ⟨hh, fl, fr⟩
simp only [charge, h, Bool.false_eq_true, ↓reduceIte, Nat.sub_eq_zero_of_le hh,
Nat.zero_add, hw, Nat.mul_add]
exact Nat.add_le_add (hl fl) (hr fr)
· simp only [Frontier, h, ↓reduceIte] at hf
simp only [charge, h, ↓reduceIte, hw]
omega
/-- No elapsed-time factor: paying e/k only at the first exercise or
terminal frontier costs at most e/k at the root, on decks of all sizes. -/
theorem frontier_regret (R k e : Nat) (q : Rule) (u : Tree → Nat) (t : Tree)
(hu : Upper R k u t) (hf : Frontier R k e q u t) :
k * (bellman R t - score R q t) ≤ e * weight t := by
have a := charge_identity R k q u t hu
have b := upper_bounds_optimum R k u t hu
have c := frontier_charge R k e q u t hf
have d := score_le_bellman R q t
rw [Nat.mul_sub_left_distrib]
omega
end Problem14.CentRegret
~~~
#### `cent/native/Play64.lean`
~~~lean
import Std
/-! Natural-number specification and no-wrap bounds for play64.c.
Input x is the positive part of the balance. The large-branch comparison
is for the rational squared slope beta / 2^64. -/
namespace CentPlay64
def beta : Nat := 13013657395120439157
abbrev word : Nat := 2^64
theorem coefficient_floor :
(83992367569237^2 * word) / (10^14)^2 = beta := by decide
theorem multiply_add_fits (t : Nat) (ht : t < word) :
beta*t + beta < 2^128 := by
have h : t+1 ≤ word := by omega
have ht' := Nat.mul_le_mul_left beta h
rw [Nat.mul_succ] at ht'
exact Nat.lt_of_le_of_lt ht' (by decide)
theorem integer_comparison (t x : Nat) :
(beta*t+beta)/word < (x+1)^2 ↔ beta*(t+1) < (x+1)^2 * word := by
rw [Nat.mul_succ]
exact Nat.div_lt_iff_lt_mul (by decide)
theorem large_profit (t x : Nat) (ht : t < word) (hx : 2^32-1 ≤ x) :
beta*(t+1) < (x+1)^2 * word := by
have h : t+1 ≤ word := by omega
have hx' : 2^32 ≤ x+1 := by omega
have h1 := Nat.mul_le_mul_left beta h
have h2 : beta < (x+1)^2 :=
Nat.lt_of_lt_of_le (by decide : beta < (2^32)^2) (Nat.pow_le_pow_left hx' 2)
exact Nat.lt_of_le_of_lt h1 (Nat.mul_lt_mul_of_pos_right h2 (by decide))
theorem small_square_fits (x : Nat) (hx : x < 2^32-1) :
(x+1)^2 < word := by
have h : x+1 ≤ 2^32-1 := by omega
exact Nat.lt_of_le_of_lt (Nat.pow_le_pow_left h 2) (by decide)
theorem small_branch_fits (t x : Nat) (ht : t ≤ 65536) (hx : x ≤ t) :
79*t < word ∧ 112*x*x+109*x+14 < word := by
have h : x ≤ 65536 := Nat.le_trans hx ht
have p := Nat.mul_le_mul (Nat.mul_le_mul_left 112 h) h
have q := Nat.mul_le_mul_left 109 h
have r := Nat.mul_le_mul_left 79 ht
constructor
· exact Nat.lt_of_le_of_lt r (by decide)
· exact Nat.lt_of_le_of_lt (Nat.add_le_add_right (Nat.add_le_add p q) 14) (by decide)
end CentPlay64
~~~
#### `followups/AdviceCounts.lean`
~~~lean
import Std
/-! Exact arithmetic for the 52-card perfect-advice code. The inputs below are
the two reflection counts in the accompanying proof. All certificates use kernel
reduction, with no native evaluation or assumed numeric facts. -/
namespace AdviceCounts
def fact : Nat → Nat
| 0 => 1
| n+1 => (n+1)*fact n
def choose (n k : Nat) : Nat :=
if k ≤ n then fact n / (fact k * fact (n-k)) else 0
def deals := choose 52 26
/-- Number of deals reaching level h, by reflection. -/
def tail (h : Nat) := if h ≤ 26 then choose 52 (26-h) else 0
def peak (h : Nat) := tail h - tail (h+1)
def labels : List Nat := (List.range 26).map (· + 1)
/-- Label three also accepts all deals with peak zero. -/
def weight (h : Nat) := peak h + (if h = 3 then peak 0 else 0)
def lengths : List Nat :=
[3,3,2,3,3,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,22]
def codeLength (h : Nat) := lengths[h-1]!
def peakBits := (labels.map fun h => weight h * codeLength h).sum
def insertWeight (x : Nat) : List Nat → List Nat
| [] => [x]
| y::ys => if x ≤ y then x::y::ys else y::insertWeight x ys
def sortedWeights := (labels.map weight).foldr insertWeight []
/-- Sum of the combined weights at the 25 greedy Huffman merges. -/
def mergeCost : Nat → List Nat → Nat
| 0, _ => 0
| k+1, ws =>
match ws with
| a :: b :: rest => a+b+mergeCost k (insertWeight (a+b) rest)
| _ => 0
/-- Number of deals whose last red attains the running and final peak h
(the expression is used only for h = 1, 2). -/
def late (h : Nat) := choose (51-h) 25 - choose (51-h) (24-h)
def saved := ([1,2].map fun h => late h * (codeLength h - codeLength 3)).sum
def improved := peakBits - saved
set_option maxRecDepth 8000
set_option maxHeartbeats 5000000
theorem code_certificate :
deals = 495918532948104 ∧ (labels.map weight).sum = deals ∧
lengths.length = 26 ∧ (lengths.map fun k => 2^(22-k)).sum = 2^22 ∧
peakBits = 1545565529332048 ∧
mergeCost 25 sortedWeights = peakBits := by decide
theorem saved_certificate :
late 1 = 18367353072152 ∧ late 2 = 13505406670700 ∧
saved = 31872759742852 ∧ improved = 1513692769589196 := by decide
/-- Equality of the reported reduced fraction in bits per deal, and a strict
upper bound of 3.052301274 bits, expressed by cross-multiplication. -/
theorem upper_certificate :
improved * 5903792058906 = deals * 18020152018919 ∧
improved * 1000000000 < deals * 3052301274 := by decide
end AdviceCounts
~~~
#### `followups/OneBitBound.lean`
~~~lean
import Std
/-! Exact coefficient certificate for the 49/100 Brownian two-nomination
envelope. No transcendental estimates or probabilistic convergence claims
are assumed or asserted by this file. Run with stock Lean 4.19.0. -/
namespace OneBitBound
/-- Coefficients of a polynomial in ascending order. All intermediate
expressions below have degree at most four. -/
abbrev Poly := Nat → Int
def con (a : Int) : Poly := fun j => if j=0 then a else 0
def lin (a b : Int) : Poly := fun j => if j=0 then a else if j=1 then b else 0
def plus (p q : Poly) : Poly := fun i => p i + q i
def times (p q : Poly) : Poly := fun i =>
((List.range (i+1)).map fun j => p j*q (i-j)).sum
def scale (a : Int) (p : Poly) : Poly := fun j => a*p j
def power (p : Poly) : Nat → Poly
| 0 => con 1
| k+1 => times p (power p k)
/-- P(Y/Z) multiplied by 1,500,000,000 Z^4. Both Y and Z are affine
linear in the interval parameter u. Here
p(y) = 1 + (797/1000)y + y²/2 + (797/3000)y³,
P(y) = ((49/100)p(y)-y) f(y) - 368/1000.
The two slopes and intercepts below encode 5000 f. -/
def transform (Y Z : Poly) (intercept slope : Int) : Poly :=
let p := plus (scale 3000 (power Z 3))
(plus (scale 2391 (times Y (power Z 2)))
(plus (scale 1500 (times (power Y 2) Z)) (scale 797 (power Y 3))))
let base := plus (scale 49 p) (scale (-300000) (times Y (power Z 2)))
plus (times base (plus (scale intercept Z) (scale slope Y)))
(scale (-552000000) (power Z 4))
/-- The two linear denominator bounds on [0,13/50], [13/50,1/2],
[1/2,1], [1,infinity). In the bounded intervals Y/Z interpolates between
the endpoints as u runs from 0 to infinity. The last substitution is y=1+u. -/
def pieces : Fin 4 → Poly
| 0 => transform (lin 0 13) (lin 50 50) 3985 5000
| 1 => transform (lin 13 25) (lin 50 50) 3188 8000
| 2 => transform (lin 1 2) (lin 2 2) 3188 8000
| 3 => transform (lin 1 1) (con 1) 3188 8000
set_option maxRecDepth 4096
set_option maxHeartbeats 0
/-- Rational endpoints used to replace sqrt(2/pi) and 1/e. The first
inequality uses pi<22/7 externally, and 1957/720 is the exponential
series at one, summed through degree six. -/
theorem elementary_constants :
797^2 * 11 < 1000^2 * 7 ∧ 720 * 1000 < 1957 * 368 := by decide
/-- All twenty integer coefficients are strictly positive. In particular
each homogenized polynomial is positive at every nonnegative real u. -/
theorem coefficients_positive : ∀ j : Fin 4, ∀ k : Fin 5, 0 < pieces j k := by decide
/-- Evaluate the checked positive coefficients homogeneously at rational
u = n/d. Positivity of the constant term suffices when d is positive. -/
def positiveNumerator (j : Fin 4) (n d : Nat) : Nat :=
((pieces j 0).toNat*d^4) +
((List.range 4).map fun k => (pieces j (k+1)).toNat*n^(k+1)*d^(3-k)).sum
theorem rational_numerator_positive (j : Fin 4) (n d : Nat) (hd : 0
#### `further/formal/Nomination52.lean`
~~~lean
import Lean
import NominationTable
/-! Exact kernel certificate for zero bits (one nomination) and one bit
(two nominations). The only supplied final numerical claims are checked
against the strategy-derived Bellman recurrence on all 729 states. -/
namespace Problem14.Nomination52
open NominationTable NominationGame Lean Meta Elab Term
/-- Generate prospective values. Reduction of the local multi-nomination
Bellman equations, below, decides whether these integers are correct. -/
elab "nomination_snapshot " r:num : term => do
let entries := (NominationTable.grid 26 r.getNat).map fun e =>
mkApp3 (mkConst ``Entry.mk) (toExpr e.ways) (toExpr e.one) (toExpr e.two)
mkListLit (mkConst ``Entry) entries
set_option Elab.async false
set_option maxRecDepth 100000
set_option maxHeartbeats 0
private def row00 : List Entry := nomination_snapshot 0
private theorem checked00 : NominationTable.grid 26 0=row00 := first (by decide +kernel)
macro "nomination_step " target:ident checked:ident prior:ident r:num : command =>
`(section
private def $target : List Entry := nomination_snapshot $r
private theorem $checked : NominationTable.grid 26 $r=$target :=
next $prior (by decide +kernel)
end)
nomination_step row01 checked01 checked00 1
nomination_step row02 checked02 checked01 2
nomination_step row03 checked03 checked02 3
nomination_step row04 checked04 checked03 4
nomination_step row05 checked05 checked04 5
nomination_step row06 checked06 checked05 6
nomination_step row07 checked07 checked06 7
nomination_step row08 checked08 checked07 8
nomination_step row09 checked09 checked08 9
nomination_step row10 checked10 checked09 10
nomination_step row11 checked11 checked10 11
nomination_step row12 checked12 checked11 12
nomination_step row13 checked13 checked12 13
nomination_step row14 checked14 checked13 14
nomination_step row15 checked15 checked14 15
nomination_step row16 checked16 checked15 16
nomination_step row17 checked17 checked16 17
nomination_step row18 checked18 checked17 18
nomination_step row19 checked19 checked18 19
nomination_step row20 checked20 checked19 20
nomination_step row21 checked21 checked20 21
nomination_step row22 checked22 checked21 22
nomination_step row23 checked23 checked22 23
nomination_step row24 checked24 checked23 24
nomination_step row25 checked25 checked24 25
nomination_step row26 checked26 checked25 26
private theorem root_data :
let root := summary 26 (deck 26 26)
(root.ways,root.one[0]!,root.two) = (495918532948104,1301526064015237,1604995391014215) := by
rw [←lookup 26 26 26 (by decide),checked26]
decide +kernel
/-- Deals and total payouts, before division into expected dollars. -/
theorem totals :
(weight (deck 26 26),best (deck 26 26) 1 0,best (deck 26 26) 2 0) =
(495918532948104,1301526064015237,1604995391014215) := by
have h := root_data
dsimp only at h
rw [incumbent_read _ _ (by decide : 0≤26)] at h
exact h
/-- The total payoff over complete deals is bounded for every history-dependent
online nomination callback. The greedy callback attains the bound. -/
theorem optimal_two_nominations :
let t := deck 26 26
(∀ f, ((words t).map (fun cs => (recorded f t [] 2 0 cs).foldl max 0)).sum ≤ 1604995391014215) ∧
((words t).map (fun cs => (recorded (NominationGame.greedy t) t [] 2 0 cs).foldl max 0)).sum = 1604995391014215 := by
have two := congrArg (fun p : Nat × Nat × Nat => p.2.2) totals
change best (deck 26 26) 2 0=1604995391014215 at two
dsimp only
rw [←two]
exact callback_optimum _ _ _
/-- The one-bit expected payoff in reduced dollar units, cross-multiplied. -/
theorem one_bit_price :
best (deck 26 26) 2 0 * 4467734531064 = 14459417937065 * weight (deck 26 26) := by
have w := congrArg Prod.fst totals
have two := congrArg (fun p : Nat × Nat × Nat => p.2.2) totals
change best (deck 26 26) 2 0=1604995391014215 at two
change weight (deck 26 26)=495918532948104 at w
rw [two,w]
theorem one_bit_premium :
(best (deck 26 26) 2 0 - best (deck 26 26) 1 0) * 35422752353436 =
21676380499927 * weight (deck 26 26) := by
have w := congrArg Prod.fst totals
have one := congrArg (fun p : Nat × Nat × Nat => p.2.1) totals
have two := congrArg (fun p : Nat × Nat × Nat => p.2.2) totals
change best (deck 26 26) 1 0=1301526064015237 at one
change best (deck 26 26) 2 0=1604995391014215 at two
change weight (deck 26 26)=495918532948104 at w
rw [one,two,w]
#print axioms optimal_two_nominations
#print axioms one_bit_price
#print axioms one_bit_premium
end Problem14.Nomination52
~~~
#### `further/formal/NominationGame.lean`
~~~lean
import Problem14
/-! Up to q online nominations. A mark records the current score and the game
continues to the next draw. Only the largest nominated score is paid. The
initial incumbent is zero, which the player may secure at expiration. -/
namespace Problem14.NominationGame
def best : Tree → Nat → Nat → Nat
| .empty, _, _ => 0
| .leaf, _, h => h
| .branch _ l r, 0, h => h*(weight l+weight r)
| .branch s l r,q+1,h =>
let newHigh := max h (s.2-s.1)
max (best l (q+1) h+best r (q+1) h)
(best l q newHigh+best r q newHigh)
theorem best_zero (t : Tree) (h : Nat) : best t 0 h = h*weight t := by
cases t <;> simp [best,weight,paths]
theorem best_step (s : State) (l r : Tree) (q h : Nat) :
best (.branch s l r) (q+1) h =
max (best l (q+1) h+best r (q+1) h)
(best l q (max h (s.2-s.1))+best r q (max h (s.2-s.1))) := rfl
/-- A strategy tree chooses whether to nominate before the next card is
revealed. Separate plans on its red and black branches admit arbitrary
dependence on the entire past. A player may retire with nominations unused.
An absent child has no deals. Each leaf contributes its incumbent once. -/
inductive Attains : Tree → Nat → Nat → Nat → Prop
| empty (q h) : Attains .empty q h 0
| leaf (q h) : Attains .leaf q h h
| retire (t q h) : Attains t q h (h*weight t)
| wait {l r q h a b} (s) :
Attains l q h a → Attains r q h b → Attains (.branch s l r) q h (a+b)
| mark {l r q h a b} (s) :
Attains l q (max h (s.2-s.1)) a → Attains r q (max h (s.2-s.1)) b →
Attains (.branch s l r) (q+1) h (a+b)
private theorem weight_branch (s : State) (l r : Tree) :
weight (.branch s l r) = weight l+weight r := by simp [weight,paths]
theorem incumbent_le (t : Tree) (q h : Nat) : h*weight t ≤ best t q h := by
induction t with
| empty | leaf => simp [best,weight,paths]
| branch s l r hl hr =>
cases q with
| zero => rw [best_zero]; exact Nat.le_refl _
| succ q =>
rw [best_step,weight_branch,Nat.mul_add]
exact Nat.le_trans (Nat.add_le_add hl hr) (Nat.le_max_left _ _)
private theorem wait_le (s : State) (l r : Tree) (q h : Nat) :
best l q h+best r q h ≤ best (.branch s l r) q h := by
cases q with
| zero => rw [best_zero,best_zero,best_zero,weight_branch,Nat.mul_add]; exact Nat.le_refl _
| succ q => exact Nat.le_max_left _ _
/-- No legal full-history strategy earns more than the recurrence. -/
theorem bounds {t q h v} (run : Attains t q h v) : v ≤ best t q h := by
induction run with
| empty | leaf => exact Nat.le_refl _
| retire t q h => exact incumbent_le t q h
| wait s _ _ il ir => exact Nat.le_trans (Nat.add_le_add il ir) (wait_le s _ _ _ _)
| mark s _ _ il ir => exact Nat.le_trans (Nat.add_le_add il ir) (Nat.le_max_right _ _)
private theorem choose_max {P : Nat → Prop} {x y : Nat} (a : P x) (b : P y) : P (max x y) := by
rcases Nat.le_total x y with h|h
· rwa [Nat.max_eq_right h]
· rwa [Nat.max_eq_left h]
/-- The full-history strategy realizing the dynamic-programming value exists. -/
theorem attainable (t : Tree) (q h : Nat) : Attains t q h (best t q h) := by
induction t generalizing q h with
| empty => exact .empty q h
| leaf => exact .leaf q h
| branch s l r il ir =>
cases q with
| zero => rw [best_zero]; exact .retire _ _ _
| succ q =>
rw [best_step]
exact choose_max (.wait s (il _ _) (ir _ _)) (.mark s (il _ _) (ir _ _))
/-- Legal strategies can discard an extra nomination. -/
theorem extra {t q h v} (run : Attains t q h v) : Attains t (q+1) h v := by
induction run with
| empty => exact .empty _ _
| leaf => exact .leaf _ _
| retire t q h => exact .retire _ _ _
| wait s _ _ il ir => exact .wait s il ir
| mark s _ _ il ir => exact .mark s il ir
theorem budget_mono (t : Tree) (q h : Nat) : best t q h ≤ best t (q+1) h :=
bounds (extra (attainable t q h))
/-- Behavior specified by any deterministic history-dependent decision
function. The history records colors, in reverse chronological order. True
means red. At a node the callback sees the past, the remaining budget, the
incumbent and the current state, before either possible child is chosen. -/
def run (decideMark : List Bool → Nat → Nat → State → Bool) :
Tree → List Bool → Nat → Nat → Nat
| .empty,_,_,_ => 0
| .leaf,_,_,h => h
| .branch _ l r,_,0,h => h*(weight l+weight r)
| .branch s l r,hist,q+1,h =>
if decideMark hist (q+1) h s then
let high := max h (s.2-s.1)
run decideMark l (true::hist) q high + run decideMark r (false::hist) q high
else
run decideMark l (true::hist) (q+1) h + run decideMark r (false::hist) (q+1) h
theorem callback_attains (f) (t : Tree) (hist : List Bool) (q h : Nat) :
Attains t q h (run f t hist q h) := by
induction t generalizing hist q h with
| empty => exact .empty _ _
| leaf => exact .leaf _ _
| branch s l r il ir =>
cases q with
| zero =>
simp only [run,← weight_branch s l r]
exact .retire _ _ _
| succ q =>
simp only [run]
split
· exact .mark s (il _ _ _) (ir _ _ _)
· exact .wait s (il _ _ _) (ir _ _ _)
theorem callback_bounds (f) (t : Tree) (hist : List Bool) (q h : Nat) :
run f t hist q h ≤ best t q h := bounds (callback_attains f t hist q h)
/-- Recover the current node using only the observed (reversed) color history. -/
def locate (root : Tree) : List Bool → Tree
| [] => root
| c :: hist =>
match locate root hist with
| .branch _ l r => if c then l else r
| _ => .empty
/-- Choose a nomination only if it improves the incumbent. Ties between
waiting and an improving nomination favor the nomination. -/
def greedyAt : Tree → Nat → Nat → Bool
| .branch s l r,q+1,h =>
let v := s.2-s.1
decide (h false
def greedy (root : Tree) (hist : List Bool) (q h : Nat) (_ : State) :=
greedyAt (locate root hist) q h
private theorem greedy_rooted (root t : Tree) (hist : List Bool) (q h : Nat)
(atNode : locate root hist=t) :
run (greedy root) t hist q h = best t q h := by
induction t generalizing hist q h with
| empty | leaf => rfl
| branch s l r il ir =>
cases q with
| zero => rfl
| succ q =>
have left : locate root (true::hist)=l := by simp [locate,atNode]
have right : locate root (false::hist)=r := by simp [locate,atNode]
simp only [run,greedy,atNode,greedyAt,decide_eq_true_eq,best_step]
rw [il _ _ _ left,ir _ _ _ right,il _ _ _ left,ir _ _ _ right]
by_cases improve : h []
| .leaf => [[]]
| .branch _ l r => (words l).map (true::·) ++ (words r).map (false::·)
private theorem word_count (t : Tree) : (words t).length = weight t := by
induction t with
| empty | leaf => rfl
| branch s l r il ir => simp [words,weight_branch,il,ir]
/-- The actual scores nominated by a callback on one fixed color word. -/
def recorded (f : List Bool → Nat → Nat → State → Bool) :
Tree → List Bool → Nat → Nat → List Bool → List Nat
| .branch s l r,hist,q+1,h,c::cs =>
let child := if c then l else r
if f hist (q+1) h s then
(s.2-s.1) :: recorded f child (c::hist) q (max h (s.2-s.1)) cs
else recorded f child (c::hist) (q+1) h cs
| _,_,_,_,_ => []
theorem recorded_length (f) (t : Tree) (hist : List Bool) (q h : Nat) (cs : List Bool) :
(recorded f t hist q h cs).length ≤ q := by
induction t generalizing hist q h cs with
| empty | leaf => simp [recorded]
| branch s l r il ir =>
cases q with
| zero => simp [recorded]
| succ q =>
cases cs with
| nil => simp [recorded]
| cons c cs =>
cases c <;> simp only [recorded,Bool.false_eq_true,if_false,if_true] <;> split
· simpa using Nat.succ_le_succ (ir _ _ _ _)
· exact ir _ _ _ _
· simpa using Nat.succ_le_succ (il _ _ _ _)
· exact il _ _ _ _
private theorem sum_join (a b : List Nat) : (a++b).sum = a.sum+b.sum := by
induction a with
| nil => simp
| cons _ _ ih => simp [ih,Nat.add_assoc]
private theorem sum_const {α : Type} (a : List α) (h : Nat) :
(a.map (fun _ => h)).sum = h*a.length := by
induction a with
| nil => simp
| cons _ _ ih => simp [ih,Nat.mul_succ,Nat.add_comm]
/-- The abstract integer evaluator sums the literal maximum nominated score
over all deals. This identifies both the maximum payout and its normalization. -/
theorem sum_pathwise (f) (t : Tree) (hist : List Bool) (q h : Nat) :
((words t).map (fun cs => (recorded f t hist q h cs).foldl max h)).sum = run f t hist q h := by
induction t generalizing hist q h with
| empty => rfl
| leaf => simp [words,recorded,run]
| branch s l r il ir =>
cases q with
| zero =>
simp only [recorded,List.foldl_nil,sum_const,word_count,weight_branch,run]
| succ q =>
simp only [words,List.map_append,sum_join,List.map_map,Function.comp_def,recorded,
Bool.false_eq_true,if_true,if_false,run]
cases a : f hist (q+1) h s <;>
simp only [a,if_true,if_false,Bool.false_eq_true,List.foldl_cons,il,ir]
/-- Exact maximum over online history callbacks, expressed in individual
deal payoffs, for arbitrary trees, incumbents, and numbers of nominations. -/
theorem callback_optimum (t : Tree) (q h : Nat) :
(∀ f, ((words t).map (fun cs => (recorded f t [] q h cs).foldl max h)).sum ≤ best t q h) ∧
((words t).map (fun cs => (recorded (greedy t) t [] q h cs).foldl max h)).sum = best t q h := by
constructor
· intro f; rw [sum_pathwise]; exact callback_bounds ..
· rw [sum_pathwise,optimal_callback]
#print axioms bounds
#print axioms attainable
#print axioms callback_optimum
end Problem14.NominationGame
~~~
#### `further/formal/NominationTable.lean`
~~~lean
import NominationGame
/-! One nomination needs one value per incumbent. Two nominations need only
the zero-incumbent slot before the first nomination. Every subsequent history
is covered by the one-nomination slots. -/
namespace Problem14.NominationTable
open NominationGame
structure Entry where
ways : Nat
one : List Nat
two : Nat
deriving Inhabited, DecidableEq, Repr
def tab {α : Type} (f : Nat → α) (start : Nat) : Nat → List α
| 0 => []
| n+1 => f start :: tab f (start+1) n
private theorem get_tab {α : Type} [Inhabited α] (f : Nat → α) (a n i : Nat) (hi : i omega
| succ n ih =>
cases i with
| zero => simp [tab]
| succ i =>
simp only [tab,List.getElem!_eq_getElem?_getD,List.getElem?_cons_succ]
simpa [Nat.add_assoc,Nat.add_comm,Nat.add_left_comm] using ih (a+1) i (by omega)
def merge (w c h : Nat) : List Nat → List Nat → List Nat
| x::xs, y::ys => max (x+y) (max h c*w) :: merge w c (h+1) xs ys
| _, _ => []
def joint (c : Nat) (l r : Entry) : Entry :=
let w := l.ways+r.ways
⟨w,merge w c 0 l.one r.one,max (l.two+r.two) (l.one[c]!+r.one[c]!)⟩
def summary (B : Nat) (t : Tree) : Entry :=
⟨weight t, tab (best t 1) 0 (B+1), best t 2 0⟩
def absent (B : Nat) : Entry := ⟨0,tab (fun _ => 0) 0 (B+1),0⟩
def terminal (B : Nat) : Entry := ⟨1,tab id 0 (B+1),0⟩
private theorem merge_tab (w c a n : Nat) (f g : Nat → Nat) :
merge w c a (tab f a n) (tab g a n) =
tab (fun h => max (f h+g h) (max h c*w)) a n := by
induction n generalizing a with
| zero => rfl
| succ n ih => simp [tab,merge,ih]
private theorem node (B : Nat) (s : State) (l r : Tree) (bound : s.2-s.1≤B) :
joint (s.2-s.1) (summary B l) (summary B r) = summary B (.branch s l r) := by
have w : weight (.branch s l r)=weight l+weight r := by simp [weight, paths]
have one : (fun h => max (best l 1 h+best r 1 h) (max h (s.2-s.1)*(weight l+weight r))) =
best (.branch s l r) 1 := by
funext h
rw [best_step _ _ _ 0, best_zero,best_zero,Nat.mul_add]
have fits : s.2-s.1
cases b with
| zero => simp [cell,model,deck,summary,terminal,weight,paths,best]; rfl
| succ b =>
simp only [cell,above,left,model,Nat.zero_add,Nat.add_one_ne_zero,if_false,if_true,
Nat.add_sub_cancel,Nat.sub_zero]
rw [deck.eq_3,empty]
exact node B (0,b+1) _ _ hb
| succ r =>
cases b with
| zero =>
simp only [cell,above,left,model,Nat.add_zero,Nat.add_one_ne_zero,if_false,if_true,
Nat.add_sub_cancel,Nat.zero_sub]
rw [deck.eq_2,empty]
simpa only [Nat.zero_sub] using node B (r+1,0) (deck r 0) .empty (by simp)
| succ b =>
have nz : r+1+(b+1)≠0 := by omega
simp only [cell,above,left,model,Nat.add_one_ne_zero,if_false,Nat.add_sub_cancel,nz]
rw [deck.eq_4]
exact node B (r+1,b+1) _ _ (by change b+1-(r+1)≤B; omega)
/-- Compute left to right, starting from the row immediately above. -/
def row (B r b : Nat) (prior : Entry) : List Entry → List Entry
| [] => []
| up::ups =>
let v := cell B r b up prior
v :: row B r (b+1) v ups
private theorem row_correct (B r b n : Nat) (limit : b+n≤B+1) :
row B r b (left B r b) (tab (above B r) b n) = tab (model B r) b n := by
induction n generalizing b with
| zero => rfl
| succ n ih =>
simp only [tab,row,model_cell B r b (by omega)]
have prev : left B r (b+1)=model B r b := by simp [left]
rw [←prev,ih _ (by omega)]
def grid (B : Nat) : Nat → List Entry
| 0 => row B 0 0 (absent B) (tab (fun _ => absent B) 0 (B+1))
| r+1 => row B (r+1) 0 (absent B) (grid B r)
theorem grid_correct (B r : Nat) : grid B r = tab (model B r) 0 (B+1) := by
induction r with
| zero => exact row_correct B 0 0 (B+1) (by omega)
| succ r ih =>
rw [grid,ih]
simpa [above,left] using row_correct B (r+1) 0 (B+1) (by omega)
theorem lookup (B r b : Nat) (hb : b≤B) : (grid B r)[b]! = summary B (deck r b) := by
rw [grid_correct,get_tab _ _ _ _ (by omega),Nat.zero_add]
rfl
theorem incumbent_read (B : Nat) (t : Tree) {h : Nat} (hb : h≤B) :
(summary B t).one[h]! = best t 1 h := by
unfold summary; rw [get_tab _ _ _ _ (by omega),Nat.zero_add]
/-- Compare literal candidates against their neighbors, then advance with
the literal certified predecessor. This keeps reductions local. -/
def checks (B r b : Nat) (prior : Entry) : List Entry → List Entry → Bool
| [], [] => true
| up::ups, v::vs => decide (cell B r b up prior=v) && checks B r (b+1) v ups vs
| _,_ => false
private theorem checked_row (B r b : Nat) (prior : Entry) (ups vs : List Entry)
(ok : checks B r b prior ups vs = true) : row B r b prior ups = vs := by
induction ups generalizing b prior vs with
| nil => cases vs <;> simp_all [checks,row]
| cons up ups ih =>
cases vs with
| nil => simp [checks] at ok
| cons v vs =>
simp only [checks,Bool.and_eq_true,decide_eq_true_eq] at ok
simp only [row,ok.1,ih _ _ _ ok.2]
theorem first {B : Nat} {v : List Entry}
(ok : checks B 0 0 (absent B) (tab (fun _ => absent B) 0 (B+1)) v=true) : grid B 0=v :=
checked_row _ _ _ _ _ _ ok
theorem next {B r : Nat} {u v : List Entry} (prev : grid B r=u)
(ok : checks B (r+1) 0 (absent B) u v=true) : grid B (r+1)=v := by
rw [grid,prev]
exact checked_row _ _ _ _ _ _ ok
end Problem14.NominationTable
~~~
#### `further/formal/PreviewPremium.lean`
~~~lean
import PreviewRecall
/-! A one-dollar bound on each downward step gives a sharp pathwise k-dollar
upper bound on the value of k-card preview over ordinary stopping. -/
namespace Problem14.PreviewRecall
universe u v
variable {Path : Type u} {Observation : Type v}
variable {observe : Path → Nat → Observation} {N k : Nat} {choose : Path → Nat}
/-- The card game's cumulative score changes by +1 or −1. Only the maximum
size of a downward step is needed here. -/
def DownwardBound (score : Path → Nat → Int) (N : Nat) :=
∀ x i, i omega
/-- Ignoring the lookahead recovers every ordinary stopping policy. -/
theorem ordinary_is_preview {s : Path → Nat} (p : Stopping observe N s) : Preview observe N k s :=
⟨p.bounded, fun x y visible => p.adapted x y
(shorterPrefix visible (Nat.le_min.mpr ⟨p.bounded x,Nat.le_add_right _ _⟩))⟩
where
shorterPrefix {a b : Nat} {x y : Path} (visible : SamePrefix observe b x y) (h : a≤b) :
SamePrefix observe a x y := fun i hi => visible i (Nat.lt_of_lt_of_le hi h)
private theorem telescopes {score : Path → Nat → Int} (step : DownwardBound score N)
(x : Path) {i j : Nat} (ordered : i≤j) (bounded : j≤N) :
score x i≤score x j+(j: Int)-(i: Int) := by
induction j with
| zero =>
have z : i=0 := by omega
rw [z]
omega
| succ j ih =>
by_cases e : i=j+1
· rw [e]; omega
· have prior := ih (by omega) (by omega)
have drop := step x j (by omega)
omega
/-- Every preview policy has a particular ordinary policy whose payoff on
each path is at most k dollars smaller. -/
theorem pathwise_premium {score : Path → Nat → Int} (step : DownwardBound score N)
(preview : Preview observe N k choose) :
∃ stop, Stopping observe N stop ∧ ∀ x, score x (choose x)≤score x (stop x)+(k:Int) := by
let p := preview.toRecall
refine ⟨p.commit,p.stopping,?_⟩
intro x
obtain ⟨left,right⟩ := p.window x
have difference := telescopes step x right (p.stopping.bounded x)
omega
private def total (paths : List Path) (pay : Path → Int) := (paths.map pay).sum
private theorem sum_bound (paths : List Path) (f g : Path → Int)
(h : ∀ x, f x≤g x+(k:Int)) : total paths f≤total paths g+paths.length*k := by
induction paths with
| nil => simp [total]
| cons x xs ih =>
have head := h x
simp only [total,List.map_cons,List.sum_cons,List.length_cons,Int.natCast_succ,
Int.add_mul,Int.one_mul] at ih ⊢
omega
/-- For uniform deals, divide by the number of paths to get the k-dollar
price premium bound. Repeating paths permits arbitrary rational weights. -/
theorem finite_premium {score : Path → Nat → Int} (step : DownwardBound score N)
(paths : List Path) (ordinaryUpper : Int)
(ordinary : ∀ s, Stopping observe N s →
(paths.map (fun x => score x (s x))).sum≤ordinaryUpper)
(preview : Preview observe N k choose) :
(paths.map (fun x => score x (choose x))).sum≤ordinaryUpper+paths.length*k := by
obtain ⟨s,legal,comparison⟩ := pathwise_premium step preview
have bound := sum_bound paths _ _ comparison
have v := ordinary s legal
unfold total at bound
omega
#print axioms pathwise_premium
#print axioms finite_premium
end Problem14.PreviewRecall
~~~
#### `further/formal/StreakGame.lean`
~~~lean
import Mathlib.Data.Rat.Lemmas
import Mathlib.Tactic.Linarith
import Mathlib.Tactic.FieldSimp
import Mathlib.Tactic.Ring
import Mathlib.Tactic.Positivity
/-! Expected gains above the current payoff for optional next-card vouchers. -/
namespace Problem14.TerminalStreak
def mix (r b : Nat) (x y : ℚ) : ℚ := (r*x+b*y)/(r+b)
def value (m r b : Nat) : ℚ :=
match r,b with
| 0,_ => 0
| r+1,0 => r+1
| r+1,b+1 =>
let blind := mix (r+1) (b+1) (1+value m r (b+1)) (value m (r+1) b-1)
match m with
| 0 => max 0 blind
| k+1 => max (max 0 blind) (mix (r+1) (b+1)
(1+value k r (b+1)) (max 0 (value k (r+1) b-1)))
termination_by r+b
theorem value_nonneg (m r b : Nat) : 0≤value m r b := by
cases r with
| zero => simp [value]
| succ r =>
cases b with
| zero => simp [value]; positivity
| succ b => cases m <;> simp [value]
end Problem14.TerminalStreak
~~~
#### `further/formal/TerminalStreak.lean`
~~~lean
import StreakGame
import Mathlib.Data.Nat.Choose.Basic
/-! A single terminal run of positive cards, after an optimal period of blind
play, has the same value as vouchers that may be freely interspersed with draws. -/
namespace Problem14.TerminalStreak
def bonus : Nat → Nat → Nat → ℚ
| 0, _, _ => 0
| _+1, 0, _ => 0
| m+1,r+1,b => ((r:ℚ)+1)/((r:ℚ)+1+b)*(1+bonus m r b)
def aux (m r b : Nat) : ℚ :=
match r,b with
| 0,_ => 0
| r+1,0 => max 0 ((r:ℚ)+1-m)
| r+1,b+1 => max 0 (mix (r+1) (b+1) (1+aux m r (b+1)) (aux m (r+1) b-1))
termination_by r+b
def single (m r b : Nat) : ℚ := bonus m r b + aux m r b
theorem mix_mono (r b : Nat) {a b' c d : ℚ} (h : a≤c) (k : b'≤d) :
mix r b a b' ≤ mix r b c d := by
unfold mix
gcongr <;> positivity
private theorem mix_shift (r b : Nat) (h : 0 cases b <;> simp [aux]
theorem bonus_zero_red (m b : Nat) : bonus m 0 b=0 := by cases m <;> rfl
private theorem bonus_nonneg (m r b : Nat) : 0≤bonus m r b := by
induction m generalizing r with
| zero => simp [bonus]
| succ m ih =>
cases r with
| zero => simp [bonus]
| succ r =>
rw [bonus]
exact mul_nonneg (div_nonneg (by positivity) (by positivity)) (by linarith [ih r])
private theorem bonus_mono (m r b : Nat) : bonus m r b≤bonus (m+1) r b := by
induction m generalizing r with
| zero => exact (bonus_nonneg 1 r b)
| succ m ih => cases r with
| zero => simp [bonus]
| succ r =>
rw [bonus,bonus]
exact mul_le_mul_of_nonneg_left (add_le_add_left (ih r) 1) (div_nonneg (by positivity) (by positivity))
private theorem bonus_axis (m r : Nat) : bonus m r 0 = (min m r:Nat) := by
induction m generalizing r with
| zero => simp [bonus]
| succ m ih =>
cases r with
| zero => simp [bonus]
| succ r =>
have h : (r:ℚ)+1 ≠ 0 := by positivity
have mm : min (m+1) (r+1) = min m r + 1 := by omega
simp [bonus,ih,div_self h,mm,add_comm]
private theorem bonus_harmonic (m r b : Nat) : bonus m r (b+1)=
mix r (b+1) (bonus m (r-1) (b+1)) (bonus m r b) := by
induction m generalizing r b with
| zero => simp [bonus,mix]
| succ m ih =>
cases r with
| zero => simp [bonus,mix]
| succ r =>
cases r with
| zero =>
simp only [bonus,bonus_zero_red,Nat.zero_sub,Nat.cast_zero,Nat.cast_succ]
unfold mix
push_cast
have a : (b:ℚ)+1≠0 := by positivity
have d : 1+((b:ℚ)+1)≠0 := by positivity
field_simp; ring
| succ r =>
have h := ih (r+1) b
simp only [Nat.add_sub_cancel] at h ⊢
rw [bonus, h, bonus, bonus]
unfold mix
push_cast
have t : (r:ℚ)+1+(b+1)≠0 := by positivity
have d : (r:ℚ)+1+1+b≠0 := by positivity
have u : (r:ℚ)+1+1+(b+1)≠0 := by positivity
field_simp; ring
/-- Raising the terminal liquidation deduction by one costs at most one dollar. -/
private theorem aux_lipschitz (m r b : Nat) : aux m r b ≤ aux (m+1) r b + 1 := by
induction r generalizing b with
| zero => simp [aux]
| succ r ir =>
induction b with
| zero =>
rw [aux,aux]; push_cast
rcases le_total 0 ((r:ℚ)+1-(m+1)) with h|h
· rw [max_eq_right h]; exact max_le (by linarith) (by linarith)
· rw [max_eq_left h]; exact max_le (by linarith) (by linarith)
| succ b ib =>
rw [aux,aux]
apply max_le
· have := le_max_left 0 (mix (r+1) (b+1) (1+aux (m+1) r (b+1)) (aux (m+1) (r+1) b-1))
linarith
· apply le_trans _ (add_le_add_right (le_max_right 0 _) 1)
rw [← mix_shift _ _ (by omega)]
apply mix_mono
· linarith [ir (b+1)]
· linarith
/-- Domination under adding a red card and raising the deduction together. -/
private theorem tagged (m r b : Nat) : aux m r b ≤ aux (m+1) (r+1) b := by
induction r generalizing b with
| zero => simpa only [aux.eq_1] using aux_nonneg (m+1) 1 b
| succ r ir =>
induction b with
| zero =>
rw [aux,aux]; push_cast; apply le_of_eq; congr 1; ring
| succ b ib =>
have A := aux_lipschitz m (r+1) (b+1)
have R := ir (b+1)
have B := ib
have U := aux_nonneg (m+1) (r+1+1) (b+1)
by_cases zero : aux m (r+1) (b+1) ≤ 0
· exact le_trans zero U
have eq : aux m (r+1) (b+1) =
mix (r+1) (b+1) (1+aux m r (b+1)) (aux m (r+1) b-1) := by
rw [aux] at zero ⊢
apply max_eq_right
by_contra! h
exact zero (max_eq_left h.le).le
rw [aux.eq_3 (m+1)]
apply le_trans _ (le_max_right _ _)
unfold mix at eq ⊢
push_cast at eq ⊢
have t : 0<(r:ℚ)+1+(b+1) := by positivity
have d : 0<(r:ℚ)+1+1+(b+1) := by positivity
rw [eq_div_iff t.ne'] at eq
rw [le_div_iff₀ d]
nlinarith only [eq,A,mul_nonneg (show 0≤(r:ℚ)+1 by positivity) (sub_nonneg.mpr R),
mul_nonneg (show 0≤(b:ℚ)+1 by positivity) (sub_nonneg.mpr B)]
theorem single_nonneg (m r b : Nat) : 0≤single m r b :=
add_nonneg (bonus_nonneg ..) (aux_nonneg ..)
private theorem bonus_le_single (m r b : Nat) : bonus m r b≤single m r b :=
le_add_of_nonneg_right (aux_nonneg ..)
theorem single_zero (m b : Nat) : single m 0 b=0 := by
simp only [single,bonus_zero_red,aux.eq_1,add_zero]
theorem single_axis (m r : Nat) : single m (r+1) 0=(r:ℚ)+1 := by
rw [single,bonus_axis,aux]
rcases le_total m (r+1) with h|h
· have hh : (m:ℚ)≤r+1 := by exact_mod_cast h
rw [min_eq_left h,max_eq_right (sub_nonneg.mpr hh)]
ring
· have hh : (r:ℚ)+1≤m := by exact_mod_cast h
rw [min_eq_right h,max_eq_left (sub_nonpos.mpr hh)]
simp
/-- The ordinary stopping Bellman recurrence with terminal streak reward. -/
theorem single_step (m r b : Nat) : single m (r+1) (b+1) =
max (bonus m (r+1) (b+1)) (mix (r+1) (b+1)
(1+single m r (b+1)) (single m (r+1) b-1)) := by
rw [single,aux,add_max,add_zero]
congr 1
rw [bonus_harmonic m (r+1) b]
simp only [Nat.add_sub_cancel]
unfold mix single
ring
private theorem single_mono (m r b : Nat) : single m r b ≤ single (m+1) r b := by
induction r generalizing b with
| zero => simp only [single_zero,le_refl]
| succ r ir =>
induction b with
| zero => simp only [single_axis,le_refl]
| succ b ib =>
rw [single_step,single_step]
exact max_le_max (bonus_mono ..) (mix_mono _ _
(add_le_add_left (ir (b+1)) _) (sub_le_sub_right ib _))
/-- A single peek that stops on black cannot improve on the terminal run. -/
private theorem stop_black (m r b : Nat) :
mix (r+1) (b+1) (1+single m r (b+1)) 0 ≤ single (m+1) (r+1) (b+1) := by
have price : mix (r+1) (b+1) (1+single m r (b+1)) 0 =
bonus (m+1) (r+1) (b+1) +
(((r:ℚ)+1)/((r:ℚ)+1+(b+1))) * aux m r (b+1) := by
unfold mix single
rw [bonus]
push_cast
ring
rw [price,single]
apply add_le_add_left
apply le_trans _ (tagged m r (b+1))
apply mul_le_of_le_one_left (aux_nonneg ..)
apply (div_le_iff₀ (by positivity)).mpr
linarith [show (0:ℚ) ≤ b by positivity]
/-- Every adaptive budget, at every composition, admits the optimal one-switch policy. -/
theorem value_eq_single (m r b : Nat) : value m r b = single m r b := by
induction r generalizing m b with
| zero => simp [value,single_zero]
| succ r ir =>
induction b generalizing m with
| zero => simp [value,single_axis]
| succ b ib =>
cases m with
| zero => rw [value,single_step,ir,ib]; rfl
| succ m =>
rw [value,ir,ib,ir,ib]
let d := mix (r+1) (b+1) (1+single (m+1) r (b+1)) (single (m+1) (r+1) b-1)
let peek := mix (r+1) (b+1) (1+single m r (b+1)) (max 0 (single m (r+1) b-1))
change max (max 0 d) peek = single (m+1) (r+1) (b+1)
have draw : d ≤ single (m+1) (r+1) (b+1) := by
rw [single_step]; exact le_max_right _ _
apply le_antisymm
· apply max_le (max_le (single_nonneg ..) draw)
dsimp only [peek]
rcases le_total (single m (r+1) b-1) 0 with h|h
· rw [max_eq_left h]; exact stop_black ..
· rw [max_eq_right h]; apply le_trans _ draw
exact mix_mono _ _ (add_le_add_left (single_mono ..) _) (sub_le_sub_right (single_mono ..) _)
· rw [single_step]
apply max_le _ (le_trans (le_max_right 0 d) (le_max_left _ _))
apply le_trans _ (le_max_right _ peek)
unfold peek
have base : bonus (m+1) (r+1) (b+1) =
mix (r+1) (b+1) (1+bonus m r (b+1)) 0 := by
rw [bonus]
unfold mix
push_cast
ring
rw [base]
exact mix_mono _ _ (add_le_add_left (bonus_le_single ..) _) (le_max_left ..)
/-- The hockey-stick expression for all terminal-streak rewards used by the solver. -/
theorem bonus_binomial (m r b : Nat) :
((r+b).choose b:ℚ)*bonus m r b =
((r+b).choose (b+1):ℚ)-((r-m+b).choose (b+1):ℚ) := by
induction m generalizing r with
| zero => simp [bonus]
| succ m ih =>
cases r with
| zero => simp [bonus]
| succ r =>
have hr : r+1+b = r+b+1 := by omega
have hd : r+b+1-b = r+1 := by omega
have den : (r:ℚ)+1+b ≠ 0 := by positivity
have nm := Nat.choose_mul_succ_eq (r+b) b
rw [hd] at nm
have step : ((r+1+b).choose b:ℚ)*(((r:ℚ)+1)/((r:ℚ)+1+b)) = (r+b).choose b := by
rw [hr,mul_div_assoc',div_eq_iff den]
have h : ((r+b).choose b:ℚ)*(r+b+1)=((r+b+1).choose b:ℚ)*(r+1) := by
exact_mod_cast nm
linarith only [h]
rw [bonus,← mul_assoc,step,mul_add,mul_one,ih,hr,Nat.choose_succ_succ]
simp only [Nat.succ_sub_succ_eq_sub,Nat.cast_add]
ring
#print axioms value_eq_single
end Problem14.TerminalStreak
~~~
#### `further/formal/VoucherBridge.lean`
~~~lean
import Vouchers
import TerminalStreak
import Mathlib.Data.Nat.Choose.Basic
import Mathlib.Tactic.LinearCombination
/-! The rational extra-gain recurrence in the terminal-streak analysis
calculates exactly the optimum over legal voucher strategies. -/
namespace Problem14.Vouchers.Bridge
open TerminalStreak
private def mass (r b : ℕ) : ℚ := weight (deck r b)
private def cash (R r b : ℕ) : ℚ := reward R (r,b)
private def affine (c w v : ℚ) := (c+v)*w
private theorem count (r b : ℕ) : weight (deck r b)=(r+b).choose b := by
have branch (s : State) (l u : Tree) :
weight (.branch s l u)=weight l+weight u := by simp [weight,paths]
induction r,b using deck.induct with
| case1 => simp [deck,weight,paths]
| case2 r ih => simp only [deck.eq_2,branch,ih]; simp [weight,paths]
| case3 b ih => simp only [deck.eq_3,branch,ih]; simp [weight,paths]
| case4 r b l u =>
rw [deck.eq_4,branch,l,u,show r+1+(b+1)=(r+b+1)+1 by omega,Nat.choose_succ_succ]
rw [show r+(b+1)=r+b+1 by omega,show r+1+b=r+b+1 by omega,Nat.add_comm]
private theorem split_mass (r b : ℕ) : mass (r+1) (b+1)=mass r (b+1)+mass (r+1) b := by
simp [mass,deck.eq_4,weight,paths]
private theorem mass_mix (r b : ℕ) (x y : ℚ) :
mix (r+1) (b+1) x y * mass (r+1) (b+1) = x*mass r (b+1)+y*mass (r+1) b := by
have a := Nat.choose_mul_succ_eq (r+b+1) (b+1)
rw [show r+b+1+1-(b+1)=r+1 by omega] at a
have d := Nat.succ_mul_choose_eq (r+b+1) b
have left : mass r (b+1)*((r:ℚ)+1+(b+1))=mass (r+1) (b+1)*(r+1) := by
unfold mass
rw [count,count,show r+(b+1)=r+b+1 by omega,show r+1+(b+1)=r+b+1+1 by omega]
convert (show (↑((r+b+1).choose (b+1)):ℚ)*(r+b+1+1)=↑((r+b+1+1).choose (b+1))*(r+1) by
exact_mod_cast a) using 1; ring
have right : ((r:ℚ)+1+(b+1))*mass (r+1) b=mass (r+1) (b+1)*(b+1) := by
unfold mass
rw [count,count,show r+1+b=r+b+1 by omega,show r+1+(b+1)=r+b+1+1 by omega]
convert (show ((r:ℚ)+b+1+1)*↑((r+b+1).choose b)=↑((r+b+1+1).choose (b+1))*(b+1) by
exact_mod_cast d) using 1; ring
unfold mix
push_cast
have pos : (r:ℚ)+1+((b:ℚ)+1)≠0 := by positivity
field_simp [pos]
linear_combination -x*left-y*right
private theorem affine_mix (r b : ℕ) (c x y : ℚ) :
affine c (mass (r+1) (b+1)) (mix (r+1) (b+1) x y) =
affine c (mass r (b+1)) x + affine c (mass (r+1) b) y := by
unfold affine
rw [add_mul,mass_mix,split_mass]
ring
private theorem affine_max (c w x y : ℚ) (h : 0≤w) :
affine c w (max x y) = max (affine c w x) (affine c w y) := by
rw [affine,add_max,max_mul_of_nonneg _ _ h]
rfl
private theorem cash_formula {R r b : ℕ} (h : r≤R) : cash R r b=(R:ℚ)-r+b := by
simp [cash,reward,Nat.cast_sub h]
private theorem red_cash {R r b : ℕ} (h : r+1≤R) :
cash R r (b+1)=cash R (r+1) (b+1)+1 := by
rw [cash_formula (by omega : r≤R),cash_formula h]
push_cast
ring
private theorem black_cash {R r b : ℕ} (h : r+1≤R) :
cash R (r+1) b=cash R (r+1) (b+1)-1 := by
rw [cash_formula h,cash_formula h]
push_cast
ring
private theorem all_black (R b m : ℕ) : best R (deck 0 b) (.finite m) = R+b := by
induction b generalizing m with
| zero => simp [deck,best]
| succ b ih =>
have wt : weight (deck 0 b)=1 := by rw [count]; simp
have empty : weight Tree.empty=0 := rfl
cases m <;> simp only [deck.eq_3,best,offer,informed,wt,empty,ih,reward,Nat.zero_add,
Nat.sub_zero,Nat.mul_zero,Nat.mul_one,Nat.add_zero] <;> omega
private theorem all_red (R r m : ℕ) (h : r≤R) : best R (deck r 0) (.finite m) = R := by
induction r generalizing m with
| zero => simp [deck,best]
| succ r ih =>
have wt : weight (deck r 0)=1 := by rw [count]; simp
have all (j : Nat) : best R (deck r 0) (.finite j)=R := ih (m:=j) (by omega)
have empty : weight Tree.empty=0 := rfl
cases m <;> simp only [deck.eq_2,best,offer,informed,wt,empty,all,reward,Nat.zero_add,
Nat.mul_zero,Nat.mul_one,Nat.add_zero] <;> omega
private theorem mass_positive (r b : ℕ) : 0≤mass r b := Nat.cast_nonneg _
private theorem models {R r b : ℕ} (h : r≤R) (m : ℕ) :
(best R (deck r b) (.finite m) : ℚ) = affine (cash R r b) (mass r b) (value m r b) := by
induction r,b using deck.induct generalizing m with
| case1 =>
rw [all_black]
simp [cash,reward,affine,mass,deck,weight,paths,value]
| case2 r _ =>
rw [all_red _ _ _ h, cash_formula h,affine]
have e : mass (r+1) 0=1 := by simp [mass,count]
rw [e,value]
push_cast; ring
| case3 b _ =>
rw [all_black,cash_formula (Nat.zero_le _),affine]
have e : mass 0 (b+1)=1 := by simp [mass,count]
rw [e,value]
push_cast; ring
| case4 r b il ir =>
let c := cash R (r+1) (b+1)
let wa := mass r (b+1)
let wb := mass (r+1) b
let w := mass (r+1) (b+1)
have wa0 : 0≤wa := mass_positive _ _
have wb0 : 0≤wb := mass_positive _ _
have w0 : 0≤w := mass_positive _ _
have addw : w=wa+wb := split_mass _ _
have left (j) : (best R (deck r (b+1)) (.finite j) : ℚ)=affine c wa (1+value j r (b+1)) := by
rw [il (by omega) j,red_cash h]; unfold affine; dsimp only [wa,c]; ring
have right (j) : (best R (deck (r+1) b) (.finite j) : ℚ)=affine c wb (value j (r+1) b-1) := by
rw [ir h j,black_cash h]; unfold affine; dsimp only [wb,c]; ring
have stop : c*(wa+wb) = affine c w 0 := by rw [addw]; simp [affine]
have redmax (j) : max (c*wa) (affine c wa (1+value j r (b+1))) =
affine c wa (1+value j r (b+1)) := by
apply max_eq_right; unfold affine
apply mul_le_mul_of_nonneg_right _ wa0
linarith [value_nonneg j r (b+1)]
have blackmax (j) : max (c*wb) (affine c wb (value j (r+1) b-1)) =
affine c wb (max 0 (value j (r+1) b-1)) := by rw [affine_max _ _ _ _ wb0]; simp [affine]
have mixEq (x y : ℚ) : affine c wa x+affine c wb y=affine c w (mix (r+1) (b+1) x y) :=
(affine_mix r b c x y).symm
change _ = affine c w _
rw [deck.eq_4,best]
cases m with
| zero =>
simp only [offer,Nat.cast_max,Nat.cast_add,Nat.cast_mul,left,right]
change max (c*(wa+wb)) (_+_) = _
rw [stop,mixEq,←affine_max _ _ _ _ w0,value]
| succ m =>
simp only [offer,informed,Nat.cast_max,Nat.cast_add,Nat.cast_mul,left,right]
change max (max (c*(wa+wb)) (_+_)) (max (c*wa) _+max (c*wb) _) = _
rw [stop,mixEq,redmax,blackmax,mixEq,←affine_max _ _ _ _ w0,←affine_max _ _ _ _ w0,value]
/-- Uniform-deal totals for optimal legal policies equal the rational
extra-gain recurrence times the total number of deals, with current cash added. -/
theorem strategy_value (R r b m : ℕ) (h : r≤R) :
(best R (deck r b) (.finite m) : ℚ) =
((R:ℚ)-r+b+value m r b)*(weight (deck r b) : ℚ) := by
rw [models h m,affine,cash_formula h]; rfl
/-- One blind stopping decision followed by a single terminal red run has
exactly the value of arbitrary adaptive, possibly interrupted voucher use. -/
theorem strategy_single (R r b m : ℕ) (h : r≤R) :
(best R (deck r b) (.finite m) : ℚ) =
((R:ℚ)-r+b+single m r b)*(weight (deck r b) : ℚ) := by
rw [strategy_value R r b m h,value_eq_single]
#print axioms strategy_single
#print axioms strategy_value
end Problem14.Vouchers.Bridge
~~~
#### `further/formal/VoucherCertificate.lean`
~~~lean
import Lean
import VoucherTable
/-! Candidate rows come from compiled evaluation. Only their integer literals
enter the proof. The kernel checks each cell's Bellman equation independently;
no native_decide or assumption of evaluator correctness is needed. -/
namespace Problem14.Vouchers
open Lean Meta Elab Term
elab "voucher_snapshot " r:num : term => do
let a := gridTable 26 21 26 r.getNat
let entries := a.toList.map fun e =>
mkApp3 (mkConst ``Entry.mk) (toExpr e.ways) (toExpr e.values) (toExpr e.rolling)
mkArrayLit (mkConst ``Entry) entries
set_option Elab.async false
set_option maxRecDepth 100000
set_option maxHeartbeats 0
private def row00 : Array Entry := voucher_snapshot 0
private theorem checked00 : gridTable 26 21 26 0 = row00 := check_first (by decide +kernel)
macro "voucher_step " target:ident checked:ident prior:ident r:num : command =>
`(section
private def $target : Array Entry := voucher_snapshot $r
private theorem $checked : gridTable 26 21 26 $r = $target :=
check_next $prior (by decide +kernel)
end)
voucher_step row01 checked01 checked00 1
voucher_step row02 checked02 checked01 2
voucher_step row03 checked03 checked02 3
voucher_step row04 checked04 checked03 4
voucher_step row05 checked05 checked04 5
voucher_step row06 checked06 checked05 6
voucher_step row07 checked07 checked06 7
voucher_step row08 checked08 checked07 8
voucher_step row09 checked09 checked08 9
voucher_step row10 checked10 checked09 10
voucher_step row11 checked11 checked10 11
voucher_step row12 checked12 checked11 12
voucher_step row13 checked13 checked12 13
voucher_step row14 checked14 checked13 14
voucher_step row15 checked15 checked14 15
voucher_step row16 checked16 checked15 16
voucher_step row17 checked17 checked16 17
voucher_step row18 checked18 checked17 18
voucher_step row19 checked19 checked18 19
voucher_step row20 checked20 checked19 20
voucher_step row21 checked21 checked20 21
voucher_step row22 checked22 checked21 22
voucher_step row23 checked23 checked22 23
voucher_step row24 checked24 checked23 24
voucher_step row25 checked25 checked24 25
voucher_step row26 checked26 checked25 26
def finalCheckpoint : Array Entry := row26
theorem certified_table : gridTable 26 21 26 26 = finalCheckpoint := checked26
#print axioms certified_table
end Problem14.Vouchers
~~~
#### `further/formal/VoucherPremium.lean`
~~~lean
import VoucherBridge
/-! The premium for m adaptive one-card peeks is at most 1-2⁻ᵐ dollars,
uniformly in the numbers of cards remaining. -/
namespace Problem14.TerminalStreak
def premiumCap (m : ℕ) : ℚ := 1-(1/2:ℚ)^m
private theorem cap_nonneg (m : ℕ) : 0≤premiumCap m := by
exact sub_nonneg.mpr (pow_le_one₀ (by norm_num) (by norm_num))
private theorem mix_translate (r b : Nat) (h : 0
rw [bonus]
exact div_nonneg (by positivity) (by positivity)
| succ m ih =>
cases r with
| zero => simp [bonus]
| succ r =>
rw [bonus]
apply le_trans (mul_le_mul_of_nonneg_left (add_le_add_left (ih r) 1)
(div_nonneg (by positivity) (by positivity)))
apply le_of_eq
push_cast
have d1 : (r:ℚ)+1+b≠0 := by positivity
have d2 : (b:ℚ)+1≠0 := by positivity
field_simp
ring
/-- With at most as many red cards as black, a fair coin dominates the run. -/
theorem bonus_le_cap (m r b : Nat) (h : r≤b) : bonus m r b ≤ premiumCap m := by
induction m generalizing r with
| zero => simp [bonus,premiumCap]
| succ m ih =>
cases r with
| zero => simpa [bonus] using cap_nonneg (m+1)
| succ r =>
have h' : (r:ℚ)+1≤b := by exact_mod_cast h
have p : ((r:ℚ)+1)/((r:ℚ)+1+b) ≤ 1/2 := by
apply (div_le_iff₀ (by positivity)).mpr
linarith
rw [bonus]
apply le_trans (mul_le_mul_of_nonneg_left (add_le_add_left (ih r (by omega)) 1)
(div_nonneg (by positivity) (by positivity)))
apply le_trans (mul_le_mul_of_nonneg_right p (by linarith [cap_nonneg m]))
unfold premiumCap
rw [pow_succ]
linarith
/-- Drawing every card locks in r-b dollars of future gain. -/
private theorem floor_zero (r b : Nat) : (r:ℚ)-b ≤ single 0 r b := by
induction r generalizing b with
| zero => simp [single_zero]
| succ r ir =>
induction b with
| zero => simp [single_axis]
| succ b ib =>
rw [single_step]
apply le_trans _ (le_max_right _ _)
have i := mix_mono (r+1) (b+1) (add_le_add_left (ir (b+1)) 1)
(sub_le_sub_right ib 1)
push_cast at i ⊢
rw [show 1+((r:ℚ)-(b+1))=r+1-(b+1) by ring,
show (r:ℚ)+1-b-1 = r+1-(b+1) by ring,mix_const _ _ (by omega)] at i
exact i
/-- The uniform finite-deck bound for m optional, adaptively timed vouchers. -/
theorem voucher_premium_le (m r b : Nat) :
value m r b - value 0 r b ≤ 1-(1/2:ℚ)^m := by
rw [value_eq_single,value_eq_single,sub_le_iff_le_add]
change single m r b ≤ premiumCap m + single 0 r b
rw [add_comm]
induction r generalizing b with
| zero => simp [single_zero,cap_nonneg]
| succ r ir =>
induction b with
| zero => simp [single_axis,cap_nonneg]
| succ b ib =>
rw [single_step m]
apply max_le
· by_cases h : r+1≤b+1
· linarith [bonus_le_cap m (r+1) (b+1) h,single_nonneg 0 (r+1) (b+1)]
· have hh : (b:ℚ)+1+1≤r+1 := by exact_mod_cast (show b+1+1≤r+1 by omega)
have g := bonus_le_full_run m (r+1) (b+1)
have fl := floor_zero (r+1) (b+1)
push_cast at g fl
have den : 0<(b:ℚ)+1+1 := by positivity
have dom : ((r:ℚ)+1)/((b:ℚ)+1+1)≤r+1-(b+1) := by
apply (div_le_iff₀ den).mpr
nlinarith only [mul_nonneg (show 0≤(b:ℚ)+1 by positivity) (sub_nonneg.mpr hh)]
linarith [cap_nonneg m]
· have i := mix_mono (r+1) (b+1) (add_le_add_left (ir (b+1)) 1) (sub_le_sub_right ib 1)
rw [show 1+(single 0 r (b+1)+premiumCap m)=1+single 0 r (b+1)+premiumCap m by ring,
show single 0 (r+1) b+premiumCap m-1=single 0 (r+1) b-1+premiumCap m by ring,
mix_translate _ _ (by omega)] at i
apply le_trans i
apply add_le_add_right
rw [single_step]
exact le_max_right _ _
#print axioms voucher_premium_le
end Problem14.TerminalStreak
namespace Problem14.Vouchers.Bridge
/-- Every legal strategy earns at most the blind optimum plus the cap, in
aggregate units summing over all color orders of the remaining deck. -/
theorem strategy_premium_le {R r b m amount : Nat} (h : r ≤ R)
(policy : Attains R (.finite m) (deck r b) amount) :
(amount:ℚ) - best R (deck r b) (.finite 0) ≤
(1-(1/2:ℚ)^m) * weight (deck r b) := by
have bound : (amount:ℚ) ≤ best R (deck r b) (.finite m) := by exact_mod_cast bounds policy
rw [strategy_value R r b m h] at bound
rw [strategy_value R r b 0 h]
have cap := mul_le_mul_of_nonneg_right (TerminalStreak.voucher_premium_le m r b)
(show 0≤(weight (deck r b):ℚ) by positivity)
linarith only [bound,cap]
#print axioms strategy_premium_le
end Problem14.Vouchers.Bridge
~~~
#### `further/formal/VoucherTable.lean`
~~~lean
import Vouchers
/-! A polynomial-size dynamic program for the strategy semantics of Vouchers.
The final certificates use Lean kernel reduction on a 27×27 grid. -/
namespace Problem14.Vouchers
structure Entry where
ways : Nat
values : Array Nat
rolling : Nat
deriving Inhabited, Repr, DecidableEq
def read (e : Entry) : Supply → Nat
| .finite j => e.values[j]!
| .permanent => e.rolling
def pack (K w : Nat) (f : Supply → Nat) : Entry :=
⟨w, Array.ofFn fun j : Fin (K+1) => f (.finite j), f .permanent⟩
def Fits (K : Nat) : Supply → Prop
| .finite j => j≤K
| .permanent => True
private theorem read_pack {K w : Nat} (f : Supply → Nat) {j : Supply} (h : Fits K j) :
read (pack K w f) j = f j := by
cases j with
| permanent => rfl
| finite j =>
change j≤K at h
simp only [read,pack]
rw [getElem!_pos,Array.getElem_ofFn]
simp; omega
private theorem pack_congr {K w : Nat} {f g : Supply → Nat}
(eq : ∀ j, Fits K j → f j=g j) : pack K w f=pack K w g := by
have slots : (fun i : Fin (K+1) => f (.finite i)) = fun i : Fin (K+1) => g (.finite i) :=
funext fun i => eq _ (show (i:Nat)≤K from Nat.le_of_lt_succ i.isLt)
simp only [pack,slots,eq .permanent trivial]
def summary (R K : Nat) (t : Tree) := pack K (weight t) (best R t)
def absent (K : Nat) := pack K 0 (fun _ => 0)
def terminal (R K : Nat) := pack K 1 (fun _ => R)
def joint (K c : Nat) (l r : Entry) :=
pack K (l.ways+r.ways) (offer c l.ways r.ways (read l) (read r))
private theorem summary_empty (R K : Nat) : summary R K .empty = absent K := rfl
private theorem summary_leaf (R K : Nat) : summary R K .leaf = terminal R K := rfl
private theorem summary_branch (R K : Nat) (s : State) (l r : Tree) :
summary R K (.branch s l r) = joint K (reward R s) (summary R K l) (summary R K r) := by
have w : weight (.branch s l r) = weight l+weight r := by simp [weight,paths]
unfold summary joint
rw [w]
apply pack_congr
intro j hj
have lr {i} (h : Fits K i) := read_pack (w:=weight l) (best R l) h
have rr {i} (h : Fits K i) := read_pack (w:=weight r) (best R r) h
cases j with
| permanent => simp only [best,offer,pack,read]
| finite j =>
cases j with
| zero => simp only [best,offer,lr hj,rr hj]; rfl
| succ j =>
have pred : Fits K (.finite j) := by change j≤K; change j+1≤K at hj; omega
simp only [best,offer,lr hj,rr hj,lr pred,rr pred]; rfl
/-- A row left-to-right. Both the red child from the preceding row and the
black child from the current row are available when a cell is filled. -/
def row (seed : Entry) (step : Nat → Entry → Entry) : Nat → Array Entry
| 0 => #[seed]
| j+1 => let a := row seed step j; a.push (step j a[j]!)
private theorem row_size (s : Entry) (f : Nat → Entry → Entry) (n : Nat) :
(row s f n).size=n+1 := by
induction n with
| zero => rfl
| succ n ih => simp [row,ih]
private theorem lookup_row (f : Nat → Entry) (s : Entry) (g : Nat → Entry → Entry)
(n : Nat) (base : s=f 0) (step : ∀ j
have z : i=0 := by omega
simpa [z,row] using base
| succ n ih =>
let a := row s g n
have ha : a.size=n+1 := row_size _ _ _
have prev (j : Nat) (hj : j≤n) : a[j]! = f j := ih (fun l hl => step l (by omega)) hj
change (a.push (g n a[n]!))[i]! = f i
have inside : i<(a.push (g n a[n]!)).size := by simp [ha]; omega
rw [getElem!_pos (a.push (g n a[n]!)) i inside,Array.getElem_push]
split
· rename_i left
simpa [getElem!_pos a i left] using prev i (by omega)
· have e : i=n+1 := by omega
subst i
rw [prev n (by omega)]
exact step n (by omega)
def gridTable (R K B : Nat) : Nat → Array Entry
| 0 => row (terminal R K) (fun b left => joint K (reward R (0,b+1)) (absent K) left) B
| r+1 =>
let prev := gridTable R K B r
row (joint K (reward R (r+1,0)) prev[0]! (absent K))
(fun b left => joint K (reward R (r+1,b+1)) prev[b+1]! left) B
theorem tabulates (R K B r b : Nat) (hb : b≤B) :
(gridTable R K B r)[b]! = summary R K (deck r b) := by
induction r generalizing b with
| zero =>
unfold gridTable
apply lookup_row _ _ _ _ (by rw [deck.eq_1,summary_leaf]) _ hb
intro j _
rw [deck.eq_3,summary_branch,summary_empty]
| succ r ih =>
unfold gridTable
apply lookup_row _ _ _ _ _ _ hb
· rw [ih 0 (by omega),deck.eq_2,summary_branch,summary_empty]
· intro j hj
rw [ih (j+1) (by omega),deck.eq_4,summary_branch]
/-- A literal checkpoint row can be verified by its size, its first cell, and
one independent two-child comparison per successive cell. -/
def checks (s : Entry) (g : Nat → Entry → Entry) (n : Nat) (a : Array Entry) : Bool :=
decide (a.size=n+1) && decide (a[0]! = s) &&
(List.range n).all fun j => decide (a[j+1]! = g j a[j]!)
private def checked_row (s : Entry) (g : Nat → Entry → Entry) (n : Nat) (a : Array Entry)
(ok : checks s g n a = true) : row s g n=a := by
simp only [checks,Bool.and_eq_true,decide_eq_true_eq,List.all_eq_true] at ok
obtain ⟨⟨sz,z⟩,next⟩ := ok
apply Array.ext ((row_size s g n).trans sz.symm)
intro i hi ha
have got := lookup_row (fun j => a[j]!) s g n z.symm
(fun j hj => (next j (List.mem_range.mpr hj)).symm) (i:=i) (by omega)
simpa [getElem!_pos a i ha,getElem!_pos (row s g n) i hi] using got
def firstChecks (R K B : Nat) :=
checks (terminal R K) (fun b left => joint K (reward R (0,b+1)) (absent K) left) B
def successorChecks (R K B r : Nat) (prev : Array Entry) :=
checks (joint K (reward R (r+1,0)) prev[0]! (absent K))
(fun b left => joint K (reward R (r+1,b+1)) prev[b+1]! left) B
theorem check_first {R K B : Nat} {a : Array Entry} (ok : firstChecks R K B a=true) :
gridTable R K B 0=a := checked_row _ _ _ _ ok
theorem check_next {R K B r : Nat} {a prev : Array Entry}
(prior : gridTable R K B r=prev) (ok : successorChecks R K B r prev a=true) :
gridTable R K B (r+1)=a := by
rw [gridTable,prior]
exact checked_row _ _ _ _ ok
end Problem14.Vouchers
~~~
#### `further/formal/Vouchers.lean`
~~~lean
import Problem14
/-! One voucher reveals just the next card at a time chosen by the player.
After seeing it the player stops before that card or draws it and continues
with one fewer voucher. With a permanent preview the option renews at every
draw. Scores are shifted totals over complete color words, in the same units
as Problem14.bellman. -/
namespace Problem14.Vouchers
inductive Supply where
| finite (n : Nat)
| permanent
deriving Repr, DecidableEq
inductive Spend : Supply → Supply → Prop
| one (k : Nat) : Spend (.finite (k+1)) (.finite k)
| permanent : Spend .permanent .permanent
/-- `draw` selects the continuation sum; otherwise take the current cash sum
on all paths consistent with the observed next card. -/
def response (draw : Bool) (cash continuation : Nat) := if draw then continuation else cash
/-- Legal total payoffs. Each child may contain its own entire policy, so these
constructors allow policies depending on the full observed history. -/
inductive Attains (R : Nat) : Supply → Tree → Nat → Prop
| empty (k) : Attains R k .empty 0
| leaf (k) : Attains R k .leaf R
| stop (k s l r) : Attains R k (.branch s l r) (reward R s*(weight l+weight r))
| draw {k l r a b} (s) : Attains R k l a → Attains R k r b →
Attains R k (.branch s l r) (a+b)
| peek {k j l r a b} (s) (dr db : Bool) : Spend k j → Attains R j l a → Attains R j r b →
Attains R k (.branch s l r)
(response dr (reward R s*weight l) a + response db (reward R s*weight r) b)
def informed (cash wl wr a b : Nat) := max (cash*wl) a + max (cash*wr) b
def offer (cash wl wr : Nat) (l r : Supply → Nat) (k : Supply) :=
let blind := max (cash*(wl+wr)) (l k+r k)
match k with
| .finite 0 => blind
| .finite (j+1) => max blind (informed cash wl wr (l (.finite j)) (r (.finite j)))
| .permanent => max blind (informed cash wl wr (l .permanent) (r .permanent))
def best (R : Nat) : Tree → Supply → Nat
| .empty => fun _ => 0
| .leaf => fun _ => R
| .branch s l r => offer (reward R s) (weight l) (weight r) (best R l) (best R r)
/-- A free renewable preview dominates the blind action at each node. Thus
permanent preview is exactly seeing the next card before every decision. -/
theorem permanent_rolling (R : Nat) (s : State) (l r : Tree) :
best R (.branch s l r) .permanent =
informed (reward R s) (weight l) (weight r) (best R l .permanent) (best R r .permanent) := by
apply Nat.max_eq_right
apply Nat.max_le.mpr
constructor
· rw [Nat.mul_add]
exact Nat.add_le_add (Nat.le_max_left _ _) (Nat.le_max_left _ _)
· exact Nat.add_le_add (Nat.le_max_right _ _) (Nat.le_max_right _ _)
private theorem blind_le (c wl wr : Nat) (l r : Supply → Nat) (k : Supply) :
max (c*(wl+wr)) (l k+r k) ≤ offer c wl wr l r k := by
cases k with
| finite j => cases j <;> simp only [offer] <;> omega
| permanent => exact Nat.le_max_left _ _
private theorem informed_le {k j : Supply} (p : Spend k j) (c wl wr : Nat) (l r : Supply → Nat) :
informed c wl wr (l j) (r j) ≤ offer c wl wr l r k := by
cases p <;> exact Nat.le_max_right _ _
private theorem response_le (draw : Bool) (x a b : Nat) (h : a≤b) :
response draw x a ≤ max x b := by cases draw <;> simp [response] <;> omega
theorem bounds {R k t v} (a : Attains R k t v) : v≤best R t k := by
induction a with
| empty | leaf => exact Nat.le_refl _
| stop k s l r => exact Nat.le_trans (Nat.le_max_left _ _) (blind_le _ _ _ _ _ _)
| draw s al ar il ir =>
exact Nat.le_trans (Nat.le_trans (Nat.add_le_add il ir) (Nat.le_max_right _ _)) (blind_le _ _ _ _ _ _)
| peek s dr db p al ar il ir =>
exact Nat.le_trans (Nat.add_le_add (response_le dr _ _ _ il) (response_le db _ _ _ ir))
(informed_le p _ _ _ _ _)
private theorem at_max {P : Nat → Prop} {x y : Nat} (hx : P x) (hy : P y) : P (max x y) := by
cases Nat.le_total x y with
| inl h => rwa [Nat.max_eq_right h]
| inr h => rwa [Nat.max_eq_left h]
private theorem choose_response (c a : Nat) : response (decide (c≤a)) c a = max c a := by
by_cases h : c≤a
· simp [response,h,Nat.max_eq_right h]
· simp [response,h,Nat.max_eq_left (by omega : a≤c)]
theorem attainable (R : Nat) (t : Tree) (k : Supply) : Attains R k t (best R t k) := by
induction t generalizing k with
| empty => exact .empty k
| leaf => exact .leaf k
| branch s l r il ir =>
let c := reward R s
have blind (j) : Attains R j (.branch s l r)
(max (c*(weight l+weight r)) (best R l j+best R r j)) :=
at_max (.stop j s l r) (.draw s (il j) (ir j))
have seen {m j} (p : Spend m j) : Attains R m (.branch s l r)
(informed c (weight l) (weight r) (best R l j) (best R r j)) := by
simpa only [informed,choose_response,c] using Attains.peek s
(decide (c*weight l ≤ best R l j)) (decide (c*weight r ≤ best R r j)) p (il j) (ir j)
cases k with
| finite j =>
cases j with
| zero => exact blind _
| succ j => exact at_max (blind _) (seen (.one j))
| permanent => exact at_max (blind _) (seen .permanent)
theorem zero_eq_bellman (R : Nat) (t : Tree) : best R t (.finite 0) = bellman R t := by
induction t with
| empty | leaf => rfl
| branch s l r il ir => simp [best,offer,bellman,il,ir]
def bump : Supply → Supply
| .finite j => .finite (j+1)
| .permanent => .permanent
theorem extra_voucher {R k t v} (a : Attains R k t v) : Attains R (bump k) t v := by
induction a with
| empty => exact .empty _
| leaf => exact .leaf _
| stop => exact .stop _ _ _ _
| draw s _ _ il ir => exact .draw s il ir
| peek s dr db p _ _ il ir => cases p <;> exact .peek s dr db (by constructor) il ir
theorem monotone (R : Nat) (t : Tree) {i j : Nat} (h : i≤j) :
best R t (.finite i) ≤ best R t (.finite j) := by
induction j with
| zero => have z : i=0 := by omega
simp [z]
| succ j ih =>
by_cases e : i=j+1
· simp [e]
· exact Nat.le_trans (ih (by omega)) (bounds (extra_voucher (attainable R t (.finite j))))
theorem unlimited {R k t v} (a : Attains R k t v) : Attains R .permanent t v := by
induction a with
| empty => exact .empty _
| leaf => exact .leaf _
| stop => exact .stop _ _ _ _
| draw s _ _ il ir => exact .draw s il ir
| peek s dr db _ _ _ il ir => exact .peek s dr db .permanent il ir
theorem permanent_bound (R : Nat) (t : Tree) (k : Nat) :
best R t (.finite k) ≤ best R t .permanent := bounds (unlimited (attainable R t (.finite k)))
def turns : Tree → Nat
| .empty | .leaf => 0
| .branch _ l r => 1+max (turns l) (turns r)
/-- On an arbitrary finite game tree, one voucher per remaining possible draw
can reproduce every permanent-preview strategy, with its exact payoff. -/
theorem simulate {R j t v} (a : Attains R j t v) (k : Nat) (h : turns t≤k) :
Attains R (.finite k) t v := by
induction a generalizing k with
| empty => exact .empty _
| leaf => exact .leaf _
| stop => exact .stop _ _ _ _
| draw s _ _ il ir =>
simp only [turns] at h
exact .draw s (il k (by omega)) (ir k (by omega))
| peek s dr db _ _ _ il ir =>
simp only [turns] at h
cases k with
| zero => omega
| succ k => exact .peek s dr db (.one k) (il k (by omega)) (ir k (by omega))
theorem saturation_by_horizon (R : Nat) (t : Tree) (k : Nat) (h : turns t≤k) :
best R t (.finite k) = best R t .permanent :=
Nat.le_antisymm (permanent_bound R t k) (bounds (simulate (attainable R t .permanent) k h))
end Problem14.Vouchers
~~~
#### `further/formal/Vouchers52.lean`
~~~lean
import VoucherCertificate
namespace Problem14.Vouchers
/-- Unshifted dollar totals over all 495918532948104 possible color words,
ordered by the number of vouchers, from 0 to 21. -/
def knownTotals : Array Nat := #[
1301526064015237, 1442704104853214, 1496629635267635, 1515795193495168,
1522513009018399, 1524780218992386, 1525528320569688, 1525760971029252,
1525829679817807, 1525848942584349, 1525854058233279, 1525855338140142,
1525855637290774, 1525855702070022, 1525855714977408, 1525855717315452,
1525855717692444, 1525855717744804, 1525855717750788, 1525855717751316,
1525855717751348, 1525855717751349]
def deals52 : Nat := 495918532948104
private def knownEntry : Entry :=
⟨deals52, knownTotals.map (· + 26*deals52), 1525855717751349+26*deals52⟩
private theorem numerals : (gridTable 26 21 26 26)[26]! = knownEntry := by
rw [certified_table]
decide +kernel
private theorem correctEntry : summary 26 21 (deck 26 26) = knownEntry :=
(tabulates 26 21 26 26 26 (by decide)).symm.trans numerals
private theorem summary_value (R K : Nat) (t : Tree) {j : Supply} (ok : Fits K j) :
read (summary R K t) j = best R t j := by
cases j with
| permanent => rfl
| finite k =>
change k≤K at ok
simp only [summary,read,pack]
rw [getElem!_pos,Array.getElem_ofFn]
simp; omega
private theorem standard_read {j : Supply} (ok : Fits 21 j) :
best 26 (deck 26 26) j = read knownEntry j := by
rw [←summary_value 26 21 _ ok,correctEntry]
theorem standard_deals : weight (deck 26 26) = deals52 :=
congrArg Entry.ways correctEntry
/-- Divide this unshifted numerator by deals52 for the expected payoff in dollars. -/
def total52 (s : Supply) := best 26 (deck 26 26) s - 26*weight (deck 26 26)
theorem standard_total {k : Nat} (ok : k≤21) : total52 (.finite k) = knownTotals[k]! := by
rw [total52,standard_deals,standard_read (j:=.finite k) ok]
change (knownTotals.map (· + 26*deals52))[k]! - 26*deals52 = knownTotals[k]!
have h : k
#### `further/machine/PocketBytes.lean`
~~~lean
import SquareRule
/-! Closed instruction fragment for the 8-byte AMD64 System V entry. RDX
points at the table, RSI is a valid 64-bit red count, and only the returned
AL is observed. A normal RET and accessible memory are assumed. -/
namespace Problem14.PocketBytes
open SquareRule
def table : List Nat := [1,2,2,2,3,3,3,3,4,4,4,4,4,5,5,5,5,5,5,6,6,6,6,6,6,6,7]
def bytes : List Nat := [0x40,0x3a,0x3c,0x32,0x0f,0x9d,0xc0,0xc3]
def advisedBytes : List Nat := [0x39,0xf7,0x0f,0x94,0xc0,0xc3]
structure Cpu where
dil : BitVec 8
rsi : Nat
edi : BitVec 32 := 0
esi : BitVec 32 := 0
zf : Bool := false
sf : Bool := false
ofl : Bool := false
al : Nat := 0
/-- CMP sets the sign and signed subtraction overflow flags. SETGE tests SF=OF. -/
def run (code : List Nat) (s : Cpu) : Option Nat := do
match code with
| 0x40::0x3a::0x3c::0x32::tail =>
let v ← table[s.rsi]?
let rhs : BitVec 8 := BitVec.ofNat 8 v
let sf := (s.dil-rhs).msb
let ofl := (s.dil.msb != rhs.msb) && (sf != s.dil.msb)
run tail {s with sf, ofl}
| 0x0f::0x9d::0xc0::tail =>
run tail {s with al := (s.sf == s.ofl).toNat}
| 0x39::0xf7::tail => run tail {s with zf := s.edi == s.esi}
| 0x0f::0x94::0xc0::tail => run tail {s with al := s.zf.toNat}
| [0xc3] => some s.al
| _ => none
def result (r b : Nat) :=
run bytes { dil := BitVec.ofNat 8 b - BitVec.ofNat 8 r, rsi := r }
private theorem all_ok :
((List.range 27).all fun r => (List.range 27).all fun b =>
decide (result r b = some ((stop (r,b)).toNat))) = true := by decide +kernel
theorem machine_eq_policy (r b : Nat) (hr : r ≤ 26) (hb : b ≤ 26) :
result r b = some ((stop (r,b)).toNat) := by
have ok := List.all_eq_true.mp (List.all_eq_true.mp all_ok r
(List.mem_range.mpr (by omega))) b (List.mem_range.mpr (by omega))
exact of_decide_eq_true ok
/-- The six-byte advised entry returns equality for any two 32-bit register inputs. -/
theorem advised_eq (x target : BitVec 32) :
run advisedBytes {dil := 0, rsi := 0, edi := x, esi := target}
= some (x == target).toNat := by rfl
end Problem14.PocketBytes
~~~
#### `further/rules/QuadraticReal.lean`
~~~lean
import Mathlib.Data.Real.Basic
import Mathlib.Tactic.Linarith
namespace Problem14.SquareRule
/-- Four required decisions already contradict every quadratic with real
coefficients. The left sides cancel and the right sides sum to -748. -/
theorem four_point_cut_real (a b c : ℝ)
(h₁ : 17≤9*a+3*b+c) (h₂ : 1156*a+34*b+c<1686)
(h₃ : 9646≤6724*a+82*b+c) (h₄ : 11449*a+107*b+c<16379) : False := by
linarith only [h₁, h₂, h₃, h₄]
end Problem14.SquareRule
~~~
#### `further/rules/SquareRule.lean`
~~~lean
import Problem14
/-! The square mnemonic and an obstruction to quadratic playing rules. -/
namespace Problem14.SquareRule
def stop (s : State) : Bool :=
let x := s.2-s.1
decide (s.1 (List.range (B+1)).all fun b =>
decide (action (tab R B) R r b = (tab R B r b).2)
private theorem tab_action (R B r b : Nat) (hb : b≤B) :
action (tab R B) R r b = action (model R) R r b := by
unfold action tab
rw [table_eq _ _ _ _ hb,table_eq _ _ _ _ hb,table_eq _ _ _ _ (by omega : b-1≤B)]
private theorem verified_action {R B : Nat} (ok : verify R B=true)
{r b : Nat} (hr : r≤R) (hb : b≤B) :
action (model R) R r b = bellman R (deck r b) := by
have h := List.all_eq_true.mp (List.all_eq_true.mp ok r
(List.mem_range.mpr (by omega))) b (List.mem_range.mpr (by omega))
have h' : action (tab R B) R r b = (tab R B r b).2 := of_decide_eq_true h
rw [tab_action _ _ _ _ hb] at h'
simpa only [tab, table_eq _ _ _ _ hb, model] using h'
set_option maxRecDepth 200000
set_option maxHeartbeats 0
private theorem checked : verify 31 31=true := by decide +kernel
private theorem policy_attains (R B : Nat) (ok : verify R B=true)
(r b : Nat) (hr : r≤R) (hb : b≤B) :
score R stop (deck r b) = bellman R (deck r b) := by
have choose {u v : Nat} (hu : u≤R) (hv : v≤B) := verified_action ok hu hv
induction r, b using deck.induct with
| case1 => simp [score,deck,paths,firstPay,bellman]
| case2 r ih =>
rw [←choose hr hb,deck.eq_2,score_branch,ih (by omega) hb]
simp [action,model,deck.eq_2,weight,paths,score]
| case3 b ih =>
rw [←choose hr hb,deck.eq_3,score_branch,ih hr (by omega)]
simp [action,model,deck.eq_3,weight,paths,score]
| case4 r b h₁ h₂ =>
rw [←choose hr hb,deck.eq_4,score_branch]
simp [action,model,deck.eq_4,weight,paths,h₁ (by omega) hb,h₂ hr (by omega)]
/-- Every first decision on every deck up to 31 pairs is optimal. -/
theorem exact_action {r b : Nat} (hr : r≤31) (hb : b≤31) :
action (model 31) 31 r b = bellman 31 (deck r b) :=
verified_action checked hr hb
/-- Following the square rule all the way attains the optimal payoff. -/
theorem exact_play {r b : Nat} (hr : r≤31) (hb : b≤31) :
score 31 stop (deck r b) = bellman 31 (deck r b) :=
policy_attains _ _ checked _ _ hr hb
/-- At 32 pairs the policy draws at a strictly profitable stopping state. -/
theorem first_failure :
stop (26,32)=false ∧ action (model 32) 32 26 32 <
reward 32 (26,32)*weight (deck 26 32) := by
constructor
· decide
· change _ < _*(model 32 26 32).1
rw [←tab_action 32 32 26 32 (by decide),←table_eq 32 32 26 32 (by decide)]
decide +kernel
/-- The four strict Bellman decisions prohibit every rational quadratic rule. -/
theorem four_point_cut (a b c d : Int) (hd : 0
#### `further/signals/CappedProduct.lean`
~~~lean
import Mathlib.Tactic.Ring
/-! The uniform product inequality in the capped-peak threshold proof. -/
namespace CappedProduct
/-- The product of a+1 through a+d. -/
def rising (a : Nat) : Nat → Nat
| 0 => 1
| d+1 => rising a d * (a+d+1)
private theorem scaled (m d : Nat) (hd : d ≤ m) :
3^d * rising m d ≤ 2^d * rising (2*m) d := by
induction d with
| zero => simp [rising]
| succ d ih =>
have hf : 3*(m+d+1) ≤ 2*(2*m+d+1) := by omega
calc
3^(d+1) * rising m (d+1) = (3^d * rising m d) * (3*(m+d+1)) := by
rw [pow_succ, rising]; ring
_ ≤ (2^d * rising (2*m) d) * (2*(2*m+d+1)) :=
Nat.mul_le_mul (ih (by omega)) hf
_ = 2^(d+1) * rising (2*m) (d+1) := by rw [pow_succ, rising]; ring
private theorem before_end (m d : Nat) (hd : d+2 ≤ m) :
m * 2^d ≤ (m-d) * 3^d := by
induction d with
| zero => simp
| succ d ih =>
have hf : (m-d)*2 ≤ (m-(d+1))*3 := by omega
calc
m * 2^(d+1) = (m*2^d)*2 := by rw [pow_succ]; ring
_ ≤ ((m-d)*3^d)*2 := Nat.mul_le_mul_right _ (ih (by omega))
_ = ((m-d)*2)*3^d := by ring
_ ≤ ((m-(d+1))*3)*3^d := Nat.mul_le_mul_right _ hf
_ = (m-(d+1))*3^(d+1) := by rw [pow_succ]; ring
private theorem endpoint (k : Nat) : (5+k)*2^(4+k) ≤ 3^(4+k) := by
induction k with
| zero => decide
| succ k ih =>
have hf : (5+(k+1))*2 ≤ (5+k)*3 := by omega
calc
(5+(k+1))*2^(4+(k+1)) = ((5+(k+1))*2)*2^(4+k) := by
rw [show 4+(k+1) = (4+k)+1 by omega, pow_succ]; ring
_ ≤ ((5+k)*3)*2^(4+k) := Nat.mul_le_mul_right _ hf
_ = ((5+k)*2^(4+k))*3 := by ring
_ ≤ 3^(4+k)*3 := Nat.mul_le_mul_right _ ih
_ = 3^(4+(k+1)) := by rw [show 4+(k+1) = (4+k)+1 by omega, pow_succ]
/-- For m ≥ 4 and 0 ≤ d < m, the extremal ratio A_d is at most one.
The denominators have been cleared, so the statement uses exact naturals. -/
theorem capped_product (m d : Nat) (hm : 4 ≤ m) (hd : d < m) :
m * rising m d ≤ (m-d) * rising (2*m) d := by
by_cases small : m=4 ∧ d=3
· obtain ⟨rfl,rfl⟩ := small
decide
have hp : m*2^d ≤ (m-d)*3^d := by
by_cases h : d+2 ≤ m
· exact before_end m d h
· have hm' : m = 5+(m-5) := by omega
have hd' : d = 4+(m-5) := by omega
have he : m-d=1 := by omega
simpa only [←hm', ←hd', he, one_mul] using endpoint (m-5)
have h := calc
(m*rising m d)*3^d = m*(3^d*rising m d) := by ring
_ ≤ m*(2^d*rising (2*m) d) := Nat.mul_le_mul_left _ (scaled m d (by omega))
_ = (m*2^d)*rising (2*m) d := by ring
_ ≤ ((m-d)*3^d)*rising (2*m) d := Nat.mul_le_mul_right _ hp
_ = ((m-d)*rising (2*m) d)*3^d := by ring
exact Nat.le_of_mul_le_mul_right h (Nat.pow_pos (by decide))
end CappedProduct
~~~
#### `further/signals/Nominations.lean`
~~~lean
import PerfectAdvice
/-! A finite menu of stopping policies and a chronological sequence of online
nominations have exactly the same achievable payoffs on every individual path. -/
namespace PerfectAdvice
private def AgreeTo (d e : Path) (t : Nat) := ∀ s ≤ t, d s = e s
private theorem stoppedBy {n} (p : Policy n) {d e t} (h : AgreeTo d e t) :
p.time d ≤ t ↔ p.time e ≤ t := by
constructor
· intro hd
rw [p.online_ d e (fun s hs => h s (hs.trans hd))]
exact hd
· intro he
rw [p.online_ e d (fun s hs => (h s (hs.trans he)).symm)]
exact he
/-- A time is an online policy if whether it has stopped by t is known at t. -/
private def fromEvents {n} (time : Path → Nat) (bound : ∀ d, time d ≤ 2*n)
(events : ∀ d e t, AgreeTo d e t → (time d ≤ t ↔ time e ≤ t)) : Policy n where
time := time
bounded := bound
online_ d e hist := by
have he : time e ≤ time d := (events d e _ hist).mp (le_refl _)
have hd : time d ≤ time e :=
(events d e _ (fun s hs => hist s (hs.trans he))).mpr (le_refl _)
exact le_antisymm he hd
private def earlier {n} (p q : Policy n) : Policy n :=
fromEvents (fun d => min (p.time d) (q.time d))
(fun d => (min_le_left ..).trans (p.bounded d)) (by
intro d e t h
simpa only [min_le_iff] using or_congr (stoppedBy p h) (stoppedBy q h))
private def later {n} (p q : Policy n) : Policy n :=
fromEvents (fun d => max (p.time d) (q.time d))
(fun d => max_le (p.bounded d) (q.bounded d)) (by
intro d e t h
simpa only [max_le_iff] using and_congr (stoppedBy p h) (stoppedBy q h))
/-- Each comparison produces two chronological stopping policies even when the
relative order of its inputs changes across paths. -/
private def insert {n} (p : Policy n) : List (Policy n) → List (Policy n)
| [] => [p]
| q :: qs => earlier p q :: insert (later p q) qs
def chronological {n} : List (Policy n) → List (Policy n)
| [] => []
| p :: ps => insert p (chronological ps)
def times {n} (d : Path) (ps : List (Policy n)) : List Nat := ps.map (fun p => p.time d)
private theorem insert_perm {n} (p : Policy n) (ps : List (Policy n)) (d : Path) :
(times d (insert p ps)).Perm (p.time d :: times d ps) := by
induction ps generalizing p with
| nil => exact List.Perm.refl _
| cons q qs ih =>
change (min (p.time d) (q.time d) :: times d (insert (later p q) qs)).Perm
(p.time d :: q.time d :: times d qs)
have h := ih (later p q)
change (times d (insert (later p q) qs)).Perm (max (p.time d) (q.time d) :: times d qs) at h
by_cases hp : p.time d ≤ q.time d
· rw [min_eq_left hp]
rw [max_eq_right hp] at h
exact h.cons _
· have hq := le_of_not_ge hp
rw [min_eq_right hq]
rw [max_eq_left hq] at h
exact (h.cons _).trans (List.Perm.swap _ _ _)
private theorem insert_ordered {n} (p : Policy n) (ps : List (Policy n)) (d : Path)
(hs : (times d ps).Pairwise (· ≤ ·)) : (times d (insert p ps)).Pairwise (· ≤ ·) := by
induction ps generalizing p with
| nil => simp [insert, times]
| cons q qs ih =>
change (q.time d :: times d qs).Pairwise (· ≤ ·) at hs
change (min (p.time d) (q.time d) :: times d (insert (later p q) qs)).Pairwise (· ≤ ·)
obtain ⟨hq, hqs⟩ := List.pairwise_cons.mp hs
refine List.pairwise_cons.mpr ⟨?_, ih _ hqs⟩
intro t ht
rcases List.mem_cons.mp ((insert_perm (later p q) qs d).mem_iff.mp ht) with h|h
· change t = max (p.time d) (q.time d) at h
omega
· exact (min_le_right ..).trans (hq t h)
/-- Sorting preserves the entire multiset of exercise times path by path. -/
theorem chronological_perm {n} (ps : List (Policy n)) (d : Path) :
(times d (chronological ps)).Perm (times d ps) := by
induction ps with
| nil => exact List.Perm.refl _
| cons p ps ih => exact (insert_perm p (chronological ps) d).trans (ih.cons _)
theorem chronological_ordered {n} (ps : List (Policy n)) (d : Path) :
(times d (chronological ps)).Pairwise (· ≤ ·) := by
induction ps with
| nil => simp [chronological, times]
| cons p ps ih => exact insert_ordered p (chronological ps) d ih
theorem chronological_length {n} (ps : List (Policy n)) :
(chronological ps).length = ps.length := by
simpa [times] using (chronological_perm ps (fun _ => 0)).length_eq
/-- The reward can depend arbitrarily on the full path and the exercise time.
Ties and repeated stopping times are retained with multiplicity. -/
theorem chronological_payoffs {n} {α : Type*} (ps : List (Policy n)) (pay : Path → Nat → α)
(d : Path) :
((chronological ps).map fun p => pay d (p.time d)).Perm
(ps.map fun p => pay d (p.time d)) := by
simpa [times, Function.comp_def] using (chronological_perm ps d).map (pay d)
/-- An oracle announces one policy from a menu of exactly m labels.
For each deck it must select a realized payout satisfying the given predicate. -/
def AdviceCan (n m : Nat) (goal : Path → Int → Prop) : Prop :=
∃ ps : List (Policy n), ps.length = m ∧ ∀ d, Balanced n d →
∃ p ∈ ps, goal d (d (p.time d))
/-- The existential payoff condition is exactly an actual pre-game encoder into
m labels together with m online decoding policies. -/
theorem advice_iff_encoder {n m} (goal : Path → Int → Prop) :
AdviceCan n m goal ↔
∃ (decode : Fin m → Policy n) (encode : {d // Balanced n d} → Fin m),
∀ d : {d // Balanced n d}, goal d.val (d.val ((decode (encode d)).time d.val)) := by
constructor
· rintro ⟨ps, rfl, hgoal⟩
have possible (d : {d // Balanced n d}) :
∃ i : Fin ps.length, goal d.val (d.val ((ps.get i).time d.val)) := by
obtain ⟨p, hp, h⟩ := hgoal d.val d.property
obtain ⟨i, rfl⟩ := List.get_of_mem hp
exact ⟨i,h⟩
choose encode hencode using possible
exact ⟨ps.get, encode, hencode⟩
· rintro ⟨decode, encode, hgoal⟩
refine ⟨List.ofFn decode, by simp, ?_⟩
intro d hd
let path : {d // Balanced n d} := ⟨d,hd⟩
exact ⟨decode (encode path), List.mem_ofFn.mpr ⟨_,rfl⟩, hgoal path⟩
/-- Chronologically numbered online nominations; the adviser may select any
nomination. With a scalar payout the best choice is the highest nomination. -/
def NominationsCan (n m : Nat) (goal : Path → Int → Prop) : Prop :=
∃ ps : List (Policy n), ps.length = m ∧ (∀ d, (times d ps).Pairwise (· ≤ ·)) ∧
∀ d, Balanced n d → ∃ p ∈ ps, goal d (d (p.time d))
theorem advice_iff_nominations {n m} (goal : Path → Int → Prop) :
AdviceCan n m goal ↔ NominationsCan n m goal := by
constructor
· rintro ⟨ps, hlen, hgoal⟩
refine ⟨chronological ps, (chronological_length ps).trans hlen, chronological_ordered ps, ?_⟩
intro d hd
obtain ⟨p, hp, hg⟩ := hgoal d hd
have hm : p.time d ∈ times d ps := List.mem_map.mpr ⟨p, hp, rfl⟩
obtain ⟨q, hq, he⟩ := List.mem_map.mp ((chronological_perm ps d).mem_iff.mpr hm)
exact ⟨q, hq, by simpa only [he] using hg⟩
· rintro ⟨ps, hlen, _, hgoal⟩
exact ⟨ps, hlen, hgoal⟩
end PerfectAdvice
~~~
#### `further/signals/PerfectAdvice.lean`
~~~lean
import Mathlib.Data.Finset.Max
import Mathlib.Data.Fintype.Card
import Mathlib.Data.Nat.Find
/-! The number of advice labels required to stop at the actual maximum
on every balanced red/black deck. Only scores up through expiry are observed. -/
namespace PerfectAdvice
abbrev Path := Nat → Int
structure Balanced (n : Nat) (d : Path) : Prop where
start : d 0 = 0
finish : d (2*n) = 0
step : ∀ t < 2*n, d (t+1) = d t + 1 ∨ d (t+1) = d t - 1
structure Policy (n : Nat) where
time : Path → Nat
bounded : ∀ d, time d ≤ 2*n
online_ : ∀ d e, (∀ t ≤ time d, d t = e t) → time e = time d
/-- One of the announced labels achieves a pathwise maximum on each deck. -/
def Perfect (n m : Nat) : Prop :=
∃ policies : Fin m → Policy n, ∀ d, Balanced n d →
∃ i, ∀ t ≤ 2*n, d t ≤ d ((policies i).time d)
private theorem height_bound {n : Nat} {d : Path} (hd : Balanced n d) :
∀ t ≤ 2*n, d t ≤ (n : Int) := by
have forward : ∀ t ≤ 2*n, d t ≤ (t : Int) := by
intro t
induction t with
| zero => simp [hd.start]
| succ t ih =>
intro ht
have := ih (by omega)
rcases hd.step t (by omega) with h|h <;> omega
have backward : ∀ u ≤ 2*n, d (2*n-u) ≤ (u : Int) := by
intro u
induction u with
| zero => simp [hd.finish]
| succ u ih =>
intro hu
have h := ih (by omega)
have he : 2*n-(u+1)+1 = 2*n-u := by omega
rcases hd.step (2*n-(u+1)) (by omega) with h'|h' <;> rw [he] at h' <;> omega
intro t ht
have h := backward (2*n-t) (by omega)
have he : 2*n-(2*n-t) = t := by omega
rw [he] at h
have := forward t ht
omega
private def Hit (n : Nat) (a : Int) (d : Path) (t : Nat) := t = 2*n ∨ d t = a
private theorem exists_hit (n : Nat) (a : Int) (d : Path) : ∃ t, Hit n a d t :=
⟨2*n, Or.inl rfl⟩
private noncomputable def first (n : Nat) (a : Int) (d : Path) :=
@Nat.find _ (Classical.decPred _) (exists_hit n a d)
private theorem first_hit (n : Nat) (a : Int) (d : Path) : Hit n a d (first n a d) := by
classical
exact Nat.find_spec (exists_hit n a d)
private theorem first_le {n : Nat} {a : Int} {d : Path} {t : Nat} (h : Hit n a d t) :
first n a d ≤ t := by
classical
exact Nat.find_min' (exists_hit n a d) h
private noncomputable def threshold (n : Nat) (a : Int) : Policy n where
time := first n a
bounded _ := first_le (Or.inl rfl)
online_ := by
intro d e agree
have transport (t : Nat) (ht : t ≤ first n a d) : Hit n a d t ↔ Hit n a e t := by
unfold Hit
rw [agree t ht]
have he := first_le ((transport _ (le_refl _)).mp (first_hit n a d))
exact le_antisymm he (first_le ((transport _ he).mpr (first_hit n a e)))
/-- Tell the player which of the levels 1 through n to hit. -/
theorem sufficient {n m : Nat} (hn : 0 < n) (hm : n ≤ m) : Perfect n m := by
refine ⟨fun i => threshold n ((i.val : Int)+1), ?_⟩
intro d hd
obtain ⟨s, hs, hmax⟩ := Finset.exists_max_image (Finset.range (2*n+1)) d ⟨0, by simp⟩
have hmax' (t) (ht : t ≤ 2*n) := hmax t (Finset.mem_range.mpr (by omega : t < 2*n+1))
have hs' := Finset.mem_range.mp hs
have hi := height_bound hd s (by omega)
have hz := hmax' 0 (by omega)
rw [hd.start] at hz
by_cases hp : 0 < d s
· let i : Fin m := ⟨(d s).toNat-1, by omega⟩
have ha : (i.val : Int)+1 = d s := by dsimp [i]; omega
refine ⟨i, ?_⟩
intro t ht
change d t ≤ d (first n ((i.val : Int)+1) d)
rw [ha]
rcases first_hit n (d s) d with hf|hf
· have hle := first_le (n:=n) (d:=d) (Or.inr rfl : Hit n (d s) d s)
have : s = 2*n := by omega
rw [this, hd.finish] at hp
omega
· rw [hf]
exact hmax' t ht
· refine ⟨⟨0, by omega⟩, ?_⟩
intro t ht
change d t ≤ d (first n 1 d)
rcases first_hit n 1 d with hf|hf
· rw [hf, hd.finish]
have := hmax' t ht
omega
· rw [hf]
have := hmax' t ht
omega
/-- Scores of the deck R^j B^n R^(n-j) up through expiry. -/
private def witness (n j : Nat) (t : Nat) : Int :=
if t ≤ j then t else if t ≤ j+n then 2*(j:Int)-t else (t:Int)-2*(n:Int)
private theorem balanced_witness {j n : Nat} (hj : 1 ≤ j) (hjn : j ≤ n) :
Balanced n (witness n j) := by
constructor
· simp [witness]
· unfold witness
split <;> (try split) <;> omega
· intro t ht
unfold witness
split <;> split <;> (try split) <;> (try split) <;> omega
private theorem peak_unique {j n t : Nat} (hj : 1 ≤ j) (ht : t ≤ 2*n)
(h : witness n j j ≤ witness n j t) : t = j := by
simp only [witness, le_refl, if_true] at h
split at h <;> (try split at h) <;> omega
/-- Two witness decks with different initial red runs cannot use one policy. -/
theorem necessary {n m : Nat} (h : Perfect n m) : n ≤ m := by
classical
obtain ⟨p, hp⟩ := h
have good (j : Fin n) := hp (witness n (j.val+1)) (balanced_witness (by omega) (by omega))
choose labels hlabels using good
have at_peak (j : Fin n) : (p (labels j)).time (witness n (j.val+1)) = j.val+1 :=
peak_unique (by omega) ((p _).bounded _) (hlabels j _ (by omega))
have distinct (j k : Fin n) (hjk : j.val < k.val) : labels j ≠ labels k := by
intro eq
have hstop := at_peak j
have hmatch := (p (labels j)).online_ (witness n (j.val+1)) (witness n (k.val+1)) (by
intro t ht
rw [hstop] at ht
simp [witness, ht, show t ≤ k.val+1 by omega])
rw [hstop, eq, at_peak k] at hmatch
omega
have inj : Function.Injective labels := by
intro j k h
apply Fin.ext
rcases lt_trichotomy j.val k.val with hlt|eq|hgt
· exact (distinct j k hlt h).elim
· exact eq
· exact (distinct k j hgt h.symm).elim
simpa using Fintype.card_le_of_injective labels inj
theorem perfect_iff {n m : Nat} (hn : 0 < n) : Perfect n m ↔ n ≤ m :=
⟨necessary, sufficient hn⟩
end PerfectAdvice
~~~
#### `kmod/KernelNewton.lean`
~~~lean
import CompactDebit
/-! Integer arithmetic used by the Problem 14 kernel-module calculator. The
mathematical specification follows the guarded DIVQ and Newton control flow of
the C source. No floating-point initial approximation is required. -/
namespace P14Kernel
open P14Quote
abbrev W : Nat := 2^64
/-- Bitwise average as evaluated on two unsigned words. -/
def average (a b : Nat) := (a &&& b) + (a ^^^ b) / 2
private theorem carry_split (a b : Nat) : 2*(a &&& b) + (a ^^^ b) = a+b := by
by_cases az : a=0
· simp [az]
· have ih := carry_split (a/2) (b/2)
have da : (a &&& b)/2 = (a/2 &&& b/2) := by
simpa [Nat.shiftRight_eq_div_pow] using (@Nat.shiftRight_and_distrib 1 a b)
have dx : (a ^^^ b)/2 = (a/2 ^^^ b/2) := by
simpa [Nat.shiftRight_eq_div_pow] using (@Nat.shiftRight_xor_distrib 1 a b)
have ma := @Nat.and_mod_two_eq_one a b
have mx := @Nat.xor_mod_two_eq_one a b
omega
termination_by a
decreasing_by omega
theorem average_exact (a b : Nat) : average a b = (a+b)/2 := by
have h := carry_split a b
unfold average
omega
theorem average_word {a b : Nat} (ha : a
have same : s=r := by omega
rw [improvements]
split
· omega
· rename_i edge
dsimp only
rw [if_neg (by have := step_above hr (by omega : 0
rw [improvements]
split
· omega
· rename_i edge
dsimp only
split
· rename_i better
have pos : 0 split <;> omega
/-- The two microdollar words written by p14_quote_integer. -/
def quote (n : Nat) : Nat × Nat :=
let r := lowerRoot n
let h := upperCeiling n r
((coefficient*r / 2^32 / 10^12)-P14Compact.algorithm n,
1+((coefficient+1)*h-1)/2^32/10^12)
theorem quote_exact {n : Nat} (low : 32768≤n) (high : n
unfold W <;> omega
#print axioms improvements_word
#print axioms quote_widths
#print axioms lower_correct
#print axioms upper_correct
#print axioms quote_exact
end P14Kernel
~~~
#### `kmod/KernelPrice.lean`
~~~lean
import KernelNewton
import asmproof.GameMachinePrice
/-! The C calculator's integer endpoints enclose the optimal finite-card-game
price for every count in the kernel-module API. The underlying finite game
certificates inherited from GameMachinePrice use native evaluation. -/
namespace P14Kernel
theorem quote_encloses_game {n : ℕ} (hn : 32768≤n) (hu : n
#### `minelf/CheckedMinOutput.lean`
~~~lean
import RenderCompact
import asmproof.GameMachinePrice
namespace P14CheckedOutput
open P14Quote
private theorem halfUp {v : ℝ} (hv : 0≤v) :
let c : ℕ := ⌊100*v+1/2⌋₊
(c:ℝ)-1/2 ≤ 100*v ∧ 100*v ≤ (c:ℝ)+1/2 := by
have h := Nat.floor_le (by positivity : (0:ℝ)≤100*v+1/2)
have h' := Nat.lt_floor_add_one (100*v+1/2)
dsimp only
constructor <;> linarith only [h,h']
def line0 : Record := ⟨133787000, 6038215406, 6038218246, 603822, 603822, true⟩
def hint0 : Witness := ⟨49678310653537, 49678310746368, 2827⟩
theorem verified0 : line0.Check hint0 := by decide
def endpoints0 := @Record.exactEndpoints _ _ verified0
def cents0 := @Record.encloses _ _ verified0
def realPrice0 := @Record.realPrice _ _ verified0
theorem gameDollars0 : (6038215406:ℝ)/10^6 ≤ Problem14.GameComparison.price 133787000 ∧
Problem14.GameComparison.price 133787000 ≤ (6038218246:ℝ)/10^6 := by
have h := P14Entry.printed_game verified0
exact ⟨h.1,h.2.1⟩
def allNearest0 := (P14Entry.printed_game verified0).2.2
theorem roundedCents0 : ⌊100*(Problem14.GameComparison.price 133787000)+1/2⌋₊ = 603822 := by
have lower := gameDollars0.1
have pos : 0 ≤ Problem14.GameComparison.price 133787000 := le_trans (by positivity) lower
obtain ⟨hl,hu⟩ := halfUp pos
have out := allNearest0 _ hl hu
exact out.2 rfl
def line1 : Record := ⟨500000000, 11673115131, 11673117310, 1167312, 1167312, true⟩
def hint1 : Witness := ⟨96038388349944, 96038388397963, 2172⟩
theorem verified1 : line1.Check hint1 := by decide
def endpoints1 := @Record.exactEndpoints _ _ verified1
def cents1 := @Record.encloses _ _ verified1
def realPrice1 := @Record.realPrice _ _ verified1
theorem gameDollars1 : (11673115131:ℝ)/10^6 ≤ Problem14.GameComparison.price 500000000 ∧
Problem14.GameComparison.price 500000000 ≤ (11673117310:ℝ)/10^6 := by
have h := P14Entry.printed_game verified1
exact ⟨h.1,h.2.1⟩
def allNearest1 := (P14Entry.printed_game verified1).2.2
theorem roundedCents1 : ⌊100*(Problem14.GameComparison.price 500000000)+1/2⌋₊ = 1167312 := by
have lower := gameDollars1.1
have pos : 0 ≤ Problem14.GameComparison.price 500000000 := le_trans (by positivity) lower
obtain ⟨hl,hu⟩ := halfUp pos
have out := allNearest1 _ hl hu
exact out.2 rfl
def line2 : Record := ⟨1000000000000, 522037675512, 522037675988, 52203768, 52203768, true⟩
def hint2 : Witness := ⟨4294967296000000, 4294967296001073, 475⟩
theorem verified2 : line2.Check hint2 := by decide
def endpoints2 := @Record.exactEndpoints _ _ verified2
def cents2 := @Record.encloses _ _ verified2
def realPrice2 := @Record.realPrice _ _ verified2
theorem gameDollars2 : (522037675512:ℝ)/10^6 ≤ Problem14.GameComparison.price 1000000000000 ∧
Problem14.GameComparison.price 1000000000000 ≤ (522037675988:ℝ)/10^6 := by
have h := P14Entry.printed_game verified2
exact ⟨h.1,h.2.1⟩
def allNearest2 := (P14Entry.printed_game verified2).2.2
theorem roundedCents2 : ⌊100*(Problem14.GameComparison.price 1000000000000)+1/2⌋₊ = 52203768 := by
have lower := gameDollars2.1
have pos : 0 ≤ Problem14.GameComparison.price 1000000000000 := le_trans (by positivity) lower
obtain ⟨hl,hu⟩ := halfUp pos
have out := allNearest2 _ hl hu
exact out.2 rfl
def line3 : Record := ⟨9223372036854775807, 1585428682979210, 1585428682979231, 158542868298, 158542868298, true⟩
def hint3 : Witness := ⟨13043817825332782211, 13043817825332782211, 20⟩
theorem verified3 : line3.Check hint3 := by decide
def endpoints3 := @Record.exactEndpoints _ _ verified3
def cents3 := @Record.encloses _ _ verified3
def realPrice3 := @Record.realPrice _ _ verified3
theorem gameDollars3 : (1585428682979210:ℝ)/10^6 ≤ Problem14.GameComparison.price 9223372036854775807 ∧
Problem14.GameComparison.price 9223372036854775807 ≤ (1585428682979231:ℝ)/10^6 := by
have h := P14Entry.printed_game verified3
exact ⟨h.1,h.2.1⟩
def allNearest3 := (P14Entry.printed_game verified3).2.2
theorem roundedCents3 : ⌊100*(Problem14.GameComparison.price 9223372036854775807)+1/2⌋₊ = 158542868298 := by
have lower := gameDollars3.1
have pos : 0 ≤ Problem14.GameComparison.price 9223372036854775807 := le_trans (by positivity) lower
obtain ⟨hl,hu⟩ := halfUp pos
have out := allNearest3 _ hl hu
exact out.2 rfl
def line4 : Record := ⟨9223372036854775808, 1585428682979210, 1585428682979231, 158542868298, 158542868298, true⟩
def hint4 : Witness := ⟨13043817825332782212, 13043817825332782212, 20⟩
theorem verified4 : line4.Check hint4 := by decide
def endpoints4 := @Record.exactEndpoints _ _ verified4
def cents4 := @Record.encloses _ _ verified4
def realPrice4 := @Record.realPrice _ _ verified4
theorem gameDollars4 : (1585428682979210:ℝ)/10^6 ≤ Problem14.GameComparison.price 9223372036854775808 ∧
Problem14.GameComparison.price 9223372036854775808 ≤ (1585428682979231:ℝ)/10^6 := by
have h := P14Entry.printed_game verified4
exact ⟨h.1,h.2.1⟩
def allNearest4 := (P14Entry.printed_game verified4).2.2
theorem roundedCents4 : ⌊100*(Problem14.GameComparison.price 9223372036854775808)+1/2⌋₊ = 158542868298 := by
have lower := gameDollars4.1
have pos : 0 ≤ Problem14.GameComparison.price 9223372036854775808 := le_trans (by positivity) lower
obtain ⟨hl,hu⟩ := halfUp pos
have out := allNearest4 _ hl hu
exact out.2 rfl
def line5 : Record := ⟨9223372036854775809, 1585428682979210, 1585428682979231, 158542868298, 158542868298, true⟩
def hint5 : Witness := ⟨13043817825332782213, 13043817825332782213, 20⟩
theorem verified5 : line5.Check hint5 := by decide
def endpoints5 := @Record.exactEndpoints _ _ verified5
def cents5 := @Record.encloses _ _ verified5
def realPrice5 := @Record.realPrice _ _ verified5
theorem gameDollars5 : (1585428682979210:ℝ)/10^6 ≤ Problem14.GameComparison.price 9223372036854775809 ∧
Problem14.GameComparison.price 9223372036854775809 ≤ (1585428682979231:ℝ)/10^6 := by
have h := P14Entry.printed_game verified5
exact ⟨h.1,h.2.1⟩
def allNearest5 := (P14Entry.printed_game verified5).2.2
theorem roundedCents5 : ⌊100*(Problem14.GameComparison.price 9223372036854775809)+1/2⌋₊ = 158542868298 := by
have lower := gameDollars5.1
have pos : 0 ≤ Problem14.GameComparison.price 9223372036854775809 := le_trans (by positivity) lower
obtain ⟨hl,hu⟩ := halfUp pos
have out := allNearest5 _ hl hu
exact out.2 rfl
def line6 : Record := ⟨18446744073709551615, 2242134745644524, 2242134745644542, 224213474564, 224213474564, true⟩
def hint6 : Witness := ⟨18446744073709551615, 18446744073709551615, 17⟩
theorem verified6 : line6.Check hint6 := by decide
def endpoints6 := @Record.exactEndpoints _ _ verified6
def cents6 := @Record.encloses _ _ verified6
def realPrice6 := @Record.realPrice _ _ verified6
theorem gameDollars6 : (2242134745644524:ℝ)/10^6 ≤ Problem14.GameComparison.price 18446744073709551615 ∧
Problem14.GameComparison.price 18446744073709551615 ≤ (2242134745644542:ℝ)/10^6 := by
have h := P14Entry.printed_game verified6
exact ⟨h.1,h.2.1⟩
def allNearest6 := (P14Entry.printed_game verified6).2.2
theorem roundedCents6 : ⌊100*(Problem14.GameComparison.price 18446744073709551615)+1/2⌋₊ = 224213474564 := by
have lower := gameDollars6.1
have pos : 0 ≤ Problem14.GameComparison.price 18446744073709551615 := le_trans (by positivity) lower
obtain ⟨hl,hu⟩ := halfUp pos
have out := allNearest6 _ hl hu
exact out.2 rfl
def line7 : Record := ⟨32768, 94484004, 94499635, 9448, 9450, false⟩
def hint7 : Witness := ⟨777472127993, 777478059612, 14909⟩
theorem verified7 : line7.Check hint7 := by decide
def endpoints7 := @Record.exactEndpoints _ _ verified7
def cents7 := @Record.encloses _ _ verified7
def realPrice7 := @Record.realPrice _ _ verified7
theorem gameDollars7 : (94484004:ℝ)/10^6 ≤ Problem14.GameComparison.price 32768 ∧
Problem14.GameComparison.price 32768 ≤ (94499635:ℝ)/10^6 := by
have h := P14Entry.printed_game verified7
exact ⟨h.1,h.2.1⟩
def allNearest7 := (P14Entry.printed_game verified7).2.2
theorem roundedCents7 : 9448 ≤ ⌊100*(Problem14.GameComparison.price 32768)+1/2⌋₊ ∧ ⌊100*(Problem14.GameComparison.price 32768)+1/2⌋₊ ≤ 9450 := by
have lower := gameDollars7.1
have pos : 0 ≤ Problem14.GameComparison.price 32768 := le_trans (by positivity) lower
obtain ⟨hl,hu⟩ := halfUp pos
have out := allNearest7 _ hl hu
exact out.1
end P14CheckedOutput
namespace P14CheckedOutput
theorem raw_line0 : P14Compact.render line0 = [112, 97, 105, 114, 115, 61, 49, 51, 51, 55, 56, 55, 48, 48, 48, 32, 105, 110, 116, 101, 114, 118, 97, 108, 61, 91, 54, 48, 51, 56, 46, 50, 49, 53, 52, 48, 54, 44, 32, 54, 48, 51, 56, 46, 50, 49, 56, 50, 52, 54, 93, 32, 110, 101, 97, 114, 101, 115, 116, 95, 99, 101, 110, 116, 61, 54, 48, 51, 56, 46, 50, 50, 10] := by decide
theorem raw_line1 : P14Compact.render line1 = [112, 97, 105, 114, 115, 61, 53, 48, 48, 48, 48, 48, 48, 48, 48, 32, 105, 110, 116, 101, 114, 118, 97, 108, 61, 91, 49, 49, 54, 55, 51, 46, 49, 49, 53, 49, 51, 49, 44, 32, 49, 49, 54, 55, 51, 46, 49, 49, 55, 51, 49, 48, 93, 32, 110, 101, 97, 114, 101, 115, 116, 95, 99, 101, 110, 116, 61, 49, 49, 54, 55, 51, 46, 49, 50, 10] := by decide
theorem raw_line2 : P14Compact.render line2 = [112, 97, 105, 114, 115, 61, 49, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 32, 105, 110, 116, 101, 114, 118, 97, 108, 61, 91, 53, 50, 50, 48, 51, 55, 46, 54, 55, 53, 53, 49, 50, 44, 32, 53, 50, 50, 48, 51, 55, 46, 54, 55, 53, 57, 56, 56, 93, 32, 110, 101, 97, 114, 101, 115, 116, 95, 99, 101, 110, 116, 61, 53, 50, 50, 48, 51, 55, 46, 54, 56, 10] := by decide
theorem raw_line3 : P14Compact.render line3 = [112, 97, 105, 114, 115, 61, 57, 50, 50, 51, 51, 55, 50, 48, 51, 54, 56, 53, 52, 55, 55, 53, 56, 48, 55, 32, 105, 110, 116, 101, 114, 118, 97, 108, 61, 91, 49, 53, 56, 53, 52, 50, 56, 54, 56, 50, 46, 57, 55, 57, 50, 49, 48, 44, 32, 49, 53, 56, 53, 52, 50, 56, 54, 56, 50, 46, 57, 55, 57, 50, 51, 49, 93, 32, 110, 101, 97, 114, 101, 115, 116, 95, 99, 101, 110, 116, 61, 49, 53, 56, 53, 52, 50, 56, 54, 56, 50, 46, 57, 56, 10] := by decide
theorem raw_line4 : P14Compact.render line4 = [112, 97, 105, 114, 115, 61, 57, 50, 50, 51, 51, 55, 50, 48, 51, 54, 56, 53, 52, 55, 55, 53, 56, 48, 56, 32, 105, 110, 116, 101, 114, 118, 97, 108, 61, 91, 49, 53, 56, 53, 52, 50, 56, 54, 56, 50, 46, 57, 55, 57, 50, 49, 48, 44, 32, 49, 53, 56, 53, 52, 50, 56, 54, 56, 50, 46, 57, 55, 57, 50, 51, 49, 93, 32, 110, 101, 97, 114, 101, 115, 116, 95, 99, 101, 110, 116, 61, 49, 53, 56, 53, 52, 50, 56, 54, 56, 50, 46, 57, 56, 10] := by decide
theorem raw_line5 : P14Compact.render line5 = [112, 97, 105, 114, 115, 61, 57, 50, 50, 51, 51, 55, 50, 48, 51, 54, 56, 53, 52, 55, 55, 53, 56, 48, 57, 32, 105, 110, 116, 101, 114, 118, 97, 108, 61, 91, 49, 53, 56, 53, 52, 50, 56, 54, 56, 50, 46, 57, 55, 57, 50, 49, 48, 44, 32, 49, 53, 56, 53, 52, 50, 56, 54, 56, 50, 46, 57, 55, 57, 50, 51, 49, 93, 32, 110, 101, 97, 114, 101, 115, 116, 95, 99, 101, 110, 116, 61, 49, 53, 56, 53, 52, 50, 56, 54, 56, 50, 46, 57, 56, 10] := by decide
theorem raw_line6 : P14Compact.render line6 = [112, 97, 105, 114, 115, 61, 49, 56, 52, 52, 54, 55, 52, 52, 48, 55, 51, 55, 48, 57, 53, 53, 49, 54, 49, 53, 32, 105, 110, 116, 101, 114, 118, 97, 108, 61, 91, 50, 50, 52, 50, 49, 51, 52, 55, 52, 53, 46, 54, 52, 52, 53, 50, 52, 44, 32, 50, 50, 52, 50, 49, 51, 52, 55, 52, 53, 46, 54, 52, 52, 53, 52, 50, 93, 32, 110, 101, 97, 114, 101, 115, 116, 95, 99, 101, 110, 116, 61, 50, 50, 52, 50, 49, 51, 52, 55, 52, 53, 46, 54, 52, 10] := by decide
theorem raw_line7 : P14Compact.render line7 = [112, 97, 105, 114, 115, 61, 51, 50, 55, 54, 56, 32, 105, 110, 116, 101, 114, 118, 97, 108, 61, 91, 57, 52, 46, 52, 56, 52, 48, 48, 52, 44, 32, 57, 52, 46, 52, 57, 57, 54, 51, 53, 93, 32, 112, 111, 115, 115, 105, 98, 108, 101, 95, 99, 101, 110, 116, 115, 61, 91, 57, 52, 46, 52, 56, 44, 32, 57, 52, 46, 53, 48, 93, 10] := by decide
end P14CheckedOutput
~~~
#### `minelf/CompactCore.lean`
~~~lean
import QuoteEntry
import CompactDebit
/-! Live-register semantics of the compact pricing path. All code except the
choice of debit routine is shared with the existing checked quote. Work at
the call boundary lets the debit's literal instruction proof be plugged in. -/
namespace P14Compact
open P14Quote P14Entry
def QuoteReturns (n fpLo fpHi : Nat) (s : M.State) (sl sh : R.CPU)
(debitReturns : Nat → Prop) (post : M.State → Prop) :=
R.Returns (fun l => ∃ a,
M.run (rootResult s l) M.lowerOps=some a ∧
R.Returns (fun h => ∃ b,
M.run (rootResult a h) M.upperOps=some b ∧
∃ d, debitReturns d ∧ ∃ z, M.run {b with ax:=d} M.finalOps=some z ∧ post z)
(rootCPU sh n (2^63) fpHi))
(rootCPU sl n 0 fpLo)
private theorem root_call (s : R.CPU) (hi lo fp : Nat)
(hh : hi<2^64) (hl : lo<2^64) (hf : fp<2^64) :
let y := hi*2^64+lo
R.Returns (fun t => t.reg .ax=floorSqrt y ∧
t.reg .dx=if (floorSqrt y)^2=y then 1 else 0) (rootCPU s hi lo fp) := by
apply (R.root_repair_quote (rootCPU s hi lo fp) lo hi (P14Seeds.rootSeed hi lo fp)
rfl rfl rfl rfl hl hh (P14Seeds.seed_guard hh hl hf).2.2).weaken
exact fun t h => ⟨h.1,h.2.1⟩
theorem compact_core {n f g : Nat} (hn : 32768≤n) (hu : n
#### `minelf/CompactDebit.lean`
~~~lean
import DebitTable
/-! The compact debit needs no precomputed table. It divides the 86-bit
constant 137000^5−1 by the possibly 65-bit divisor 2n+1, then compares
exact fifth powers with the quotient. -/
namespace P14Compact
open P14Quote
def W : Nat := 2^64
def target : Nat := debitPower-1
def halfTarget : Nat := debitPower/2-1
def join (hi lo : Nat) := hi*W+lo
def longDiv (a m : Nat) :=
let h := a/W
let l := a%W
join (h/m) (join (h%m) l /m)
theorem longDiv_eq (a m : Nat) (hm : 0 rhs; rw [←rep]
rw [Nat.mul_add_div hm]
rfl
theorem longDiv_fits {m : Nat} (hm : 0 rename_i h
· symm
apply Nat.div_eq_of_lt_le
· rw [Nat.sub_mul,prod,Nat.one_mul]
unfold divisor
omega
· rw [show q-1+1=q by omega,prod]
omega
· rw [Nat.sub_zero]
symm
apply Nat.div_eq_of_lt_le
· rw [prod]; omega
· rw [Nat.add_mul,prod,Nat.one_mul,dest]
unfold divisor
calc
2*(n*q+r)+1 < 2*(n*q+n)+1 := Nat.add_lt_add_right
(Nat.mul_lt_mul_of_pos_left (Nat.add_lt_add_left rn _) (by decide : 0<2)) _
_ = 2*(n*q)+(2*n+1) := by rw [Nat.mul_add,Nat.add_assoc]
_ ≤ 2*(n*q)+q+(2*n+1) := Nat.add_le_add_right (Nat.le_add_right _ _) _
theorem largeDiv_fits (n : Nat) (hn : 2^63 ≤ n) :
halfTarget/W < n ∧ halfTarget/n < W := by
have cap : halfTarget/W < 2^63 := by decide
have bound : halfTarget < W*2^63 := by decide
exact ⟨Nat.lt_of_lt_of_le cap hn,(Nat.div_lt_iff_lt_mul (by omega)).mpr
(Nat.lt_of_lt_of_le bound (Nat.mul_le_mul_left W hn))⟩
def quotient (n : Nat) := if n < 2^63 then longDiv target (divisor n) else largeDiv n
theorem quotient_eq (n : Nat) : quotient n = target/divisor n := by
unfold quotient
split
· exact longDiv_eq _ _ (by unfold divisor; omega)
· exact largeDiv_eq _ (by omega)
theorem passes_iff {n d : Nat} :
quotient n < d^5 ↔ debitPower ≤ d^5*divisor n := by
rw [quotient_eq,Nat.div_lt_iff_lt_mul (by unfold divisor; omega : 0
rw [search,dif_pos room,if_pos pass]
exact ih hl ((root _).mp pass)
| case2 l h room mid fails ih =>
rw [search,dif_pos room,if_neg fails]
exact ih (by have hn : ¬d≤mid := fun hd => fails ((root _).mpr hd); omega) hh
| case3 l h done => rw [search,dif_neg done]; omega
theorem fit_iff {n d : Nat} (hd : DebitSpec n d) (j : Nat) :
quotient n < j^5 ↔ d ≤ j := by
rw [passes_iff]
constructor
· intro pass
by_cases hj : d ≤ j
· exact hj
· exact False.elim ((Nat.not_lt_of_ge pass) (hd.2 j (by omega)))
· intro hj
exact Nat.le_trans hd.1 (Nat.mul_le_mul_right _ (Nat.pow_le_pow_left hj 5))
def algorithm (n : Nat) :=
let q := if n < 2^63 then divideWord target (divisor n) else largeDiv n
search q 17 14909
theorem algorithm_eq {n : Nat} (hl : 32768 ≤ n) (hu : n
#### `minelf/CompactEntry.lean`
~~~lean
import CompactCore
import CompactQuotient
import CompactLoop
/-! Complete compact debit and price call chain. At byte offset 83 the
low and high quotient words are passed directly from the hardware division
prefix to the inclusive search loop. Frame pointers, the return address,
and disjoint writable output words have the same ABI assumptions as the
original quotation routine. -/
namespace P14Compact
open P14Quote P14Entry
/-- Transfer every register shared by the two instruction projections.
The loop overwrites ESI and both flags before it uses their values. -/
def handoff (s : QuotCPU.State) (scratch : LoopCPU.State) : LoopCPU.State :=
{scratch with pc:=s.pc,ax:=s.ax,dx:=s.dx,cx:=s.cx,di:=s.di,r8:=s.r8,r9:=s.r9,cf:=s.cf}
def DebitReturns (s : QuotCPU.State) (t : LoopCPU.State) (n d : Nat) : Prop :=
∃ z, QuotCPU.run 20 {s with pc:=0, di:=n} = some z ∧ z.pc=83 ∧
LoopCPU.Returns d (handoff z t)
theorem compact_debit_returns (s : QuotCPU.State) (t : LoopCPU.State) (n : Nat) (hu : n
z.outLo=lowerMicro n (floorSqrt (inputLo n)) (debit n) ∧
z.outHi=upperMicro n (floorSqrt (inputHi n))) :=
compact_core hn hu fl fh s sl sh (compact_debit_returns d t n hu) (fun _ lo hi=>⟨lo,hi⟩)
#print axioms machine_endpoints
end P14Compact
~~~
#### `minelf/CompactGame.lean`
~~~lean
import CompactEntry
import asmproof.GameMachinePrice
/-! The compact, table-free integer program encloses the same finite
optimal-stopping price as the previously certified program. The two
finite Bellman certificates use Lean native evaluation. -/
namespace P14Compact
open P14Quote P14Entry
theorem machine_encloses_game {n f g : Nat} (hn : 32768≤n) (hu : n
(z.outLo:ℝ)/10^6 ≤ Problem14.GameComparison.price n ∧
Problem14.GameComparison.price n ≤ (z.outHi:ℝ)/10^6) := by
apply compact_core hn hu fl fh s sl sh (compact_debit_returns d t n hu)
intro z left right
rw [left,right]
exact cash_endpoints hn hu
#print axioms machine_encloses_game
end P14Compact
~~~
#### `minelf/CompactLoop.lean`
~~~lean
import CompactDebit
/-! Decoded x86-64 execution of offsets 83..139 of p14_compact_debit.
States retain the registers and condition flags read on this path.
A return is observed when the decoded RET uses the SysV return address. -/
namespace P14Compact.LoopCPU
open P14Compact
set_option maxRecDepth 4096
set_option maxHeartbeats 1000000
structure State where
pc : Nat := 0
ax : Nat := 0
dx : Nat := 0
cx : Nat := 0
si : Nat := 0
di : Nat := 0
r8 : Nat := 0
r9 : Nat := 0
cf : Bool := false
zf : Bool := false
inductive Op where
| loadLo | loadHi | cmpRange | sum32 | shr32 | copyCx | square
| multiply | cmpHigh | cmpLow | raiseLo | lowerHi | movResult | ret
| jumpEq (pc : Nat) | jumpAbove (pc : Nat) | jumpBelow (pc : Nat) | jump (pc : Nat)
deriving DecidableEq, Repr
open Op
def bytes : List Nat := [190, 17, 0, 0, 0, 191, 61, 58, 0, 0, 57, 254, 116, 40, 141, 12, 62, 209, 233, 72, 137, 200, 72, 15, 175, 192, 72, 15, 175, 192, 72, 247, 225, 76, 57, 194, 119, 12, 114, 5, 76, 57, 200, 119, 5, 141, 113, 1, 235, 216, 137, 207, 235, 212, 137, 240, 195]
private def relative (next d : Nat) := if d<128 then next+d else next+d-256
private def decode (pc : Nat) : List Nat → Option (Op × Nat)
| 190::17::0::0::0::_ => some (loadLo,pc+5)
| 191::61::58::0::0::_ => some (loadHi,pc+5)
| 57::254::_ => some (cmpRange,pc+2)
| 116::d::_ => some (jumpEq (relative (pc+2) d),pc+2)
| 141::12::62::_ => some (sum32,pc+3)
| 209::233::_ => some (shr32,pc+2)
| 72::137::200::_ => some (copyCx,pc+3)
| 72::15::175::192::_ => some (square,pc+4)
| 72::247::225::_ => some (multiply,pc+3)
| 76::57::194::_ => some (cmpHigh,pc+3)
| 119::d::_ => some (jumpAbove (relative (pc+2) d),pc+2)
| 114::d::_ => some (jumpBelow (relative (pc+2) d),pc+2)
| 76::57::200::_ => some (cmpLow,pc+3)
| 141::113::1::_ => some (raiseLo,pc+3)
| 235::d::_ => some (jump (relative (pc+2) d),pc+2)
| 137::207::_ => some (lowerHi,pc+2)
| 137::240::_ => some (movResult,pc+2)
| 195::_ => some (ret,pc+1)
| _ => none
def fetch (pc : Nat) := if pc<83 then none else decode pc (bytes.drop (pc-83))
private def narrow (v : Nat) := v % 2^32
private def setCmp (s : State) (x y : Nat) : State :=
{s with cf:=decide (x {z with si:=17}
| loadHi => {z with di:=14909}
| cmpRange => setCmp z (narrow s.si) (narrow s.di)
| sum32 => {z with cx:=narrow (s.si+s.di)}
| shr32 => {z with cx:=narrow s.cx / 2}
| copyCx => {z with ax:=s.cx}
| square => {z with ax:=s.ax*s.ax % W}
| multiply => {z with ax:=s.ax*s.cx%W,dx:=s.ax*s.cx/W}
| cmpHigh => setCmp z s.dx s.r8
| cmpLow => setCmp z s.ax s.r9
| raiseLo => {z with si:=narrow (s.cx+1)}
| lowerHi => {z with di:=narrow s.cx}
| movResult => {z with ax:=narrow s.si}
| jumpEq d => {s with pc:=if s.zf then d else next}
| jumpAbove d => {s with pc:=if !s.cf && !s.zf then d else next}
| jumpBelow d => {s with pc:=if s.cf then d else next}
| jump d => {s with pc:=d}
| ret => z
inductive Returns (v : Nat) : State → Prop where
| atRet {s next} : fetch s.pc=some (.ret,next) → s.ax=v → Returns v s
| step {s op next} : fetch s.pc=some (op,next) → op≠.ret →
Returns v (exec s next op) → Returns v s
private def walk (s : State) : List (Op × Nat) → State
| [] => s
| (op,k)::rest => walk (exec s k op) rest
private def legal (s : State) : List (Op × Nat) → Prop
| [] => True
| (op,k)::rest => fetch s.pc = some (op,k) ∧ op ≠ .ret ∧ legal (exec s k op) rest
private theorem follow {s : State} {ops : List (Op×Nat)} (h : legal s ops)
{v : Nat} (ret : Returns v (walk s ops)) : Returns v s := by
induction ops generalizing s with
| nil => exact ret
| cons pair tail ih => rcases pair with ⟨o,k⟩; exact .step h.1 h.2.1 (ih h.2.2 ret)
@[simp] private theorem fetch83 : fetch 83=some (loadLo,88) := by decide
@[simp] private theorem fetch88 : fetch 88=some (loadHi,93) := by decide
@[simp] private theorem fetch93 : fetch 93=some (cmpRange,95) := by decide
@[simp] private theorem fetch95 : fetch 95=some (jumpEq 137,97) := by decide
@[simp] private theorem fetch97 : fetch 97=some (sum32,100) := by decide
@[simp] private theorem fetch100 : fetch 100=some (shr32,102) := by decide
@[simp] private theorem fetch102 : fetch 102=some (copyCx,105) := by decide
@[simp] private theorem fetch105 : fetch 105=some (square,109) := by decide
@[simp] private theorem fetch109 : fetch 109=some (square,113) := by decide
@[simp] private theorem fetch113 : fetch 113=some (multiply,116) := by decide
@[simp] private theorem fetch116 : fetch 116=some (cmpHigh,119) := by decide
@[simp] private theorem fetch119 : fetch 119=some (jumpAbove 133,121) := by decide
@[simp] private theorem fetch121 : fetch 121=some (jumpBelow 128,123) := by decide
@[simp] private theorem fetch123 : fetch 123=some (cmpLow,126) := by decide
@[simp] private theorem fetch126 : fetch 126=some (jumpAbove 133,128) := by decide
@[simp] private theorem fetch128 : fetch 128=some (raiseLo,131) := by decide
@[simp] private theorem fetch131 : fetch 131=some (jump 93,133) := by decide
@[simp] private theorem fetch133 : fetch 133=some (lowerHi,135) := by decide
@[simp] private theorem fetch135 : fetch 135=some (jump 93,137) := by decide
@[simp] private theorem fetch137 : fetch 137=some (movResult,139) := by decide
@[simp] private theorem fetch139 : fetch 139=some (ret,140) := by decide
private def Range (s : State) (qh ql l u : Nat) :=
s.pc=93 ∧ s.r8=qh ∧ s.r9=ql ∧ s.si=l ∧ s.di=u
private def Mid (s : State) (qh ql l u m : Nat) :=
s.pc=119 ∧ s.r8=qh ∧ s.r9=ql ∧ s.si=l ∧ s.di=u ∧ s.cx=m ∧
s.ax=m^5%W ∧ s.cf=decide (m^5/W
rw [search,dif_pos room,if_pos pass]
apply midpoint h room bound
intro z hz
exact route hz lo (by omega) (fun _ t ht => ih (by omega) (by omega) t ht)
(fun bad => False.elim (bad pass))
| case2 l u room m fail ih =>
rw [search,dif_pos room,if_neg fail]
apply midpoint h room bound
intro z hz
exact route hz lo (by omega) (fun bad => False.elim (fail bad))
(fun _ t ht => ih (by omega) bound t ht)
| case3 l u done =>
rw [search,dif_neg done]
have eq : u=l := by omega
subst u
obtain ⟨pc,_,_,si,di⟩ := h
let ops : List (Op×Nat) := [(cmpRange,95),(jumpEq 137,97),(movResult,139)]
apply follow (ops:=ops)
· simp [ops,legal,exec,setCmp,pc,si,di]
· apply Returns.atRet (next:=140)
· simp [walk,ops,exec]
· simp [walk,ops,exec,setCmp,si,narrow,Nat.mod_eq_of_lt (by omega : l<2^32)]
/-- A finite trace from the first register initialization through the decoded
RET. The caller supplies only the high and low limbs of its quotient. -/
theorem bisect_run (s : State) (entry : s.pc=83) (lo : s.r9
#### `minelf/CompactQuotient.lean`
~~~lean
import CompactDebit
/-! Literal x86-64 quotient prefix. PCs are byte offsets from p14_compact_debit.
The state projects the registers and condition flags read by this prefix.
DIV leaves its undefined flags unconstrained by the returned theorem.
An unsigned DIV with high dividend ≥ divisor faults. The instruction following
byte 82 starts the fifth-power search with its quotient in R8:R9. -/
namespace P14Compact.QuotCPU
open P14Quote
structure State where
pc : Nat := 0
ax : Nat := 0
dx : Nat := 0
cx : Nat := 0
r8 : Nat := 0
r9 : Nat := 0
di : Nat := 0
cf : Bool := false
sf : Bool := false
deriving Repr
inductive Op where
| xorR8 | testDi | js65 | leaOdd | setHigh | cmpDxCx | jbLow | axDx
| xorDx | divCx | r8Ax | setLow | r9Ax | jmpEnd | setHalfLow | setHalfHigh
| divDi | shrAx | cmpDxAx | sbbR9
deriving DecidableEq, Repr
open Op
def highImm := [0xd1,0xeb,0x27,0x00]
def lowImm := [0xff,0x7f,0x4a,0xb6,0x73,0xe2,0x40,0x53]
def halfLowImm := [0xff,0x3f,0x25,0xdb,0x39,0x71,0xa0,0xa9]
def halfHighImm := [0xe8,0xf5,0x13,0x00]
def little : List Nat → Nat
| [] => 0
| b::bs => b+256*little bs
def instr : Op → List Nat
| xorR8 => [0x45,0x31,0xc0]
| testDi => [0x48,0x85,0xff]
| js65 => [0x78,0x2c]
| leaOdd => [0x48,0x8d,0x4c,0x3f,0x01]
| setHigh => 0xba :: highImm
| cmpDxCx => [0x48,0x39,0xca]
| jbLow => [0x72,0x0b]
| axDx => [0x48,0x89,0xd0]
| xorDx => [0x31,0xd2]
| divCx => [0x48,0xf7,0xf1]
| r8Ax => [0x49,0x89,0xc0]
| setLow => [0x48,0xb8] ++ lowImm
| r9Ax => [0x49,0x89,0xc1]
| jmpEnd => [0xeb,0x1f]
| setHalfLow => [0x48,0xb8] ++ halfLowImm
| setHalfHigh => 0xba :: halfHighImm
| divDi => [0x48,0xf7,0xf7]
| shrAx => [0x48,0xd1,0xe8]
| cmpDxAx => [0x48,0x39,0xc2]
| sbbR9 => [0x49,0x83,0xd9,0x00]
def all : List Op := [xorR8,testDi,js65,leaOdd,setHigh,cmpDxCx,jbLow,axDx,xorDx,divCx,
r8Ax,setLow,r9Ax,jmpEnd,setHalfLow,setHalfHigh,divDi,shrAx,cmpDxAx,sbbR9]
def bytes : List Nat := [69,49,192,72,133,255,120,44,72,141,76,63,1,186,209,235,39,0,
72,57,202,114,11,72,137,208,49,210,72,247,241,73,137,192,72,184,255,127,74,182,
115,226,64,83,72,247,241,73,137,193,235,31,72,184,255,63,37,219,57,113,160,169,
186,232,245,19,0,72,247,247,73,137,193,72,209,232,72,57,194,73,131,217,0]
def fetch (pc : Nat) : Option Op := all.find? fun op => (instr op).isPrefixOf (bytes.drop pc)
def divide (s : State) (d : Nat) : Option State :=
if s.dx < d then
let a := join s.dx s.ax
some {s with ax:=a/d, dx:=a%d}
else none
def exec (s : State) (op : Op) : Option State :=
let z := {s with pc:=s.pc+(instr op).length}
match op with
| xorR8 => some {z with r8:=0, cf:=false, sf:=false}
| testDi => some {z with cf:=false, sf:=decide (2^63≤s.di%W)}
| js65 => some {z with pc:=if s.sf then z.pc+0x2c else z.pc}
| leaOdd => some {z with cx:=(2*s.di+1)%W}
| setHigh => some {z with dx:=little highImm}
| cmpDxCx => some {z with cf:=decide (s.dx some {z with pc:=if s.cf then z.pc+0x0b else z.pc}
| axDx => some {z with ax:=s.dx}
| xorDx => some {z with dx:=0, cf:=false, sf:=false}
| divCx => divide z s.cx
| r8Ax => some {z with r8:=s.ax}
| setLow => some {z with ax:=little lowImm}
| r9Ax => some {z with r9:=s.ax}
| jmpEnd => some {z with pc:=z.pc+0x1f}
| setHalfLow => some {z with ax:=little halfLowImm}
| setHalfHigh => some {z with dx:=little halfHighImm}
| divDi => divide z s.di
| shrAx => some {z with ax:=s.ax/2, cf:=decide (s.ax%2=1), sf:=false}
| cmpDxAx => some {z with cf:=decide (s.dx
let borrow := if s.cf then 1 else 0
let diff := (s.r9+W-borrow)%W
some {z with r9:=diff, cf:=decide (s.r9 if s.pc=83 then some s else none
| k+1, s => if s.pc=83 then some s else do
let op ← fetch s.pc
let next ← exec s op
run k next
@[simp] private theorem pc0 : fetch 0 = some xorR8 := by decide
@[simp] private theorem pc3 : fetch 3 = some testDi := by decide
@[simp] private theorem pc6 : fetch 6 = some js65 := by decide
@[simp] private theorem pc8 : fetch 8 = some leaOdd := by decide
@[simp] private theorem pc13 : fetch 13 = some setHigh := by decide
@[simp] private theorem pc18 : fetch 18 = some cmpDxCx := by decide
@[simp] private theorem pc21 : fetch 21 = some jbLow := by decide
@[simp] private theorem pc23 : fetch 23 = some axDx := by decide
@[simp] private theorem pc26 : fetch 26 = some xorDx := by decide
@[simp] private theorem pc28 : fetch 28 = some divCx := by decide
@[simp] private theorem pc31 : fetch 31 = some r8Ax := by decide
@[simp] private theorem pc34 : fetch 34 = some setLow := by decide
@[simp] private theorem pc44 : fetch 44 = some divCx := by decide
@[simp] private theorem pc47 : fetch 47 = some r9Ax := by decide
@[simp] private theorem pc50 : fetch 50 = some jmpEnd := by decide
@[simp] private theorem pc52 : fetch 52 = some setHalfLow := by decide
@[simp] private theorem pc62 : fetch 62 = some setHalfHigh := by decide
@[simp] private theorem pc67 : fetch 67 = some divDi := by decide
@[simp] private theorem pc70 : fetch 70 = some r9Ax := by decide
@[simp] private theorem pc73 : fetch 73 = some shrAx := by decide
@[simp] private theorem pc76 : fetch 76 = some cmpDxAx := by decide
@[simp] private theorem pc79 : fetch 79 = some sbbR9 := by decide
@[simp] private theorem size_xorR8 : (instr xorR8).length = 3 := by decide
@[simp] private theorem size_testDi : (instr testDi).length = 3 := by decide
@[simp] private theorem size_js65 : (instr js65).length = 2 := by decide
@[simp] private theorem size_leaOdd : (instr leaOdd).length = 5 := by decide
@[simp] private theorem size_setHigh : (instr setHigh).length = 5 := by decide
@[simp] private theorem size_cmpDxCx : (instr cmpDxCx).length = 3 := by decide
@[simp] private theorem size_jbLow : (instr jbLow).length = 2 := by decide
@[simp] private theorem size_axDx : (instr axDx).length = 3 := by decide
@[simp] private theorem size_xorDx : (instr xorDx).length = 2 := by decide
@[simp] private theorem size_divCx : (instr divCx).length = 3 := by decide
@[simp] private theorem size_r8Ax : (instr r8Ax).length = 3 := by decide
@[simp] private theorem size_setLow : (instr setLow).length = 10 := by decide
@[simp] private theorem size_r9Ax : (instr r9Ax).length = 3 := by decide
@[simp] private theorem size_jmpEnd : (instr jmpEnd).length = 2 := by decide
@[simp] private theorem size_setHalfLow : (instr setHalfLow).length = 10 := by decide
@[simp] private theorem size_setHalfHigh : (instr setHalfHigh).length = 5 := by decide
@[simp] private theorem size_divDi : (instr divDi).length = 3 := by decide
@[simp] private theorem size_shrAx : (instr shrAx).length = 3 := by decide
@[simp] private theorem size_cmpDxAx : (instr cmpDxAx).length = 3 := by decide
@[simp] private theorem size_sbbR9 : (instr sbbR9).length = 4 := by decide
private theorem high : little highImm = target/W := by decide
private theorem low : little lowImm = target%W := by decide
private theorem half_high : little halfHighImm = halfTarget/W := by decide
private theorem half_join : join (little halfHighImm) (little halfLowImm) = halfTarget := by decide
private theorem rep : join (target/W) (target%W) = target := by decide
private def Good (n : Nat) : Option State → Prop
| none => False
| some z => z.pc=83 ∧ z.di=n ∧ z.r8 rw [e] at h; exact h.elim
| some z => exact ⟨z,rfl,by simpa only [e,Good] using h⟩
#print axioms run_to_bisect
end P14Compact.QuotCPU
~~~
#### `minelf/ELFHeader.lean`
~~~lean
import Std
/-! Decode the ELF64 header and its single ELF64 program-header slot from
the 120 emitted bytes. All offsets below are byte offsets and all integer
fields are little-endian. This describes the file format. -/
namespace Problem14.MinELF
def le (bytes : List UInt8) (offset width : Nat) : Nat :=
((bytes.drop offset).take width).foldr (fun byte n => byte.toNat+256*n) 0
structure Program where
kind : Nat
flags : Nat
offset : Nat
vaddr : Nat
paddr : Nat
fileSize : Nat
memSize : Nat
align : Nat
deriving DecidableEq
structure Header where
ident : List UInt8
kind : Nat
machine : Nat
version : Nat
entry : Nat
phoff : Nat
shoff : Nat
flags : Nat
ehsize : Nat
phentsize : Nat
phnum : Nat
shentsize : Nat
shnum : Nat
shstrndx : Nat
program : Program
deriving DecidableEq
def decode (bytes : List UInt8) : Header :=
let u := le bytes
⟨bytes.take 16, u 16 2, u 18 2, u 20 4, u 24 8, u 32 8, u 40 8, u 48 4,
u 52 2, u 54 2, u 56 2, u 58 2, u 60 2, u 62 2,
⟨u 64 4, u 68 4, u 72 8, u 80 8, u 88 8, u 96 8, u 104 8, u 112 8⟩⟩
/-- The expected complete header, including zero-valued fields. One PT_LOAD
with PF_R | PF_X accounts for every program header; a separate interpreter
or dynamic-linking program header would require another slot. -/
def layout (fileSize entryOffset : Nat) : Header :=
⟨[0x7f,0x45,0x4c,0x46,2,1,1,0,0,0,0,0,0,0,0,0],
2, 62, 1, 0x400000+entryOffset, 64, 0, 0, 64, 56, 1, 0, 0, 0,
⟨1, 5, 0, 0x400000, 0x400000, fileSize, fileSize, 4096⟩⟩
abbrev Certified (raw : List UInt8) (size entryOffset : Nat) : Prop :=
raw.length = 120 ∧ 120 ≤ entryOffset ∧ entryOffset < size ∧
decode raw = layout size entryOffset
theorem entry_in_load {raw size offset} (h : Certified raw size offset) :
(decode raw).program.vaddr+120 ≤ (decode raw).entry ∧
(decode raw).entry < (decode raw).program.vaddr+(decode raw).program.fileSize := by
rw [h.2.2.2]
change 0x400000+120 ≤ 0x400000+offset ∧ 0x400000+offset < 0x400000+size
obtain ⟨_,_,_,_⟩ := h
omega
/-- The first and last memory bytes lie on the same 4 KiB page. -/
theorem one_page {raw size offset} (h : Certified raw size offset) (small : size≤4096) :
(decode raw).program.vaddr/4096 =
((decode raw).program.vaddr+(decode raw).program.memSize-1)/4096 := by
rw [h.2.2.2]
change 0x400000/4096 = (0x400000+size-1)/4096
obtain ⟨_,_,_,_⟩ := h
omega
end Problem14.MinELF
~~~
#### `minelf/RenderCompact.lean`
~~~lean
import CLIProof
import OutputCertificate
/-! Raw ASCII records as emitted by the compact binary. The existing
digit-pair proof supplies both the variable-width integer part and the
exactly six or two fractional digits, including leading zeroes. -/
namespace P14Compact
open P14Quote Problem14.CLI
def textBytes (s : String) : List Nat := s.toList.map Char.toNat
/-- Unroll ten digit-pair steps to let the kernel evaluate every uint64
sample by reduction. Beyond that depth the original formatter is used. -/
def whole : Nat → Nat → List Nat
| 0, n => wholeDigits n
| k+1, n => if n<10 then [48+n] else if n<100 then two n
else whole k (n/100) ++ two (n%100)
theorem whole_eq (k n : Nat) : whole k n = wholeDigits n := by
induction k generalizing n with
| zero => rfl
| succ k ih =>
conv => rhs; rw [wholeDigits]
simp only [whole,ih]
def fixedBytes (n pairs : Nat) : List Nat :=
let qr := splitFraction n pairs
whole 10 qr.1 ++ [46] ++ qr.2
def render (r : Record) : List Nat :=
let startBytes := textBytes "pairs=" ++ whole 10 r.pairs ++ textBytes " interval=[" ++
fixedBytes r.lo 3 ++ textBytes ", " ++ fixedBytes r.hi 3
if r.single then startBytes ++ textBytes "] nearest_cent=" ++ fixedBytes r.lowCent 1 ++ [10]
else startBytes ++ textBytes "] possible_cents=[" ++ fixedBytes r.lowCent 1 ++
textBytes ", " ++ fixedBytes r.highCent 1 ++ [93,10]
end P14Compact
~~~
#### `Makefile`
~~~text
CC ?= cc
CXX ?= c++
LEAN ?= lean
PYTHON ?= python3
.PHONY: all check lean-check verify-quotes
all: fast exact record heat catalan price
fast: fast.c
$(CC) -std=c11 -O3 -march=native -frounding-math -ffp-contract=off $< -lm -o $@
record: record.c
$(CC) -std=gnu11 -O3 -march=native -frounding-math -ffp-contract=off $< -lm -o $@
price: price.c
$(CC) -std=gnu11 -O3 $< -o $@
heat: heat.c
$(CC) -std=gnu11 -O3 -march=native $< -lm -o $@
catalan: catalan.c
$(CC) -std=gnu11 -O3 -march=native -frounding-math -ffp-contract=off $< -lm -o $@
constant-upper: constant_upper.c
$(CC) -std=c11 -O3 $< -o $@
verify-multislab: verify_multislab.c multislab.h record.c
$(CC) -std=gnu11 -O3 -march=native -frounding-math -ffp-contract=off $< -lm -o $@
fractional-verify: fractional_verify.c
$(CC) -std=gnu11 -O3 -march=native -frounding-math -ffp-contract=off $< -lm -o $@
verify-quotes: price constant-upper fractional-verify
./constant-upper
./fractional-verify
$(PYTHON) quote_test.py
exact: exact.cpp
$(CXX) -std=c++17 -O3 $< -lgmpxx -lgmp -o $@
frontier: frontier.cpp
$(CXX) -std=c++17 -O3 $< -lgmpxx -lgmp -o $@
Problem14.olean: Problem14.lean
$(LEAN) -o $@ $<
lean-check: Problem14.olean
LEAN_PATH=. $(LEAN) Excursions.lean
LEAN_PATH=. $(LEAN) RationalObstruction.lean
LEAN_PATH=. $(LEAN) Tableau.lean
LEAN_PATH=. $(LEAN) StraightLine.lean
$(LEAN) Plateau.lean
$(LEAN) FactorialPowers.lean
$(LEAN) FrontierExtension.lean
$(LEAN) TaylorGap.lean
check: all lean-check verify-quotes verify-multislab frontier
$(PYTHON) exact_test.py ./exact
$(PYTHON) test_fast.py ./fast
$(PYTHON) record_test.py
$(PYTHON) straight_line.py --check
$(PYTHON) frontier_test.py
$(PYTHON) heat_test.py ./heat
$(PYTHON) catalan_test.py ./catalan ./exact
./verify-multislab
$(PYTHON) test_multislab.py
$(PYTHON) test_frontier.py ./frontier ./exact
$(PYTHON) shrinking_check.py
# Standalone Linux / x86-64 quote and the corresponding callable kernel.
ASMDIR := asmproof
ASMKERNEL := $(addprefix $(ASMDIR)/,quote.S root_repair.S debit_correct.S)
ASM_LDFLAGS := -nostdlib -static -no-pie -Wl,--build-id=none,-z,noseparate-code
OBJCOPY ?= objcopy
.PHONY: asm check-asm proof-asm proof-asm-full bench-asm
asm: price-asm
price-asm.elf: $(ASMDIR)/cli.S $(ASMKERNEL) $(ASMDIR)/debit_table.inc
$(CC) $(ASM_LDFLAGS) $(ASMDIR)/cli.S $(ASMKERNEL) -o $@
price-asm: price-asm.elf
$(OBJCOPY) --strip-all $< $@
bench-quote: $(ASMDIR)/bench_quote.c price.c $(ASMKERNEL) $(ASMDIR)/debit_table.inc
$(CC) -O3 -march=native $< $(ASMKERNEL) -lm -o $@
bench-startup: $(ASMDIR)/bench_startup.c
$(CC) -O3 $< -o $@
price-startup-control: $(ASMDIR)/cli.S $(ASMDIR)/startup_control.c price.c
$(CC) -O3 -ffreestanding -ffunction-sections -fdata-sections -fno-asynchronous-unwind-tables $(ASM_LDFLAGS) -Wl,--gc-sections,-s $(ASMDIR)/cli.S $(ASMDIR)/startup_control.c -lgcc -o $@
check-asm: asm price bench-quote
./bench-quote --test
$(PYTHON) $(ASMDIR)/cli_test.py ./price ./price-asm
$(PYTHON) $(ASMDIR)/check_quote_bytes.py price-asm.elf price-asm
$(PYTHON) $(ASMDIR)/check_root_bytes.py price-asm.elf
$(PYTHON) $(ASMDIR)/check_debit.py price-asm.elf
proof-asm: check-asm
$(PYTHON) $(ASMDIR)/build_proofs.py --lean $(LEAN)
LEAN_PATH=.asm-build $(PYTHON) $(ASMDIR)/check_debit.py price-asm.elf --lean $(LEAN)
$(PYTHON) $(ASMDIR)/certify_price.py --lean $(LEAN) --exe ./price-asm --self-test
proof-asm-full: check-asm check-batch
$(PYTHON) $(ASMDIR)/build_proofs.py --lean $(LEAN) --mathlib "$(MATHLIB)"
LEAN_PATH=.asm-build $(PYTHON) $(ASMDIR)/check_debit.py price-asm.elf --lean $(LEAN) --mathlib "$(MATHLIB)" --game
$(PYTHON) $(ASMDIR)/certify_price.py --lean $(LEAN) --mathlib "$(MATHLIB)" --game --exe ./price-asm --self-test
bench-asm: asm price bench-quote bench-startup price-startup-control
./bench-quote
./bench-startup 400 ./price ./price-asm ./price-startup-control
# Same raw CLI with integer inverse thresholds and SSE2 candidate generation.
.asm-build/cli-inverse.o: $(ASMDIR)/cli.S
mkdir -p .asm-build
$(CC) -Dquote_asm=quote_threshold -c $< -o $@
price-inverse: .asm-build/cli-inverse.o $(ASMDIR)/experimental/threshold.c $(ASMDIR)/experimental/threshold.h $(ASMKERNEL) $(ASMDIR)/debit_table.inc
$(CC) -O3 -fno-math-errno -fno-asynchronous-unwind-tables -ffp-contract=off $(ASM_LDFLAGS) -Wl,-s $< $(ASMDIR)/experimental/threshold.c $(ASMKERNEL) -o $@
.PHONY: batch check-batch
batch:
$(MAKE) -C $(ASMDIR)/experimental all
check-batch: price-inverse batch
$(MAKE) -C $(ASMDIR)/experimental check
# Byte certificate for the packaged GCC 14.2 lowering. A different compiler
# can legitimately generate different instructions for the equivalent C.
.PHONY: check-inverse-image
check-inverse-image:
$(PYTHON) $(ASMDIR)/check_threshold_bytes.py $(ASMDIR)/experimental/price_batch
# Linux x86-64 executable images. Both are built without invoking a linker.
.PHONY: minelf check-minelf
minelf: price-minelf price-flat .asm-build/exit-minelf
.asm-build/min-compact.o: minelf/compact_source.py minelf/compact.S minelf/direct.py $(ASMDIR)/cli.S $(ASMDIR)/quote.S $(ASMDIR)/root_repair.S
mkdir -p .asm-build
$(PYTHON) minelf/compact_source.py --assembler "$(AS)" $@
.asm-build/min-compact.bin: .asm-build/min-compact.o minelf/direct.py
$(PYTHON) -c 'from pathlib import Path; from minelf.direct import check_relocations; check_relocations(Path("$<"))'
$(OBJCOPY) --only-section=.text --output-target=binary $< $@
price-minelf: .asm-build/min-compact.bin minelf/build.py
$(PYTHON) minelf/build.py --payload $< $@
.asm-build/flat.payload: minelf/direct.py $(ASMDIR)/cli.S $(ASMKERNEL) $(ASMDIR)/debit_table.inc
mkdir -p .asm-build
$(PYTHON) minelf/direct.py $@
price-flat: .asm-build/flat.payload minelf/build.py
$(PYTHON) minelf/build.py --payload $< --entry-offset 176 $@
.asm-build/exit-minelf: minelf/build.py
mkdir -p .asm-build
$(PYTHON) minelf/build.py --exit-only $@
.asm-build/bench-minelf: minelf/bench.c
mkdir -p .asm-build
$(CC) -O2 -std=c11 -Wall -Wextra $< -o $@
check-minelf: minelf price-asm.elf price
$(PYTHON) minelf/check_compact.py price-asm.elf price-minelf --mutation-test
$(PYTHON) minelf/preserve.py --check price-asm.elf price-flat
$(PYTHON) minelf/test_preserve.py price-asm.elf
$(PYTHON) $(ASMDIR)/cli_test.py ./price ./price-minelf
$(PYTHON) $(ASMDIR)/cli_test.py ./price ./price-flat
$(PYTHON) minelf/check_min.py ./price-minelf
.PHONY: check-minelf-runtime proof-minelf-headers proof-minelf proof-minelf-full
check-minelf-runtime: minelf
$(PYTHON) minelf/check_runtime.py
proof-minelf-headers: minelf
$(PYTHON) minelf/check_headers.py --lean $(LEAN) price-minelf price-flat .asm-build/exit-minelf
proof-minelf: check-minelf proof-minelf-headers
$(PYTHON) minelf/proofs.py --lean $(LEAN)
proof-minelf-full: check-minelf proof-minelf-headers
$(PYTHON) minelf/proofs.py --lean $(LEAN) --mathlib "$(MATHLIB)"
~~~
#### `Problem-14-Card-Table.html`
~~~html
The price of a question · Problem 14
The price of a question
Shuffle 26 red cards and 26 black. Each red earns a dollar. Each black costs a dollar. You can stop after any draw and keep the balance.
$0
Changing the offer restarts the same shuffle. The fair prices assume a fresh, unknown deal. Replays let you compare the offers card for card.
What does the best question ask?
Imagine playing with two chances to mark a balance and collecting the better mark. The optimal marking rule uses only cards already drawn. Before the first draw, the dealer tells you which mark to take. A missing mark pays the terminal zero. The dealer splits tied shuffles so each answer comes up exactly half the time.
The last card’s color is also an exactly fair bit. Try both on the same shuffle. Four bits instead let the dealer name a dollar target from 1 through 16. The optimal strategy aims for the peak capped at 16. The next-card offer gives a new clue on every draw.
", page, re.S)
sources = [html.unescape(re.sub(r"<[^>]*>", "", block)).strip() + "\n" for block in blocks]
candidates = [source for source in sources if "#define NUM_CARDS 133787000" in source
and "void handle_work_done" in source and "int skipped[" in source]
if len(candidates) != 1:
parser.error("could not identify the published benchmark code")
original = candidates[0]
print("extracted source SHA-256:", hashlib.sha256(original.encode()).hexdigest())
print("cards_per_color block threads value median_seconds individual_seconds")
for n in args.sizes:
for block in args.blocks:
if n % block:
continue # published program requires exact blocks
for threads in args.threads:
with tempfile.TemporaryDirectory() as tmp:
src = pathlib.Path(tmp) / "khoth.c"
code = original.replace("#define NUM_CARDS 133787000", f"#define NUM_CARDS {n}")
code = code.replace("#define NUM_THREADS 15", f"#define NUM_THREADS {threads}")
code = code.replace("#define BLOCK_SIZE 1000", f"#define BLOCK_SIZE {block}")
src.write_text(code.replace("value=%g", "value=%.16g"))
exe = pathlib.Path(tmp) / "khoth"
subprocess.run(["gcc", "-Ofast", "-march=native", "-pthread", str(src),
"-o", str(exe)], check=True)
timings = []
for _ in range(args.runs):
start = time.perf_counter()
result = subprocess.check_output([str(exe)], timeout=300).decode().strip()
timings.append(time.perf_counter() - start)
print(n, block, threads, result, f"{statistics.median(timings):.6f}",
*(f"{t:.6f}" for t in timings), flush=True)
~~~
#### `baseline/exact-packed.cpp`
~~~cpp
// Exact balanced Shepp urn value. Build with
// c++ -O3 -std=c++17 exact.cpp -lgmpxx -lgmp -o exact
// The argument is the number of cards of EACH color. --boundary prints the
// complete stopping rule. --triangle computes the fraction by the control
// algorithm. See exact.md for the Catalan convolution and complexity.
#include
#include
#include