Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
95 commits
Select commit Hold shift + click to select a range
6094ec9
feat(exactTriangle): relate lopsided queries and matrix products
edemaine Oct 28, 2026
dec963a
feat(exactTriangle): prove modular counts and the selected-prime bound
edemaine Oct 28, 2026
0d8da3e
doc(threeSum): cite the lopsided triangle paper and clarify adaptatio…
edemaine Oct 28, 2026
8d80ecc
doc(bibliography): sort the new paper entry
edemaine Oct 28, 2026
fd69be7
fix(exactTriangle): repair the prime-window header and hashing docume…
edemaine Oct 28, 2026
ce646c7
feat(exactTriangle): split modular queries and recover witnesses
edemaine Oct 28, 2026
2cae26c
doc(threeSum): record finite splitting and recovery milestone
edemaine Oct 28, 2026
dc4206a
refactor(exactTriangle): reuse the natural residue bound and clarify …
edemaine Oct 28, 2026
19ee942
feat(wordram): count Chan–He collisions with native histograms
edemaine Oct 28, 2026
a712205
fix(wordram): preserve collision-counting parameters explicitly
edemaine Oct 28, 2026
4fc6a70
feat(wordram): add native radix sorting and multiplicity arrays
edemaine Oct 28, 2026
4edf0b8
chore(wordram): keep Lean sources non-executable
edemaine Oct 28, 2026
5cbb93d
feat(wordram): compute Chan–He parameters from native input
edemaine Oct 28, 2026
0505439
fix(wordram): repair parameter proof hygiene and ceiling-log docs
edemaine Oct 28, 2026
0e05605
feat(wordram): implement prime tables and collision minimum searches
edemaine Oct 28, 2026
a5a5391
feat(wordram): compute the Chan–He two-prime modulus natively
edemaine Oct 28, 2026
ba4cab2
feat(wordram): construct native Chan–He node outputs
edemaine Oct 28, 2026
b2554d5
fix(wordram): export sorted radix keys from composed contracts
edemaine Oct 28, 2026
36e0f7e
Merge commit 'b2554d58b9eb90291e7d9314128433b62016e203' into t3/nativ…
edemaine Oct 28, 2026
ebe62bc
Merge commit 'ba4cab2a6096c4d692e2d7a75b59d7591ea5162e' into t3/nativ…
edemaine Oct 28, 2026
374795a
Merge commit 'b2554d58b9eb90291e7d9314128433b62016e203' into t3/nativ…
edemaine Oct 28, 2026
712b07d
feat(wordram): implement complete native distinct-position frontend
edemaine Oct 28, 2026
6372d31
fix(wordram): link frontend readback to its native run
edemaine Oct 28, 2026
0781373
Merge commit '6372d314a08ff7215b78425b25315021c0c936a7' into t3/nativ…
edemaine Oct 28, 2026
ceb537f
feat(three-sum): prove complete native Chan-He root traversal
edemaine Oct 28, 2026
f6f22da
test(wordram): remove disconnected native node checks
edemaine Oct 28, 2026
d32859e
refactor(wordram): reuse prime counts and test later acceptance
edemaine Oct 28, 2026
ec8aa56
test(wordram): drop disconnected radix contract example
edemaine Oct 28, 2026
1085648
doc(wordram): explain the Chan-He prime-window interface
edemaine Oct 28, 2026
787aa2c
feat(three-sum): bound charged traversal tree overhead
edemaine Oct 28, 2026
1d150b5
Merge commit 'f6f22dac7018f00793f6aae1aa44bd04ae08cee6' into t3/nativ…
edemaine Oct 28, 2026
eae533d
Merge commit 'd32859e8beea19d17a763e0a241463ad7c7d4aa0' into t3/nativ…
edemaine Oct 28, 2026
5c172a9
Merge commit 'ec8aa561feae957effa539ac6f84d64c5db903c8' into t3/nativ…
edemaine Oct 28, 2026
af8fdb7
Merge commit '108564889ee67ecae0ad1e2e2973aae98b401666' into t3/nativ…
edemaine Oct 28, 2026
a49400c
doc(wordram): record complete bounded Chan-He traversal scope
edemaine Oct 28, 2026
48a0fa3
chore(exactTriangle): merge current main for sibling integration
codex Oct 29, 2026
3fb98bd
chore(exactTriangle): join reviewed query splitting and counting layers
codex Oct 29, 2026
d1bc583
chore(exactTriangle): reconcile modular-hashing integration documenta…
SamuelSchlesinger Oct 29, 2026
c0b0511
chore(exactTriangle): carry hashing integration through query splitting
SamuelSchlesinger Oct 29, 2026
a76a7d3
chore(exactTriangle): carry documentation integration through native …
SamuelSchlesinger Oct 29, 2026
4f6de79
fix(imports): deduplicate aggregate after counting integration
SamuelSchlesinger Oct 29, 2026
02f1b49
fix(imports): deduplicate aggregate after query-splitting integration
SamuelSchlesinger Oct 29, 2026
b17ece3
Merge commit '4f6de797203eb5dac02b2cadd9e8fa33e7427d57' into coordina…
SamuelSchlesinger Oct 29, 2026
e031b72
Merge remote-tracking branch 'origin/main' into coordinator/integrate…
SamuelSchlesinger Oct 29, 2026
b79ae8e
fix(imports): regenerate aggregate after Chan-He parameter integration
SamuelSchlesinger Oct 29, 2026
f219cb7
chore(three-sum): integrate reviewed prime search with parameter supp…
SamuelSchlesinger Oct 29, 2026
ec9351c
chore(three-sum): merge current main before prime-search validation
SamuelSchlesinger Oct 29, 2026
4d3d55a
chore(three-sum): integrate reviewed modulus with refreshed prime search
SamuelSchlesinger Oct 29, 2026
1d7ce92
chore(three-sum): integrate reviewed node packing with refreshed prim…
SamuelSchlesinger Oct 29, 2026
3552eb0
Merge remote-tracking branch 'origin/main' into integrate/1497-remain…
SamuelSchlesinger Oct 29, 2026
5337d45
Merge branch 'integrate/1497-remainingmath-20261029' into integrate/1…
SamuelSchlesinger Oct 29, 2026
eb8f925
perf(three-sum): check native query tests within default heartbeats
SamuelSchlesinger Oct 29, 2026
b94e77f
perf(three-sum): run modulus instance within default heartbeats
SamuelSchlesinger Oct 29, 2026
350a66b
Merge branch 'integrate/1497-remainingmath-20261029' into integrate/1…
SamuelSchlesinger Oct 29, 2026
ab3e96c
chore(integration): reconcile splitting layer with landed hashing parent
SamuelSchlesinger Oct 29, 2026
9c8b9fc
perf(wordram): reduce native parameter proof heartbeat budget
SamuelSchlesinger Oct 29, 2026
0c9b346
Merge remote-tracking branch 'github/main' into coordinator-heartbeat…
SamuelSchlesinger Oct 29, 2026
da6a301
chore(integration): adopt splitting layer after its parent landed
SamuelSchlesinger Oct 29, 2026
452924e
chore(wordram): scope measured parameter proof budget to reduction task
SamuelSchlesinger Oct 29, 2026
6aaf569
Merge commit 'da6a301aca1e0c03e6953b3329474b2236f0fac8' into coordina…
SamuelSchlesinger Oct 29, 2026
170d9eb
Merge remote-tracking branch 'origin/p1469' into integrate/1497-remai…
SamuelSchlesinger Oct 29, 2026
af80519
Merge branch 'integrate/1497-remainingmath-20261029' into integrate/1…
SamuelSchlesinger Oct 29, 2026
e69b812
Merge branch 'integrate/1497-remainingmath-20261029' into integrate/1…
SamuelSchlesinger Oct 29, 2026
0940d1f
Merge commit 'af80519e7bb5034a6d4979ffcb91c653e4c693d4' into coordina…
SamuelSchlesinger Oct 29, 2026
aa7cebd
chore(wordram): regenerate frontend integration imports
SamuelSchlesinger Oct 29, 2026
5265a9b
chore(three-sum): integrate reviewed recursion with initialized frontend
SamuelSchlesinger Oct 29, 2026
7ba74ea
chore(three-sum): include refreshed node-packing supplier
SamuelSchlesinger Oct 29, 2026
06214ec
Merge remote-tracking branch 'origin/main' into integrate/1535-remain…
SamuelSchlesinger Oct 29, 2026
8a81617
Merge remote-tracking branch 'github/main' into coordinator-refresh-1…
SamuelSchlesinger Oct 29, 2026
618654d
Merge commit '8a81617ea81ea15a43e8581ceb848ec31ed2126b' into coordina…
SamuelSchlesinger Oct 29, 2026
5f1d90a
Merge commit '618654db3356a6a45b35091d0b9605c4401c3e61' into coordina…
SamuelSchlesinger Oct 29, 2026
0a6d3b6
Merge commit '618654db3356a6a45b35091d0b9605c4401c3e61' into coordina…
SamuelSchlesinger Oct 29, 2026
3b77142
Merge commit '5f1d90a31b4b247815170813376db6a32e029afc' into coordina…
SamuelSchlesinger Oct 29, 2026
1b2d346
Merge commit '1666428cd' into coordinator-refresh-1527-main
SamuelSchlesinger Oct 29, 2026
48a8d3a
chore(wordram): refresh frontend imports after landed main
SamuelSchlesinger Oct 29, 2026
4b2d75c
Merge remote-tracking branch 'github/main' into coordinator-queue-146…
SamuelSchlesinger Oct 29, 2026
1f57c3c
Merge commit '4b2d75ce50dbca1101868ed3726170770d0a3e77' into coordina…
SamuelSchlesinger Oct 29, 2026
e2bf09d
Merge remote-tracking branch 'github/main' into coordinator-warm-1497
SamuelSchlesinger Oct 29, 2026
4b71a93
doc(roadmap): restore tensor milestone reference
SamuelSchlesinger Oct 29, 2026
6a18c48
Merge commit '4b71a936e4f8f33ff009045bf58d9a1c3d7400c1' into coordina…
SamuelSchlesinger Oct 29, 2026
677ea83
Merge commit '4b71a936e4f8f33ff009045bf58d9a1c3d7400c1' into coordina…
SamuelSchlesinger Oct 29, 2026
24a8774
Merge commit 'a1d1fa882117891cabd7865b108d12b5eb850d5b' into coordina…
SamuelSchlesinger Oct 29, 2026
4cb34a9
doc(roadmap): separate native Chan-He progress from tensor work
SamuelSchlesinger Oct 29, 2026
7023643
Merge commit '4cb34a93df09ff1776a998df7565d98ad7df9644' into coordina…
SamuelSchlesinger Oct 29, 2026
b70f51e
Merge commit '4cb34a93df09ff1776a998df7565d98ad7df9644' into coordina…
SamuelSchlesinger Oct 29, 2026
fa68703
Merge commit '70236432a6cef8644d5256a75edc215df92af844' into coordina…
SamuelSchlesinger Oct 29, 2026
20a40e6
Merge commit '70236432a6cef8644d5256a75edc215df92af844' into coordina…
SamuelSchlesinger Oct 29, 2026
3bb8edf
Merge commit '38f32f97e76ad36666b99d1f0d39a64fc0ef3306' into coordina…
SamuelSchlesinger Oct 29, 2026
16f2809
doc(roadmap): separate initialized frontend progress and references
SamuelSchlesinger Oct 29, 2026
ee6c863
Merge commit 'fa687036fbd8890c3dc9e0f018dd937d471f5b23' into coordina…
SamuelSchlesinger Oct 29, 2026
ad112d3
Merge commit 'cf63e382d02ba396b4f8d460958d70b15735f23e' into coordina…
SamuelSchlesinger Oct 29, 2026
490d996
Merge commit 'ad112d34ed1a803ad492859089800e30b1213541' into coordina…
SamuelSchlesinger Oct 29, 2026
dbf76d0
Merge commit '490d996b7ade2a8b41a8e8c4b7a6f9b5c6008e26' into coordina…
SamuelSchlesinger Oct 29, 2026
5a0fce5
Merge commit 'dbf76d0bcf9e4660026080f44d716a91efbc081b' into coordina…
SamuelSchlesinger Oct 29, 2026
ccc8586
chore(wordram): refresh traversal onto actual frontend parent
SamuelSchlesinger Oct 29, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions Complexity.lean
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ public import Complexity.Algorithms.ThreeSum.ChanHe.Collisions
public import Complexity.Algorithms.ThreeSum.ChanHe.Defs
public import Complexity.Algorithms.ThreeSum.ChanHe.FromNumbers
public import Complexity.Algorithms.ThreeSum.ChanHe.Recursion
public import Complexity.Algorithms.ThreeSum.ChanHe.SelectorBounds
public import Complexity.Algorithms.ThreeSum.ChanHe.Sizes
public import Complexity.Algorithms.ThreeSum.Convolution
public import Complexity.Algorithms.ThreeSum.Defs
Expand Down Expand Up @@ -118,6 +119,8 @@ public import Complexity.Algorithms.WordRAM.PrefixSums.Dynamic
public import Complexity.Algorithms.WordRAM.PrefixSums.Query
public import Complexity.Algorithms.WordRAM.PrefixSums.Tree
public import Complexity.Algorithms.WordRAM.PrefixSums.Update
public import Complexity.Algorithms.WordRAM.PrimeTable
public import Complexity.Algorithms.WordRAM.PrimeTrial
public import Complexity.Algorithms.WordRAM.PriorityQueue.Basic
public import Complexity.Algorithms.WordRAM.PriorityQueue.BinaryHeap
public import Complexity.Algorithms.WordRAM.PriorityQueue.BinaryHeap.Model
Expand All @@ -144,11 +147,67 @@ public import Complexity.Algorithms.WordRAM.RadixSort.Scan
public import Complexity.Algorithms.WordRAM.Stack
public import Complexity.Algorithms.WordRAM.Stack.Controller
public import Complexity.Algorithms.WordRAM.ThreeSum.Cell
public import Complexity.Algorithms.WordRAM.ThreeSum.ChanHe.BucketCounts
public import Complexity.Algorithms.WordRAM.ThreeSum.ChanHe.CollisionTest
public import Complexity.Algorithms.WordRAM.ThreeSum.ChanHe.Collisions
public import Complexity.Algorithms.WordRAM.ThreeSum.ChanHe.Count
public import Complexity.Algorithms.WordRAM.ThreeSum.ChanHe.CountCall
public import Complexity.Algorithms.WordRAM.ThreeSum.ChanHe.CountFrame
public import Complexity.Algorithms.WordRAM.ThreeSum.ChanHe.CountPlace
public import Complexity.Algorithms.WordRAM.ThreeSum.ChanHe.CountPlaceMemory
public import Complexity.Algorithms.WordRAM.ThreeSum.ChanHe.CountTriple
public import Complexity.Algorithms.WordRAM.ThreeSum.ChanHe.Modulus
public import Complexity.Algorithms.WordRAM.ThreeSum.ChanHe.NodeExec
public import Complexity.Algorithms.WordRAM.ThreeSum.ChanHe.NodeInitialize
public import Complexity.Algorithms.WordRAM.ThreeSum.ChanHe.NodeLayout
public import Complexity.Algorithms.WordRAM.ThreeSum.ChanHe.NodeMemory
public import Complexity.Algorithms.WordRAM.ThreeSum.ChanHe.NodeProgram
public import Complexity.Algorithms.WordRAM.ThreeSum.ChanHe.NodeRound
public import Complexity.Algorithms.WordRAM.ThreeSum.ChanHe.NodeSetup
public import Complexity.Algorithms.WordRAM.ThreeSum.ChanHe.NodeSpec
public import Complexity.Algorithms.WordRAM.ThreeSum.ChanHe.Padding
public import Complexity.Algorithms.WordRAM.ThreeSum.ChanHe.Parameters
public import Complexity.Algorithms.WordRAM.ThreeSum.ChanHe.Place
public import Complexity.Algorithms.WordRAM.ThreeSum.ChanHe.PlaceExec
public import Complexity.Algorithms.WordRAM.ThreeSum.ChanHe.PlaceMemory
public import Complexity.Algorithms.WordRAM.ThreeSum.ChanHe.Query
public import Complexity.Algorithms.WordRAM.ThreeSum.ChanHe.Residues
public import Complexity.Algorithms.WordRAM.ThreeSum.ChanHe.Search
public import Complexity.Algorithms.WordRAM.ThreeSum.ChanHe.TraversalAdmitted
public import Complexity.Algorithms.WordRAM.ThreeSum.ChanHe.TraversalCall
public import Complexity.Algorithms.WordRAM.ThreeSum.ChanHe.TraversalChildren
public import Complexity.Algorithms.WordRAM.ThreeSum.ChanHe.TraversalCost
public import Complexity.Algorithms.WordRAM.ThreeSum.ChanHe.TraversalDeliver
public import Complexity.Algorithms.WordRAM.ThreeSum.ChanHe.TraversalEmission
public import Complexity.Algorithms.WordRAM.ThreeSum.ChanHe.TraversalEmissionFrame
public import Complexity.Algorithms.WordRAM.ThreeSum.ChanHe.TraversalExec
public import Complexity.Algorithms.WordRAM.ThreeSum.ChanHe.TraversalFrames
public import Complexity.Algorithms.WordRAM.ThreeSum.ChanHe.TraversalInvariant
public import Complexity.Algorithms.WordRAM.ThreeSum.ChanHe.TraversalLive
public import Complexity.Algorithms.WordRAM.ThreeSum.ChanHe.TraversalLoop
public import Complexity.Algorithms.WordRAM.ThreeSum.ChanHe.TraversalModel
public import Complexity.Algorithms.WordRAM.ThreeSum.ChanHe.TraversalOutput
public import Complexity.Algorithms.WordRAM.ThreeSum.ChanHe.TraversalPending
public import Complexity.Algorithms.WordRAM.ThreeSum.ChanHe.TraversalProgram
public import Complexity.Algorithms.WordRAM.ThreeSum.ChanHe.TraversalResources
public import Complexity.Algorithms.WordRAM.ThreeSum.ChanHe.TraversalRoot
public import Complexity.Algorithms.WordRAM.ThreeSum.ChanHe.TraversalSkip
public import Complexity.Algorithms.WordRAM.ThreeSum.ChanHe.TraversalStack
public import Complexity.Algorithms.WordRAM.ThreeSum.ChanHe.TraversalStep
public import Complexity.Algorithms.WordRAM.ThreeSum.ChanHe.TraversalTime
public import Complexity.Algorithms.WordRAM.ThreeSum.ChanHe.TraversalVisit
public import Complexity.Algorithms.WordRAM.ThreeSum.Fill
public import Complexity.Algorithms.WordRAM.ThreeSum.Frontend
public import Complexity.Algorithms.WordRAM.ThreeSum.Frontend.Arrays
public import Complexity.Algorithms.WordRAM.ThreeSum.Frontend.Bounds
public import Complexity.Algorithms.WordRAM.ThreeSum.Frontend.Execute
public import Complexity.Algorithms.WordRAM.ThreeSum.Frontend.Input
public import Complexity.Algorithms.WordRAM.ThreeSum.Frontend.Layout
public import Complexity.Algorithms.WordRAM.ThreeSum.Frontend.Model
public import Complexity.Algorithms.WordRAM.ThreeSum.Frontend.Program
public import Complexity.Algorithms.WordRAM.ThreeSum.Frontend.Scan
public import Complexity.Algorithms.WordRAM.ThreeSum.Frontend.Select
public import Complexity.Algorithms.WordRAM.ThreeSum.Frontend.Time
public import Complexity.Algorithms.WordRAM.ThreeSum.Host.Loop
public import Complexity.Algorithms.WordRAM.ThreeSum.Host.Prepare
public import Complexity.Algorithms.WordRAM.ThreeSum.Host.Program
Expand Down Expand Up @@ -1717,6 +1776,7 @@ public import Complexity.Computability.WordRAM.Dynamic
public import Complexity.Computability.WordRAM.ExactNotation
public import Complexity.Computability.WordRAM.Function
public import Complexity.Computability.WordRAM.Generic
public import Complexity.Computability.WordRAM.GhostLoop
public import Complexity.Computability.WordRAM.Heap
public import Complexity.Computability.WordRAM.ListArray
public import Complexity.Computability.WordRAM.MapOp
Expand Down
64 changes: 64 additions & 0 deletions Complexity/Algorithms/ThreeSum/ChanHe/SelectorBounds.lean
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/-
Copyright (c) 2026 Erik Demaine. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Erik Demaine
-/

module
-- upstream: candidate

public import Complexity.Algorithms.ThreeSum.ChanHe.Defs

/-!
# Size bounds for the Chan–He selectors, including their default

Bounding the modulus does not require either filter to succeed: a failed filter returns one.
These bounds therefore apply to native execution with arbitrary nonnegative collision thresholds,
including empty input sets. They do not assert the collision-shrinking property of a successful
search.

## Main results

* `minOrOne_filter_bounds`: a positive bounded candidate set keeps its filtered selector bounded.
* `modulus_bounds_of_candidates`: both selections, including defaults, have product in `[1,m²]`.

The bounds are original elementary consequences of the existing finite selectors.
-/

@[expose] public section

namespace Cslib.Algorithms.ThreeSum.ChanHe

open Finset

/-- Filtering positive candidates bounded by `m` keeps the default-one selector in `[1,m]`.
The candidate set and the filtered set may both be empty. -/
theorem minOrOne_filter_bounds {Q : Finset ℕ} {m : ℕ} (hm : 1 ≤ m)
(hpos : ∀ q ∈ Q, 1 ≤ q) (hle : ∀ q ∈ Q, q ≤ m)
(A : ℕ → Prop) [DecidablePred A] :
1 ≤ minOrOne {q ∈ Q | A q} ∧ minOrOne {q ∈ Q | A q} ≤ m := by
let S := {q ∈ Q | A q}
by_cases h : S.Nonempty
· have hmem : S.min' h ∈ Q := (mem_filter.mp (min'_mem S h)).1
change 1 ≤ minOrOne S ∧ minOrOne S ≤ m
rw [minOrOne, dite_eq_left h]
exact ⟨hpos _ hmem, hle _ hmem⟩
· change 1 ≤ minOrOne S ∧ minOrOne S ≤ m
rw [minOrOne, dite_eq_right h]
exact ⟨le_rfl, hm⟩

/-- Positive bounded candidates bound the modulus regardless of whether either filter succeeds.
This is a size bound only; no magnitude or successful-search premise is needed. -/
theorem modulus_bounds_of_candidates {Q : Finset ℕ} {m : ℕ} (hm : 1 ≤ m)
(hpos : ∀ q ∈ Q, 1 ≤ q) (hle : ∀ q ∈ Q, q ≤ m)
(Λ : ℕ) (S₁ S₂ S₃ : Finset ℤ) :
1 ≤ modulus Q Λ S₁ S₂ S₃ ∧ modulus Q Λ S₁ S₂ S₃ ≤ m ^ 2 := by
have hp : 1 ≤ firstP Q Λ S₁ S₂ S₃ ∧ firstP Q Λ S₁ S₂ S₃ ≤ m :=
minOrOne_filter_bounds hm hpos hle _
have hq : 1 ≤ secondP Q Λ S₁ S₂ S₃ (firstP Q Λ S₁ S₂ S₃) ∧
secondP Q Λ S₁ S₂ S₃ (firstP Q Λ S₁ S₂ S₃) ≤ m :=
minOrOne_filter_bounds hm hpos hle _
exact ⟨Nat.mul_le_mul hp.1 hq.1,
(Nat.mul_le_mul hp.2 hq.2).trans_eq (pow_two m).symm⟩

end Cslib.Algorithms.ThreeSum.ChanHe
224 changes: 224 additions & 0 deletions Complexity/Algorithms/WordRAM/PrimeTable.lean
Original file line number Diff line number Diff line change
@@ -0,0 +1,224 @@
/-
Copyright (c) 2026 Erik Demaine. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Erik Demaine
-/

module
-- upstream: candidate

public import Complexity.Algorithms.WordRAM.PrimeTrial
public import Mathlib.NumberTheory.PrimeCounting

/-!
# Native prime tables

This fixed program tests every candidate through the supplied bound, writes its primality
bit, and counts the primes. Trial division, table addresses, writes and loops are charged.
There is no primality oracle or assumed sieve.

## Main definitions

* `PrimeTable.program`: the complete native table builder.
* `PrimeTable.memory`: its output bitmap and memory frame.

## Main results

* `PrimeTable.exec`: exact bitmap and prime count in an explicit quadratic instruction bound.
-/

@[expose] public section

namespace Cslib.Algorithms.WordRAM.PrimeTable

open Cslib.WordRAM
open Finset

/-- Registers of the trial-division subroutine. -/
def trialRegisters (i : Fin 6) : Fin 15 := ⟨i.val, by omega⟩

private theorem trial_injective : Function.Injective trialRegisters := by
intro i j h
apply Fin.ext
exact congrArg (fun i : Fin 15 => i.val) h

/-- Current trial-division candidate. -/
abbrev arg : Fin 15 := 0
/-- Current candidate's primality bit. -/
abbrev flag : Fin 15 := 2
/-- Largest candidate. -/
abbrev limit : Fin 15 := 6
/-- Output bitmap base. -/
abbrev base : Fin 15 := 7
/-- First candidate not yet written. -/
abbrev cursor : Fin 15 := 8
/-- Address scratch. -/
abbrev addr : Fin 15 := 9
/-- Number of primes written. -/
abbrev count : Fin 15 := 10
/-- One past the largest candidate. -/
abbrev stop : Fin 15 := 11
/-- Constant one. -/
abbrev one : Fin 15 := 12
/-- Constant zero. -/
abbrev zero : Fin 15 := 13
/-- Constant two. -/
abbrev two : Fin 15 := 14

/-- Handle zero and one directly; test all larger candidates by charged native trial division. -/
def test : Code .standard 15 :=
.branch (.lt cursor two) (ram[ flag ← #0 ])
(.seq (ram[ arg ← cursor ]) (PrimeTrial.program.rename trialRegisters))

/-- Test, write the bit, update the count, and advance the candidate. -/
def body : Code .standard 15 :=
.seq test (ram[ addr ← base + cursor; *addr ← flag;
count ← count + flag; cursor ← cursor + one ])

/-- A finite native prime-table program with its bound and base supplied in registers. -/
def program : Code .standard 15 :=
.seq (ram[ one ← #1; zero ← #0; two ← #2; cursor ← #0; count ← #0;
stop ← limit + one ]) (.loop (.lt cursor stop) body)

/-- The first `k` primality bits, preserving all other memory cells. -/
def memory (mem : ℕ → ℕ) (base k : ℕ) : ℕ → ℕ :=
fun a => if base ≤ a ∧ a < base + k then if (a - base).Prime then 1 else 0 else mem a

private theorem memory_zero (mem : ℕ → ℕ) (base : ℕ) : memory mem base 0 = mem := by
funext a
simp [memory]

private theorem memory_succ (mem : ℕ → ℕ) (base k : ℕ) :
memory mem base (k + 1) = Function.update (memory mem base k)
(base + k) (if k.Prime then 1 else 0) := by
funext a
by_cases ha : a = base + k
· subst a
simp [memory]
· rw [Function.update_of_ne ha]
have h : (base ≤ a ∧ a < base + (k + 1)) ↔ (base ≤ a ∧ a < base + k) := by omega
simp only [memory, h]

private theorem exec_test {w m : ℕ} (x : Data 15) (htwo : x.regs two = 2)
(hbound : x.regs cursor ≤ m) (hfit : Fits w (m + 3)) :
∃ y, ExecWithin w test x y (7 * m + 9) ∧
y.regs flag = (if (x.regs cursor).Prime then 1 else 0) ∧ y.mem = x.mem ∧
∀ i, 6 ≤ i.val → y.regs i = x.regs i := by
by_cases hp : x.regs cursor < 2
· have hnp : ¬(x.regs cursor).Prime := fun h => by have := h.two_le; omega
refine ⟨x.set flag 0, ?_, by simp [hnp], rfl, ?_⟩
· exact (ExecWithin.branch_pos (by simpa only [Cond.holds_lt, htwo] using hp)
(ExecWithin.const (fits_zero w))).mono (by omega)
· intro i hi
have hne : i ≠ flag := by intro h; subst i; change 6 ≤ 2 at hi; omega
simp only [Data.set_regs, Function.update_of_ne hne]
· let p := x.set arg (x.regs cursor)
have hcopy : ExecWithin (B := .standard) w (ram[ arg ← cursor ]) x p 1 :=
ExecWithin.copy
obtain ⟨a, ha, haf, haa, ham⟩ := PrimeTrial.exec (p.comap trialRegisters)
(by change 2 ≤ x.regs cursor; omega)
(hfit.of_le (by change x.regs cursor + 2 ≤ m + 3; omega))
let y := a.extend trialRegisters p
have hf : y.regs flag = a.regs PrimeTrial.flag := by
change Function.extend trialRegisters a.regs p.regs (trialRegisters PrimeTrial.flag) = _
exact trial_injective.extend_apply _ _ _
refine ⟨y, ?_, hf.trans haf, ham, ?_⟩
· exact (ExecWithin.branch_neg (by simpa only [Cond.holds_lt, htwo] using hp)
(hcopy.seq (ha.rename trial_injective))).mono (by
change 1 + (7 * (x.regs cursor - 2) + 6) + 2 ≤ 7 * m + 9
omega)
· intro i hi
change Function.extend trialRegisters a.regs p.regs i = x.regs i
rw [Function.extend_apply']
· have hne : i ≠ arg := by intro h; subst i; change 6 ≤ 0 at hi; omega
exact Function.update_of_ne hne _ _
· rintro ⟨j, hj⟩
have := congrArg Fin.val hj
dsimp [trialRegisters] at this
omega


/-- Write every primality bit through `m`, count exactly `Nat.primesLE m`, and preserve
all cells outside the bitmap. Trial division gives the explicit quadratic bound
`(m+1)(7m+15)+8`; the final halt is excluded. -/
theorem exec {w : ℕ} (x : Data 15)
(hfit : Fits w (x.regs limit + 3))
(haddr : Fits w (x.regs base + (x.regs limit + 1))) :
∃ y, ExecWithin w program x y ((x.regs limit + 1) * (7 * x.regs limit + 15) + 8) ∧
y.mem = memory x.mem (x.regs base) (x.regs limit + 1) ∧
y.regs count = #(Nat.primesLE (x.regs limit)) ∧
y.regs limit = x.regs limit ∧ y.regs base = x.regs base := by
let m := x.regs limit
let I (y : Data 15) : Prop := y.regs limit = m ∧ y.regs base = x.regs base ∧
y.regs stop = m + 1 ∧ y.regs one = 1 ∧ y.regs zero = 0 ∧ y.regs two = 2 ∧
y.regs cursor ≤ m + 1 ∧ y.regs count = Nat.primeCounting' (y.regs cursor) ∧
y.mem = memory x.mem (x.regs base) (y.regs cursor)
have hbody (y : Data 15) (hy : I y) (hc : (Cond.lt cursor stop).Holds y) :
∃ q, ExecWithin w body y q (7 * m + 13) ∧ I q ∧
m + 1 - q.regs cursor < m + 1 - y.regs cursor := by
obtain ⟨hl, hb, hs, ho, hz, ht, hi, hcount, hm⟩ := hy
have hlt : y.regs cursor < m + 1 := by simpa only [Cond.holds_lt, hs] using hc
obtain ⟨z, he, hzf, hzm, hzr⟩ := exec_test y ht (show y.regs cursor ≤ m by omega) hfit
have hzb : z.regs base = x.regs base := (hzr base (by decide)).trans hb
have hzi : z.regs cursor = y.regs cursor := hzr cursor (by decide)
have hzc : z.regs count = Nat.primeCounting' (y.regs cursor) :=
(hzr count (by decide)).trans hcount
have hzo : z.regs one = 1 := (hzr one (by decide)).trans ho
have hzf_le : z.regs flag ≤ 1 := by rw [hzf]; split_ifs <;> omega
have ha : Fits w (z.regs base + z.regs cursor) := haddr.of_le (by rw [hzb, hzi]; omega)
have hn : Fits w (z.regs cursor + 1) := hfit.of_le (by rw [hzi]; change _ ≤ m + 3; omega)
have hct : Fits w (z.regs count + z.regs flag) := hfit.of_le (by
rw [hzc]
have hle : Nat.primeCounting' (y.regs cursor) ≤ y.regs cursor :=
Nat.count_le Nat.Prime
change _ ≤ m + 3
omega)
refine ⟨?q, ?run, ?inv, ?decrease⟩
case run =>
have htail : ExecWithin w (ram[ addr ← base + cursor; *addr ← flag;
count ← count + flag; cursor ← cursor + one ]) z ?q 4 := by
ram_eval [ha, hn, hct, hzo]
exact (he.seq htail).mono (by omega)
case inv =>
refine ⟨?_, ?_, ?_, ?_, ?_, ?_, ?_, ?_, ?_⟩
· simpa +decide [Function.update_apply] using (hzr limit (by decide)).trans hl
· simpa +decide [Function.update_apply] using hzb
· simpa +decide [Function.update_apply] using (hzr stop (by decide)).trans hs
· simpa +decide [Function.update_apply] using hzo
· simpa +decide [Function.update_apply] using (hzr zero (by decide)).trans hz
· simpa +decide [Function.update_apply] using (hzr two (by decide)).trans ht
· simpa +decide [Function.update_apply, hzi] using Nat.succ_le_of_lt hlt
· change z.regs count + z.regs flag = Nat.primeCounting' (z.regs cursor + 1)
rw [hzc, hzf, hzi]
simp only [Nat.primeCounting', Nat.count_succ]
· change Function.update z.mem (z.regs base + z.regs cursor) (z.regs flag) =
memory x.mem (x.regs base) (z.regs cursor + 1)
rw [hzm, hm, hzb, hzi, hzf, ← memory_succ]
case decrease =>
change m + 1 - (z.regs cursor + 1) < m + 1 - y.regs cursor
rw [hzi]
omega
let x₀ := (((((x.set one 1).set zero 0).set two 2).set cursor 0).set count 0).set stop (m + 1)
have hx₀ : I x₀ := by
simp +decide [I, x₀, m, limit, base, stop, one, zero, two, cursor, count,
Nat.primeCounting', Nat.count_zero, memory_zero]
obtain ⟨y, he, hy, hc⟩ := ExecWithin.loop_invariant I
(fun y => m + 1 - y.regs cursor) hbody hx₀
obtain ⟨hl, hb, hs, ho, hz, ht, hi, hcount, hm⟩ := hy
have hend : y.regs cursor = m + 1 := by
simp only [Cond.holds_lt, hs] at hc
omega
have h1 : Fits w 1 := hfit.of_le (by omega)
have h2 : Fits w 2 := hfit.of_le (by omega)
have hstop : Fits w (x.regs limit + 1) := hfit.of_le (by omega)
have hinit : ExecWithin (B := .standard) w
(ram[ one ← #1; zero ← #0; two ← #2; cursor ← #0; count ← #0;
stop ← limit + one ]) x x₀ 6 := by
ram_eval [x₀, m, h1, h2, hstop, limit, base, stop, one, zero, two, cursor, count, Fin.mk.injEq]
refine ⟨y, ?_, by simpa only [hend] using hm, ?_, hl, hb⟩
· have hi₀ : x₀.regs cursor = 0 := rfl
have hcost : 7 * m + 13 + 2 = 7 * m + 15 := by omega
exact (hinit.seq he).mono (by rw [hi₀, Nat.sub_zero, hcost]; dsimp only [m]; omega)
· rw [hcount, hend, Nat.primesLE_card_eq_primeCounting, Nat.primeCounting]

end Cslib.Algorithms.WordRAM.PrimeTable
Loading
Loading