# Structured fraction limbs for GMP 6.3.0 The proposed enhancement is [gmp-6.3.0-structured-fraction-limbs.patch](patches/gmp-6.3.0-structured-fraction-limbs.patch), one combined change against stock GMP 6.3.0. It replaces repeated division through zero padding with reciprocal-prefix growth using multiplication, and fills the remaining output directly when a remainder proves a terminating or repeating state. On the reference 64-bit ARM host, targeted short-dividend cases are **5.34–39.10 times faster than stock GMP**. Generic short inputs also improve, by **1.25–6.89 times**. The largest measured slowdowns are **2.43% below the fraction-generation threshold** and **2.73% on full-length dividends**. These are conditional microbenchmark results, not an application-wide speedup. The proposed source was built and tested in native and portable configurations. The consolidated patch produces the same reviewed source files as the historical component series used for those measurements and tests; the [equivalence record](results/consolidated-patch-check.json) checks this explicitly. The distributable bundle includes source and evidence. A fresh run recreates build trees and full test logs. ## From serial division to structured growth GMP stores large numbers in machine-sized chunks called limbs. A limb is a digit in base `B`; on the measured build, `B = 2^64`. When `mpf_div_ui` needs more quotient limbs than its input provides, stock GMP divides a dividend padded with zero limbs. The enhancement first divides the existing input limbs. A zero remainder proves that the entire fraction tail is zero, so it can be filled immediately. Otherwise, for sufficiently long tails, a helper generates the fraction limbs from an exact reciprocal prefix. If `B^k = U*v + rho`, the prefix `U` and its one-limb remainder describe the next block. With `B^j = U_j*v + rho_j`, ```text floor(B^(k+j) / v) = U*B^j + rho*U_j + floor(rho*rho_j / v). ``` Single-limb multiplication and a bounded carry construct that block. The helper grows half the reciprocal in the output workspace, then incorporates the actual numerator remainder using the same identity: ```text floor(rem*B^k / v) = rem*U + floor(rem*rho / v). ``` The remainder describes what comes next. The opportunity is to reduce arithmetic dependencies while retaining the complete output required by the API. The running time remains O(n) in output limbs. ## One small branch inside the enhancement The helper computes `B = seed*v + rho` for its first reciprocal limb. Let `rem` be the incoming numerator remainder, with `0 < rem < v`. * If `rho == 0`, then `rem*B = (rem*seed)*v`. The first fraction limb is `rem*seed`; every following limb is zero. * If `rho == 1`, then `rem*B = (rem*seed)*v + rem`. The remainder is unchanged, so that same limb repeats throughout the result. The product fits in one limb because `rem*seed < B`. The patch saves it before filling, since the fill overwrites the reciprocal seed's location: ```c if (rho <= 1) { c = rem * qp[l - 1]; MPN_FILL (qp, n - 1, rho ? c : CNST_LIMB (0)); qp[n - 1] = c; return; } ``` Powers of two such as 8 give the terminating case. On the tested 64-bit limb build, divisors such as 3, 5 and 17 give the repeating case. Recognition uses a remainder already computed by the helper; it needs no factorization, cycle search, additional division or allocation. Other remainders use the general reciprocal-prefix growth path. The enhancement uses a threshold of 24 fraction limbs and a no-nails restriction; the caller's alias handling and sign/exponent completion remain in force. ## ARM64 measurements against stock GMP Times below are nanoseconds per call, the median of two invocations' per-round medians. Each invocation used a different input/order seed and 15 shuffled rounds. The actual fraction-limb count is shown; GMP's internal precision includes an extra limb beyond the requested precision used by this harness. Speedups divide stock time by proposed time before display rounding. | Divisor | Fraction limbs | Stock GMP 6.3.0 | Proposed enhancement | Speedup over stock | |---:|---:|---:|---:|---:| | 8 | 25 | 82.6 | 15.4 | 5.36x | | 8 | 1,025 | 3,427.7 | 112.5 | 30.46x | | 8 | 16,385 | 54,984.4 | 1,460.0 | 37.66x | | 3 | 25 | 82.7 | 15.4 | 5.37x | | 3 | 1,025 | 3,434.6 | 113.4 | 30.28x | | 3 | 16,385 | 55,000.0 | 1,493.7 | 36.82x | | 10 | 25 | 83.3 | 66.0 | 1.26x | | 10 | 1,025 | 3,446.3 | 603.3 | 5.71x | | 10 | 16,385 | 55,015.6 | 8,263.7 | 6.66x | The complete grid contains 73 fixtures per run. The following six families partition that grid; none are omitted. Ranges cover separate per-run ratios across both final runs, not confidence intervals or workload averages. Slowdowns are the maximum observed in the family. | Input family | Cases per run | Proposed enhancement versus stock | |---|---:|---| | Targeted short inputs with fixed or terminating states, at least 24 fraction limbs | 24 | 5.34–39.10x faster | | Generic short inputs, divisors 7, 10 and ULONG_MAX−58, at least 24 fraction limbs | 12 | 1.25–6.89x faster | | Positive fraction tails below the threshold | 9 | Up to 2.43% slower | | Full-length dividends | 10 | Up to 2.73% slower | | Exact division, zero incoming remainder | 8 | 14.68–35.95x faster | | Half-length dividends | 10 | 1.25–1.95x faster | Half-length dividends benefit less because the existing input still needs to be divided. Within that family, the fixed-state cases improve by 1.90–1.95x and generic cases by 1.25–1.72x. The [stock-comparison summary](results/stock-comparison.txt) and [machine-readable record](results/stock-comparison.json) retain all 146 per-run records, per-family ranges and representative table calculations. An identical-code A/A control used the same output buffer and fixtures, but made every method label execute the same function. The proposed-versus-stock label comparison showed changes from 3.64% faster to 3.10% slower despite identical code. These are observed timing differences, not confidence intervals or proof that the enhancement has no overhead. The maximum gap between any two of the six labels was 4.80%; that is a different comparison. The [raw A/A data](results/states-aa.csv) are retained, and the provenance appendix explains the label mapping. ## Native x86-64 replication The same runner and fixture grid ran on an Intel Xeon Platinum 8488C in an EC2 `c7i.large` VM with Amazon Linux 2023 and GCC 11.5.0. Both builds used the same GMP-selected compiler flags, with 64-bit limbs, no nails and no LTO. The two timing runs and identical-code control each used 15 shuffled rounds across 73 cases. Targeted short inputs improved **3.77–12.00×** versus stock, and generic short inputs improved **1.29–7.55×**. The largest observed slowdowns were **0.77%** below the threshold and **2.04%** on full-length dividends. The slowest full-length case was 2.16% faster in the other run. The x86-64 identical-code control showed time differences between 4.16% faster and 2.65% slower. The short-input gains held on both hosts, with a smaller targeted range on the Xeon. The x86-64 run passed all 54,264 exact comparisons and the sanitizer check. Its native and portable/assertion GMP builds each passed 178 tests with one skip. [Cross-host comparison](results/x86-64-stock-comparison.txt) · [Raw timings, validation and build metadata](results/x86-64-evidence.tar.gz) ## ARM64 correctness and review * Six independently compiled benchmark methods passed **54,264 exact comparisons** across 4,522 fixtures. Comparisons cover every live limb, signed size and exponent, including aliasing, oversized inputs, positive/negative inputs, zero/exact results, odd/even sizes and threshold boundaries. [Log](results/exact-checks.txt). * The fixed-state regression tests include 24 deterministic cases for `7/8` and `2/3`, both signs, alias and separate outputs, and actual fraction lengths 23/24/25. These use explicit limb-pattern expectations and GMP's reference division checker. Remainders greater than one specifically catch overwriting the seed before scaling it. * Proposed native GMP build: **179 tests, 178 passed, one skipped, zero failures**. [Metadata](results/validation-native.json). * Proposed `--disable-assembly --enable-assert` build: **179 tests, 178 passed, one skipped, zero failures**. [Metadata](results/validation-portable.json). Both skips are the platform-dependent `t-addaddmul` test. * AddressSanitizer and UndefinedBehaviorSanitizer: all 54,264 exact comparisons passed. The changed C implementations and harness were instrumented; the common GMP static library was not. [Log](results/sanitizers.txt). * The clean full builds verify the measured division source and regression-test source byte for byte. The [consolidation check](results/consolidated-patch-check.json) separately verifies that the combined review patch reproduces the final component-series source. See [independent review](REVIEW.md) for the arithmetic and benchmark audit; that record retains historical component names. ## Reproducing the study Use the fresh-directory command in [the reviewer guide](README.md). It performs the same six-method comparison, exact checks, native and portable assertion suites, and A/A control. It captures new results and provenance without replacing these reference measurements. The runner applies the historical component series, whose final source is byte-identical to applying the consolidated patch; it preserves that sequence to reproduce the measured experiment. The original measurements used GMP 6.3.0, macOS 27.2.1 arm64, 64-bit limbs, Apple clang 21.0.0 (invoked as `gcc`), and `-O2 -pedantic -march=armv8-a`. CPU model lookup was unavailable in the sandbox. There was no CPU affinity pinning. [build.json](build.json) retains the original commands and source, header, executable, library and archive hashes. Original machine paths in that file are historical records, not commands to copy onto another machine. The final benchmark used the same immutable input and destination buffer for every method in a case. Each timed batch lasted at least 1 ms; generation, checks, and checksums were outside the timed loop. Every timed result was checked against stock. No LTO was used. The summary validates the complete fixture grid, unique rounds, minimum batch duration and matching output hashes. ## Boundaries The benchmark is hot, repeated-input, single-threaded library work on one host per architecture. It does not measure cold caches, application speedup, changing-divisor throughput, or how frequently real workloads hit these remainder classes. The diagnostic short-input fixtures deliberately require a nontrivial incoming remainder where possible. They establish conditional performance, not application-wide hit rates. No native 32-bit run was available. The portable build still uses this host's 64-bit limbs. The benchmark runner supports 64-bit limbs, 64-bit `unsigned long`, no nails, and no LTO. The fraction threshold has not been tuned across architectures, and the helper's documented constraints still apply to manual threshold overrides. Longer-period detection, rational summation and other APIs remain outside the proposed change. No novelty, universal-optimality or GMP project endorsement is claimed. ## Appendix: provenance and reproduction labels This independent study from mikedotexe was developed with Claude and Codex. The reciprocal-prefix implementation originated in the supplied Claude archive; fixed-state handling and comparative validation were developed during the subsequent collaborative study. The original zip and its 20 extracted files were preserved. These stages are consolidated into one proposed contribution against stock GMP. The historical application order is **0001 → release-tarball test registration → 0003**. The runner retains it to reproduce the original experiment. The combined review patch includes the final C source changes and test registration in `Makefile.am`; [consolidated-patch-check.json](results/consolidated-patch-check.json) records the equivalence of those three files. Release tarballs also need the [generated `Makefile.in` companion](../claude/gmp-patch/patches/tarball-only/tests-mpf-Makefile.in.patch). The runner applies that companion automatically. | Label in raw records | Implementation | |---|---| | `stock` | Stock GMP 6.3.0 baseline. | | `claude` | Intermediate reciprocal-prefix implementation from the supplied archive. | | `zero` | Exploratory terminating-state-only variant. | | `repeat` | Exploratory repeating-state-only variant. | | `fixed` | Final proposed enhancement, including reciprocal-prefix growth and combined fixed-state fill. | | `split` | Exploratory variant with separate zero and repeated-value fills. | The final public comparison is `stock` versus `fixed` in runs 4 and 5. [summary.csv](results/summary.csv) and [summary.txt](results/summary.txt) preserve all six labels and intermediate comparison columns for auditability; `stock_over_fixed` is the public comparison ratio. In the A/A run all labels call the intermediate `claude` function, so neither the `stock` nor `fixed` label describes the code executed in that control. Initial exploratory runs used separate output allocations per method. They showed large exact-division control swings and suggested a substantial advantage for explicit zero-fill. Repeating with one shared output buffer removed those large swings and most of that apparent advantage. The split-fill candidate still wins locally, about 5–6% for divisor 8 at 1,025 fraction limbs, but loses about 10% at 65 fraction limbs and has inconsistent large-buffer gains. There was no consistent advantage across the tested sizes to justify its extra branch, so the smaller combined-fill implementation was selected. Runs 1–3 are exploratory; only runs 4–5 support the final tables. The archive also contains pairwise rational summation and an online binary-counter accumulator. They are separate scheduling ideas and are not part of this contribution. Distinct denominators alone do not make a running total grow linearly in bit size: `sum(1/[i(i+1)], i=1..n) = n/(n+1)` is a counterexample. Pairwise addition helps when operand growth and cancellation patterns make its arithmetic schedule advantageous. The archive's documentation patch was not included in the proposed code build. The archive's other-division benchmark uses a different numerator/precision setup from its main `mpf_div_ui` comparison and does not validate every alternative in the same way. A broad claim that no other GMP routine can compete should not be inferred from those rows. The results reported here compare the same `mpf_div_ui` contract, inputs, precision and complete output against stock GMP.