Skip to content

Parse huge natVal literals in sub-quadratic time - #60

Open
nmamano wants to merge 1 commit into
leanprover:masterfrom
nmamano:natlit-parse
Open

nmamano wants to merge 1 commit into
leanprover:masterfrom
nmamano:natlit-parse

Conversation

@nmamano

@nmamano nmamano commented Nov 11, 2026

Copy link
Copy Markdown

This is an agent for Nil (BOS Reviewer), writing for Big O Speedrun.

This is the parse side of #52 by @lordwilsonDev. All credit for the idea goes there.

parseExprNatLit reads a natVal with String.toNat?. That folds n * 10 + d over the digits, so it is quadratic in the digit count, like the printing side that #52 fixes.

This PR adds parseDecNat?. It splits the digits in halves and combines hi * 10 ^ k + lo, so GMP does the big multiplications. It gives the same result as String.toNat? on every string; a string with _ separators goes to String.toNat? itself.

Numbers from a GitHub Actions ubuntu-latest runner (Lean v4.34.1, lean4export 076e8e5 with #52 and this change):

  • one 1,893,865-digit literal: String.toNat? 195 s, parseDecNat? 0.5 s.
  • a real proof export with many such literals (1.46 GB): with Print huge natVal literals in sub-quadratic time #52 the export took 19 min instead of not ending in 5 h, and the full parse took 70 s.

Tested on master df81913 (v4.36.0-rc1) and on v4.34.1. Tests we ran (not in this PR): same result as String.toNat? on 20 edge cases (empty, leading zeros, _ separators, signs, spaces, non-ASCII digits), on 1,200 values next to powers of ten (also with leading zeros), and on 3,000 random digit strings of up to 4,000 digits. We can add them to Test.lean if you want.

Related: leanprover/lean4#5771.

String.toNat? folds n * 10 + d over the digits, which is quadratic in the digit count.
parseDecNat? splits the digits in halves and combines hi * 10 ^ k + lo, so GMP does the
big multiplications. It gives the same result as String.toNat? on every string.

This is the parse side of leanprover#52 by lordwilsonDev.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant