tla-ts 0.0.9 → 0.0.10-dev.06b481ee0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (631) hide show
  1. package/README.md +30 -1
  2. package/dist/compile.cjs +23 -0
  3. package/dist/compile.js +23 -0
  4. package/dist/deciders.cjs +41 -37
  5. package/dist/deciders.js +48 -44
  6. package/dist/index.cjs +1 -1
  7. package/dist/index.d.cts +122 -12
  8. package/dist/index.d.ts +122 -12
  9. package/dist/index.js +1 -1
  10. package/dist/parallel-worker.cjs +1 -1
  11. package/dist/parallel-worker.js +1 -1
  12. package/dist/prove-worker.cjs +1 -1
  13. package/dist/prove-worker.js +1 -1
  14. package/dist/prove.cjs +2746 -410
  15. package/dist/prove.js +2745 -409
  16. package/dist/run.cjs +144 -31
  17. package/dist/run.js +144 -31
  18. package/dist/tlapm.cjs +2 -2
  19. package/dist/tlapm.js +2 -2
  20. package/dist/transfer.cjs +134 -104
  21. package/dist/transfer.js +134 -104
  22. package/dist/worker.cjs +7 -7
  23. package/dist/worker.js +7 -7
  24. package/package.json +3 -1
  25. package/src/ast.ts +56 -60
  26. package/src/bags.ts +128 -110
  27. package/src/builtins.ts +31 -77
  28. package/src/bundled-modules.ts +1 -8
  29. package/src/check-failure.ts +118 -0
  30. package/src/check-trace.ts +320 -0
  31. package/src/check.ts +1156 -888
  32. package/src/cli/options.ts +12 -32
  33. package/src/cli/run.ts +0 -2
  34. package/src/cli/runtime-invariants.ts +100 -0
  35. package/src/cli/shared.ts +19 -12
  36. package/src/cli/tlapm.ts +433 -82
  37. package/src/cli/tlc-arguments.ts +652 -0
  38. package/src/cli/tlc-output.ts +701 -0
  39. package/src/cli/tlc-usage.ts +360 -0
  40. package/src/cli/tlc.ts +330 -659
  41. package/src/cli/typescript.ts +23 -0
  42. package/src/cli/xml-exporter.ts +27 -49
  43. package/src/cli.ts +0 -1
  44. package/src/codegen.ts +217 -82
  45. package/src/config.ts +140 -109
  46. package/src/coverage.ts +1019 -0
  47. package/src/dependencies.ts +101 -66
  48. package/src/dfid.ts +683 -0
  49. package/src/environment-config.ts +315 -0
  50. package/src/environment.ts +263 -370
  51. package/src/errors.ts +107 -57
  52. package/src/evaluate.ts +898 -369
  53. package/src/exit-codes.ts +63 -13
  54. package/src/fingerprints.ts +75 -11
  55. package/src/index.ts +3 -0
  56. package/src/instances.ts +137 -22
  57. package/src/java-hash.ts +21 -0
  58. package/src/java-overrides.ts +6 -21
  59. package/src/json-reader.ts +455 -0
  60. package/src/json.ts +252 -139
  61. package/src/levels.ts +231 -154
  62. package/src/lexer.ts +83 -101
  63. package/src/liveness-checker.ts +743 -322
  64. package/src/liveness.ts +230 -133
  65. package/src/obligations/action.ts +17 -44
  66. package/src/obligations/anonymize.ts +120 -95
  67. package/src/obligations/enabled-axioms.ts +218 -0
  68. package/src/obligations/equality.ts +1 -3
  69. package/src/obligations/expression.ts +37 -26
  70. package/src/obligations/format.ts +0 -10
  71. package/src/obligations/generate.ts +66 -64
  72. package/src/obligations/index.ts +39 -20
  73. package/src/obligations/levels.ts +27 -18
  74. package/src/obligations/module.ts +28 -55
  75. package/src/obligations/normalize.ts +31 -41
  76. package/src/obligations/operators.ts +0 -3
  77. package/src/obligations/pragma.ts +52 -24
  78. package/src/obligations/printer.ts +94 -63
  79. package/src/obligations/proof.ts +3 -6
  80. package/src/obligations/regroup.ts +0 -5
  81. package/src/obligations/simplify.ts +57 -63
  82. package/src/obligations/source.ts +121 -95
  83. package/src/obligations/subexpression.ts +49 -28
  84. package/src/obligations/substitution.ts +1 -5
  85. package/src/obligations/temporal.ts +12 -20
  86. package/src/obligations/tuples.ts +2 -10
  87. package/src/parallel-worker.ts +36 -60
  88. package/src/parallel.ts +64 -73
  89. package/src/parser.ts +1184 -531
  90. package/src/pcal/ast.ts +53 -86
  91. package/src/pcal/parse.ts +144 -219
  92. package/src/pcal/tokenize.ts +91 -131
  93. package/src/pcal/translate.ts +83 -130
  94. package/src/pcal/validate.ts +48 -68
  95. package/src/pretty-print.ts +7 -8
  96. package/src/prover/decide-pool.ts +8 -13
  97. package/src/prover/deciders.ts +12 -13
  98. package/src/prover/first-order.ts +0 -11
  99. package/src/prover/isabelle/decide.ts +3 -31
  100. package/src/prover/isabelle/encode.ts +82 -64
  101. package/src/prover/isabelle/isar/attrib.ts +250 -0
  102. package/src/prover/isabelle/isar/context.ts +335 -0
  103. package/src/prover/isabelle/isar/induct.ts +382 -0
  104. package/src/prover/isabelle/isar/inner-syntax.ts +262 -117
  105. package/src/prover/isabelle/isar/method.ts +510 -226
  106. package/src/prover/isabelle/isar/proof.ts +570 -23
  107. package/src/prover/isabelle/isar/rule-cases.ts +226 -0
  108. package/src/prover/isabelle/isar/theory.ts +488 -88
  109. package/src/prover/isabelle/isar/toplevel.ts +331 -0
  110. package/src/prover/isabelle/isar/type-check.ts +99 -38
  111. package/src/prover/isabelle/provers/blast/blast.ts +16 -105
  112. package/src/prover/isabelle/provers/blast/branch.ts +0 -33
  113. package/src/prover/isabelle/provers/blast/prove.ts +0 -36
  114. package/src/prover/isabelle/provers/blast/rules.ts +5 -45
  115. package/src/prover/isabelle/provers/blast/state.ts +1 -29
  116. package/src/prover/isabelle/provers/blast/term.ts +8 -37
  117. package/src/prover/isabelle/provers/clasimp.ts +1 -15
  118. package/src/prover/isabelle/provers/classical.ts +58 -61
  119. package/src/prover/isabelle/provers/hypsubst.ts +29 -54
  120. package/src/prover/isabelle/pure/bicompose.ts +24 -39
  121. package/src/prover/isabelle/pure/consts.ts +0 -8
  122. package/src/prover/isabelle/pure/conv.ts +2 -18
  123. package/src/prover/isabelle/pure/drule.ts +95 -45
  124. package/src/prover/isabelle/pure/envir.ts +2 -53
  125. package/src/prover/isabelle/pure/goal.ts +1 -9
  126. package/src/prover/isabelle/pure/interrupt.ts +0 -5
  127. package/src/prover/isabelle/pure/list.ts +0 -3
  128. package/src/prover/isabelle/pure/logic.ts +1 -16
  129. package/src/prover/isabelle/pure/name.ts +1 -10
  130. package/src/prover/isabelle/pure/net.ts +2 -60
  131. package/src/prover/isabelle/pure/object-logic.ts +15 -16
  132. package/src/prover/isabelle/pure/pattern.ts +1 -20
  133. package/src/prover/isabelle/pure/raw-simplifier.ts +16 -63
  134. package/src/prover/isabelle/pure/rewriter.ts +34 -77
  135. package/src/prover/isabelle/pure/search.ts +2 -11
  136. package/src/prover/isabelle/pure/seq.ts +0 -11
  137. package/src/prover/isabelle/pure/simplifier.ts +27 -16
  138. package/src/prover/isabelle/pure/table.ts +2 -33
  139. package/src/prover/isabelle/pure/tactic.ts +11 -23
  140. package/src/prover/isabelle/pure/tactical.ts +47 -48
  141. package/src/prover/isabelle/pure/term-ord.ts +1 -7
  142. package/src/prover/isabelle/pure/term.ts +4 -47
  143. package/src/prover/isabelle/pure/thm.ts +26 -48
  144. package/src/prover/isabelle/pure/type.ts +1 -16
  145. package/src/prover/isabelle/pure/unify.ts +19 -31
  146. package/src/prover/isabelle/pure/variable.ts +2 -8
  147. package/src/prover/isabelle/tla/classical-setup.ts +17 -25
  148. package/src/prover/isabelle/tla/context.ts +65 -26
  149. package/src/prover/isabelle/tla/logic-data.ts +1 -1
  150. package/src/prover/isabelle/tla/logic.ts +53 -32
  151. package/src/prover/isabelle/tla/simpdata.ts +45 -44
  152. package/src/prover/isabelle/tools/intuitionistic.ts +28 -21
  153. package/src/prover/ocaml.ts +4 -7
  154. package/src/prover/prep/action.ts +33 -66
  155. package/src/prover/prep/enabled-axioms.ts +22 -20
  156. package/src/prover/prep/fingerprint.ts +2 -21
  157. package/src/prover/prep/level-comparison.ts +8 -12
  158. package/src/prover/prep/md5.ts +26 -31
  159. package/src/prover/prep/methods.ts +189 -86
  160. package/src/prover/prep/normalize.ts +42 -37
  161. package/src/prover/prove-worker.ts +0 -2
  162. package/src/prover/prove.ts +398 -133
  163. package/src/prover/ptl/decide.ts +96 -56
  164. package/src/prover/ptl/encode.ts +15 -38
  165. package/src/prover/ptl/sat.ts +24 -32
  166. package/src/prover/ptl/tableau.ts +40 -28
  167. package/src/prover/smt/arithmetic.ts +310 -0
  168. package/src/prover/smt/axioms.ts +12 -15
  169. package/src/prover/smt/context.ts +60 -32
  170. package/src/prover/smt/data.ts +517 -401
  171. package/src/prover/smt/encode.ts +155 -85
  172. package/src/prover/smt/extensionality.ts +5 -13
  173. package/src/prover/smt/flatten.ts +7 -28
  174. package/src/prover/smt/format.ts +33 -14
  175. package/src/prover/smt/instances.ts +7 -11
  176. package/src/prover/smt/layout.ts +91 -0
  177. package/src/prover/smt/rewrite.ts +1021 -658
  178. package/src/prover/smt/simplify.ts +441 -0
  179. package/src/prover/smt/solver/ackermannize-bv-tactic.ts +61 -0
  180. package/src/prover/smt/solver/ackr-helper.ts +179 -0
  181. package/src/prover/smt/solver/ackr-model-converter.ts +105 -0
  182. package/src/prover/smt/solver/act-cache.ts +0 -16
  183. package/src/prover/smt/solver/add-bounds-tactic.ts +59 -0
  184. package/src/prover/smt/solver/aig-tactic.ts +52 -0
  185. package/src/prover/smt/solver/aig.ts +889 -0
  186. package/src/prover/smt/solver/arith-rewriter.ts +626 -56
  187. package/src/prover/smt/solver/arith-terms.ts +121 -0
  188. package/src/prover/smt/solver/array-decl-plugin.ts +175 -0
  189. package/src/prover/smt/solver/array-rewriter.ts +319 -0
  190. package/src/prover/smt/solver/array.ts +1 -3
  191. package/src/prover/smt/solver/asserted-formulas.ts +241 -99
  192. package/src/prover/smt/solver/ast-lt.ts +165 -21
  193. package/src/prover/smt/solver/ast-util.ts +160 -7
  194. package/src/prover/smt/solver/ast.ts +1480 -184
  195. package/src/prover/smt/solver/auf-solver.ts +30 -56
  196. package/src/prover/smt/solver/bit-blast-tactic.ts +608 -0
  197. package/src/prover/smt/solver/bit-blaster.ts +871 -0
  198. package/src/prover/smt/solver/blast-term-ite.ts +47 -0
  199. package/src/prover/smt/solver/bound-manager.ts +196 -0
  200. package/src/prover/smt/solver/bound-simplifier.ts +598 -0
  201. package/src/prover/smt/solver/bv-bound-chk.ts +492 -0
  202. package/src/prover/smt/solver/bv-decl-plugin.ts +341 -0
  203. package/src/prover/smt/solver/bv-divrem-bounds.ts +95 -0
  204. package/src/prover/smt/solver/bv-rewriter.ts +1901 -0
  205. package/src/prover/smt/solver/bv1-blast.ts +214 -0
  206. package/src/prover/smt/solver/bv2fpa-converter.ts +174 -0
  207. package/src/prover/smt/solver/bv2int-rewriter.ts +544 -0
  208. package/src/prover/smt/solver/bv2real-rewriter.ts +533 -0
  209. package/src/prover/smt/solver/card2bv.ts +127 -0
  210. package/src/prover/smt/solver/case-split-queue.ts +0 -10
  211. package/src/prover/smt/solver/cg-table.ts +39 -42
  212. package/src/prover/smt/solver/check-logic.ts +330 -0
  213. package/src/prover/smt/solver/clause.ts +0 -27
  214. package/src/prover/smt/solver/cofactor-elim-term-ite.ts +293 -0
  215. package/src/prover/smt/solver/conflict-resolution.ts +78 -11
  216. package/src/prover/smt/solver/context.ts +600 -187
  217. package/src/prover/smt/solver/ctx-simplify.ts +34 -52
  218. package/src/prover/smt/solver/ctx-solver-simplify.ts +122 -0
  219. package/src/prover/smt/solver/datatype-decl-plugin.ts +580 -0
  220. package/src/prover/smt/solver/datatype-rewriter.ts +82 -0
  221. package/src/prover/smt/solver/demodulator.ts +786 -0
  222. package/src/prover/smt/solver/dependent-expr-state.ts +93 -0
  223. package/src/prover/smt/solver/der.ts +39 -30
  224. package/src/prover/smt/solver/diff-neq.ts +205 -0
  225. package/src/prover/smt/solver/distribute-forall.ts +57 -0
  226. package/src/prover/smt/solver/dom-simplify.ts +511 -0
  227. package/src/prover/smt/solver/dt2bv-tactic.ts +296 -0
  228. package/src/prover/smt/solver/dyn-ack.ts +0 -11
  229. package/src/prover/smt/solver/e-matching.ts +9 -41
  230. package/src/prover/smt/solver/elim-bounds.ts +89 -0
  231. package/src/prover/smt/solver/elim-small-bv-tactic.ts +129 -0
  232. package/src/prover/smt/solver/elim-term-ite-tactic.ts +48 -0
  233. package/src/prover/smt/solver/elim-uncnstr.ts +542 -0
  234. package/src/prover/smt/solver/enode.ts +100 -23
  235. package/src/prover/smt/solver/eq2bv-tactic.ts +218 -0
  236. package/src/prover/smt/solver/euf/arith-axioms.ts +403 -0
  237. package/src/prover/smt/solver/euf/arith-internalize.ts +653 -0
  238. package/src/prover/smt/solver/euf/arith-solver.ts +889 -0
  239. package/src/prover/smt/solver/euf/array-axioms.ts +527 -0
  240. package/src/prover/smt/solver/euf/array-internalize.ts +428 -0
  241. package/src/prover/smt/solver/euf/array-solver.ts +306 -0
  242. package/src/prover/smt/solver/euf/bv-ackerman.ts +162 -0
  243. package/src/prover/smt/solver/euf/bv-internalize.ts +748 -0
  244. package/src/prover/smt/solver/euf/bv-solver.ts +449 -0
  245. package/src/prover/smt/solver/euf/dt-solver.ts +618 -0
  246. package/src/prover/smt/solver/euf/egraph.ts +901 -0
  247. package/src/prover/smt/solver/euf/euf-solver.ts +1204 -0
  248. package/src/prover/smt/solver/euf/fpa-solver.ts +317 -0
  249. package/src/prover/smt/solver/euf/mam.ts +1046 -0
  250. package/src/prover/smt/solver/euf/q-ematch.ts +829 -0
  251. package/src/prover/smt/solver/euf/q-mbi.ts +587 -0
  252. package/src/prover/smt/solver/euf/q-model-fixer.ts +296 -0
  253. package/src/prover/smt/solver/euf/q-solver.ts +361 -0
  254. package/src/prover/smt/solver/euf/th-solver.ts +328 -0
  255. package/src/prover/smt/solver/euf/th-solvers.ts +30 -0
  256. package/src/prover/smt/solver/expr-ref.ts +0 -5
  257. package/src/prover/smt/solver/expr-safe-replace.ts +26 -7
  258. package/src/prover/smt/solver/expr2polynomial.ts +271 -0
  259. package/src/prover/smt/solver/factor.ts +163 -0
  260. package/src/prover/smt/solver/fd-solver.ts +734 -0
  261. package/src/prover/smt/solver/fingerprints.ts +15 -26
  262. package/src/prover/smt/solver/fix-dl-var.ts +147 -0
  263. package/src/prover/smt/solver/flat-literals.ts +0 -9
  264. package/src/prover/smt/solver/fm-tactic.ts +884 -0
  265. package/src/prover/smt/solver/fpa-decl-plugin.ts +618 -0
  266. package/src/prover/smt/solver/fpa-rewriter.ts +639 -0
  267. package/src/prover/smt/solver/fpa2bv-converter.ts +2251 -0
  268. package/src/prover/smt/solver/fpa2bv-rewriter.ts +349 -0
  269. package/src/prover/smt/solver/fpa2bv-tactic.ts +73 -0
  270. package/src/prover/smt/solver/goal.ts +179 -28
  271. package/src/prover/smt/solver/goal2nlsat.ts +216 -0
  272. package/src/prover/smt/solver/guard-set.ts +219 -0
  273. package/src/prover/smt/solver/hash.ts +0 -9
  274. package/src/prover/smt/solver/hashtable.ts +30 -23
  275. package/src/prover/smt/solver/inf-eps.ts +63 -0
  276. package/src/prover/smt/solver/inj-axiom.ts +101 -0
  277. package/src/prover/smt/solver/internalizer.ts +113 -133
  278. package/src/prover/smt/solver/lackr.ts +381 -0
  279. package/src/prover/smt/solver/lbool.ts +0 -2
  280. package/src/prover/smt/solver/lia2card.ts +268 -0
  281. package/src/prover/smt/solver/lia2pb.ts +154 -0
  282. package/src/prover/smt/solver/literal.ts +0 -4
  283. package/src/prover/smt/solver/logic-tactics.ts +355 -0
  284. package/src/prover/smt/solver/lp/bound-propagator.ts +7 -26
  285. package/src/prover/smt/solver/lp/constraints.ts +1 -8
  286. package/src/prover/smt/solver/lp/containers.ts +18 -31
  287. package/src/prover/smt/solver/lp/core-solver.ts +35 -37
  288. package/src/prover/smt/solver/lp/cross-nested.ts +4 -21
  289. package/src/prover/smt/solver/lp/dep-intervals.ts +6 -24
  290. package/src/prover/smt/solver/lp/dependency.ts +0 -5
  291. package/src/prover/smt/solver/lp/dioph-eq.ts +8 -103
  292. package/src/prover/smt/solver/lp/explanation.ts +0 -6
  293. package/src/prover/smt/solver/lp/gomory.ts +8 -22
  294. package/src/prover/smt/solver/lp/hnf-cutter.ts +16 -23
  295. package/src/prover/smt/solver/lp/hnf.ts +10 -28
  296. package/src/prover/smt/solver/lp/int-cube.ts +17 -39
  297. package/src/prover/smt/solver/lp/int-solver.ts +3 -35
  298. package/src/prover/smt/solver/lp/lar-solver.ts +70 -83
  299. package/src/prover/smt/solver/lp/lar-term.ts +0 -5
  300. package/src/prover/smt/solver/lp/lp-settings.ts +6 -16
  301. package/src/prover/smt/solver/lp/maximize-term.ts +76 -52
  302. package/src/prover/smt/solver/lp/nex-creator.ts +7 -30
  303. package/src/prover/smt/solver/lp/nex.ts +2 -7
  304. package/src/prover/smt/solver/lp/nla-backoff.ts +0 -5
  305. package/src/prover/smt/solver/lp/nla-basics.ts +48 -30
  306. package/src/prover/smt/solver/lp/nla-core.ts +92 -136
  307. package/src/prover/smt/solver/lp/nla-divisions.ts +31 -43
  308. package/src/prover/smt/solver/lp/nla-emonics.ts +3 -21
  309. package/src/prover/smt/solver/lp/nla-factorization.ts +0 -4
  310. package/src/prover/smt/solver/lp/nla-grobner.ts +177 -149
  311. package/src/prover/smt/solver/lp/nla-horner.ts +2 -12
  312. package/src/prover/smt/solver/lp/nla-intervals.ts +1 -12
  313. package/src/prover/smt/solver/lp/nla-monomial-bounds.ts +15 -42
  314. package/src/prover/smt/solver/lp/nla-monotone.ts +1 -6
  315. package/src/prover/smt/solver/lp/nla-order.ts +0 -13
  316. package/src/prover/smt/solver/lp/nla-patcher.ts +3 -7
  317. package/src/prover/smt/solver/lp/nla-powers.ts +220 -0
  318. package/src/prover/smt/solver/lp/nla-tangents.ts +0 -10
  319. package/src/prover/smt/solver/lp/nla-throttle.ts +0 -6
  320. package/src/prover/smt/solver/lp/nla-transcendentals.ts +324 -0
  321. package/src/prover/smt/solver/lp/nla-types.ts +0 -12
  322. package/src/prover/smt/solver/lp/nla-var-eqs.ts +4 -26
  323. package/src/prover/smt/solver/lp/nra-solver.ts +164 -147
  324. package/src/prover/smt/solver/lp/numeric-pair.ts +0 -4
  325. package/src/prover/smt/solver/lp/pdd-interval.ts +6 -5
  326. package/src/prover/smt/solver/lp/pdd-simplifier.ts +61 -34
  327. package/src/prover/smt/solver/lp/pdd-solver.ts +74 -72
  328. package/src/prover/smt/solver/lp/pdd.ts +730 -358
  329. package/src/prover/smt/solver/lp/random-updater.ts +0 -9
  330. package/src/prover/smt/solver/lp/static-matrix.ts +8 -19
  331. package/src/prover/smt/solver/lp/union-find.ts +5 -5
  332. package/src/prover/smt/solver/macro-finder.ts +530 -0
  333. package/src/prover/smt/solver/mam-compiler.ts +129 -139
  334. package/src/prover/smt/solver/mam-interpreter.ts +0 -21
  335. package/src/prover/smt/solver/max-bv-sharing-tactic.ts +17 -0
  336. package/src/prover/smt/solver/max-cliques.ts +105 -0
  337. package/src/prover/smt/solver/maxcore.ts +310 -0
  338. package/src/prover/smt/solver/maximize-ac-sharing.ts +8 -21
  339. package/src/prover/smt/solver/maxlex.ts +115 -0
  340. package/src/prover/smt/solver/maxsmt-base.ts +106 -0
  341. package/src/prover/smt/solver/maxsmt.ts +92 -0
  342. package/src/prover/smt/solver/mbp/mbp-arith.ts +467 -0
  343. package/src/prover/smt/solver/mbp/mbp-basic-tg.ts +101 -0
  344. package/src/prover/smt/solver/mbp/mbp-plugin.ts +287 -0
  345. package/src/prover/smt/solver/mbp/mbp-qel.ts +48 -0
  346. package/src/prover/smt/solver/mbp/mbp-solve-plugin.ts +271 -0
  347. package/src/prover/smt/solver/mbp/mbp-term-graph.ts +606 -0
  348. package/src/prover/smt/solver/model-based-opt.ts +844 -0
  349. package/src/prover/smt/solver/model-checker.ts +20 -63
  350. package/src/prover/smt/solver/model-evaluator.ts +192 -40
  351. package/src/prover/smt/solver/model-finder.ts +14 -32
  352. package/src/prover/smt/solver/model-generator.ts +104 -46
  353. package/src/prover/smt/solver/model-macro-solver.ts +60 -114
  354. package/src/prover/smt/solver/model-printer.ts +214 -0
  355. package/src/prover/smt/solver/mpf.ts +709 -0
  356. package/src/prover/smt/solver/mus.ts +50 -0
  357. package/src/prover/smt/solver/muz/dl-context.ts +382 -0
  358. package/src/prover/smt/solver/muz/dl-mk-bit-blast.ts +97 -0
  359. package/src/prover/smt/solver/muz/dl-mk-coi-filter.ts +167 -0
  360. package/src/prover/smt/solver/muz/dl-mk-elim-term-ite.ts +125 -0
  361. package/src/prover/smt/solver/muz/dl-mk-interp-tail-simplifier.ts +299 -0
  362. package/src/prover/smt/solver/muz/dl-mk-rule-inliner.ts +455 -0
  363. package/src/prover/smt/solver/muz/dl-mk-slice.ts +340 -0
  364. package/src/prover/smt/solver/muz/dl-mk-subsumption-checker.ts +163 -0
  365. package/src/prover/smt/solver/muz/dl-rule-set.ts +273 -0
  366. package/src/prover/smt/solver/muz/dl-rule-transformer.ts +123 -0
  367. package/src/prover/smt/solver/muz/dl-rule.ts +495 -0
  368. package/src/prover/smt/solver/muz/hnf.ts +201 -0
  369. package/src/prover/smt/solver/muz/horn-subsume-model-converter.ts +176 -0
  370. package/src/prover/smt/solver/muz/horn-tactic.ts +214 -0
  371. package/src/prover/smt/solver/muz/rule-properties.ts +359 -0
  372. package/src/prover/smt/solver/muz/spacer-context.ts +1404 -0
  373. package/src/prover/smt/solver/muz/spacer-dl-interface.ts +52 -0
  374. package/src/prover/smt/solver/muz/spacer-generalizers.ts +241 -0
  375. package/src/prover/smt/solver/muz/spacer-manager.ts +127 -0
  376. package/src/prover/smt/solver/muz/spacer-pdr.ts +219 -0
  377. package/src/prover/smt/solver/muz/spacer-prop-solver.ts +333 -0
  378. package/src/prover/smt/solver/muz/spacer-util.ts +282 -0
  379. package/src/prover/smt/solver/muz/substitution.ts +203 -0
  380. package/src/prover/smt/solver/nla2bv-tactic.ts +285 -0
  381. package/src/prover/smt/solver/nlqsat.ts +484 -0
  382. package/src/prover/smt/solver/nlsat/algebraic.ts +357 -236
  383. package/src/prover/smt/solver/nlsat/atoms.ts +73 -54
  384. package/src/prover/smt/solver/nlsat/evaluator.ts +16 -22
  385. package/src/prover/smt/solver/nlsat/explain.ts +429 -275
  386. package/src/prover/smt/solver/nlsat/interval-set.ts +9 -51
  387. package/src/prover/smt/solver/nlsat/levelwise.ts +477 -344
  388. package/src/prover/smt/solver/nlsat/mpbq.ts +47 -14
  389. package/src/prover/smt/solver/nlsat/polynomial.ts +2385 -832
  390. package/src/prover/smt/solver/nlsat/solver.ts +297 -156
  391. package/src/prover/smt/solver/nlsat/transcendental-eval.ts +310 -0
  392. package/src/prover/smt/solver/nlsat/transcendentals.ts +391 -0
  393. package/src/prover/smt/solver/nlsat/types.ts +0 -9
  394. package/src/prover/smt/solver/nlsat/upolynomial-factorization.ts +9 -51
  395. package/src/prover/smt/solver/nlsat/upolynomial.ts +49 -109
  396. package/src/prover/smt/solver/nlsat-tactic.ts +82 -0
  397. package/src/prover/smt/solver/nnf.ts +112 -61
  398. package/src/prover/smt/solver/normalize-bounds.ts +53 -0
  399. package/src/prover/smt/solver/occf.ts +97 -0
  400. package/src/prover/smt/solver/opt-context.ts +801 -0
  401. package/src/prover/smt/solver/opt-nlsat.ts +386 -0
  402. package/src/prover/smt/solver/opt-pareto.ts +301 -0
  403. package/src/prover/smt/solver/opt-preprocess.ts +101 -0
  404. package/src/prover/smt/solver/opt-solver.ts +312 -0
  405. package/src/prover/smt/solver/opt-value.ts +55 -0
  406. package/src/prover/smt/solver/optsmt.ts +692 -0
  407. package/src/prover/smt/solver/parallel-tactic.ts +299 -0
  408. package/src/prover/smt/solver/pattern-inference.ts +21 -26
  409. package/src/prover/smt/solver/pb-rewriter.ts +281 -0
  410. package/src/prover/smt/solver/pb2bv-tactic.ts +540 -0
  411. package/src/prover/smt/solver/poly-rewriter.ts +261 -79
  412. package/src/prover/smt/solver/probes.ts +577 -0
  413. package/src/prover/smt/solver/propagate-values.ts +37 -30
  414. package/src/prover/smt/solver/proto-model.ts +650 -66
  415. package/src/prover/smt/solver/pull-quant.ts +28 -23
  416. package/src/prover/smt/solver/purify-arith.ts +632 -0
  417. package/src/prover/smt/solver/push-app-ite.ts +37 -0
  418. package/src/prover/smt/solver/qe-arith-plugin.ts +1096 -0
  419. package/src/prover/smt/solver/qe-lite-der.ts +2 -31
  420. package/src/prover/smt/solver/qe-lite-fm.ts +4 -28
  421. package/src/prover/smt/solver/qe-lite.ts +41 -51
  422. package/src/prover/smt/solver/qe-mbp.ts +270 -0
  423. package/src/prover/smt/solver/qe.ts +1499 -0
  424. package/src/prover/smt/solver/qel.ts +25 -0
  425. package/src/prover/smt/solver/qi-queue.ts +0 -16
  426. package/src/prover/smt/solver/qsat.ts +829 -0
  427. package/src/prover/smt/solver/quant-hoist.ts +196 -0
  428. package/src/prover/smt/solver/quant-tactics.ts +17 -74
  429. package/src/prover/smt/solver/quantifier-analyzer.ts +26 -47
  430. package/src/prover/smt/solver/quantifier-manager.ts +22 -32
  431. package/src/prover/smt/solver/quasi-macros.ts +243 -0
  432. package/src/prover/smt/solver/random-gen.ts +0 -2
  433. package/src/prover/smt/solver/rational.ts +45 -8
  434. package/src/prover/smt/solver/recfun-decl-plugin.ts +262 -0
  435. package/src/prover/smt/solver/recfun-rewriter.ts +107 -0
  436. package/src/prover/smt/solver/reduce-args.ts +225 -0
  437. package/src/prover/smt/solver/reduce-bv-size.ts +119 -0
  438. package/src/prover/smt/solver/ref-vector.ts +0 -6
  439. package/src/prover/smt/solver/relevancy.ts +2 -16
  440. package/src/prover/smt/solver/rewriter-tpl.ts +59 -135
  441. package/src/prover/smt/solver/rewriter.ts +507 -144
  442. package/src/prover/smt/solver/rlimit.ts +46 -24
  443. package/src/prover/smt/solver/sat/asymm-branch.ts +325 -0
  444. package/src/prover/smt/solver/sat/big.ts +177 -0
  445. package/src/prover/smt/solver/sat/clause-use-list.ts +71 -0
  446. package/src/prover/smt/solver/sat/clause.ts +203 -0
  447. package/src/prover/smt/solver/sat/cleaner.ts +94 -0
  448. package/src/prover/smt/solver/sat/config.ts +122 -0
  449. package/src/prover/smt/solver/sat/consequences.ts +203 -0
  450. package/src/prover/smt/solver/sat/elim-eqs.ts +142 -0
  451. package/src/prover/smt/solver/sat/goal2sat.ts +579 -0
  452. package/src/prover/smt/solver/sat/inc-sat-solver.ts +464 -0
  453. package/src/prover/smt/solver/sat/model-converter.ts +136 -0
  454. package/src/prover/smt/solver/sat/pb-constraint.ts +268 -0
  455. package/src/prover/smt/solver/sat/pb-solver.ts +1596 -0
  456. package/src/prover/smt/solver/sat/probing.ts +170 -0
  457. package/src/prover/smt/solver/sat/sat-tactic.ts +53 -0
  458. package/src/prover/smt/solver/sat/sat2goal.ts +189 -0
  459. package/src/prover/smt/solver/sat/scc.ts +142 -0
  460. package/src/prover/smt/solver/sat/simplifier.ts +1618 -0
  461. package/src/prover/smt/solver/sat/solver.ts +2107 -0
  462. package/src/prover/smt/solver/sat/var-queue.ts +117 -0
  463. package/src/prover/smt/solver/sat/watch-list.ts +140 -0
  464. package/src/prover/smt/solver/search-tree.ts +284 -0
  465. package/src/prover/smt/solver/seq-axioms.ts +995 -0
  466. package/src/prover/smt/solver/seq-decl-plugin.ts +819 -0
  467. package/src/prover/smt/solver/seq-derive.ts +1298 -0
  468. package/src/prover/smt/solver/seq-eq-approx.ts +236 -0
  469. package/src/prover/smt/solver/seq-eq-solver.ts +439 -0
  470. package/src/prover/smt/solver/seq-factory.ts +89 -0
  471. package/src/prover/smt/solver/seq-monadic.ts +730 -0
  472. package/src/prover/smt/solver/seq-range-predicate.ts +235 -0
  473. package/src/prover/smt/solver/seq-re-rewriter.ts +1171 -0
  474. package/src/prover/smt/solver/seq-re-util.ts +758 -0
  475. package/src/prover/smt/solver/seq-regex-bisim.ts +144 -0
  476. package/src/prover/smt/solver/seq-regex-live.ts +200 -0
  477. package/src/prover/smt/solver/seq-rewriter.ts +2404 -0
  478. package/src/prover/smt/solver/seq-skolem.ts +294 -0
  479. package/src/prover/smt/solver/seq-subset.ts +165 -0
  480. package/src/prover/smt/solver/seq-view-witness.ts +353 -0
  481. package/src/prover/smt/solver/smt-consequences.ts +297 -0
  482. package/src/prover/smt/solver/smt-kernel.ts +124 -0
  483. package/src/prover/smt/solver/smt-logics.ts +66 -0
  484. package/src/prover/smt/solver/smt-setup.ts +589 -0
  485. package/src/prover/smt/solver/smt2-printer.ts +765 -0
  486. package/src/prover/smt/solver/smtlib-parser.ts +3546 -406
  487. package/src/prover/smt/solver/smtlib-script.ts +2134 -0
  488. package/src/prover/smt/solver/solve-eqs.ts +928 -0
  489. package/src/prover/smt/solver/solver.ts +135 -40
  490. package/src/prover/smt/solver/sort.ts +1 -5
  491. package/src/prover/smt/solver/static-features.ts +314 -0
  492. package/src/prover/smt/solver/sticky-generations.ts +0 -6
  493. package/src/prover/smt/solver/tactic.ts +2141 -0
  494. package/src/prover/smt/solver/term-enumeration.ts +205 -0
  495. package/src/prover/smt/solver/theory-array.ts +1240 -0
  496. package/src/prover/smt/solver/theory-bv.ts +1210 -0
  497. package/src/prover/smt/solver/theory-char.ts +355 -0
  498. package/src/prover/smt/solver/theory-datatype.ts +598 -0
  499. package/src/prover/smt/solver/theory-finite-set.ts +30 -0
  500. package/src/prover/smt/solver/theory-fpa.ts +389 -0
  501. package/src/prover/smt/solver/theory-lra-axioms.ts +55 -25
  502. package/src/prover/smt/solver/theory-lra-bounds.ts +31 -11
  503. package/src/prover/smt/solver/theory-lra-final-check.ts +60 -91
  504. package/src/prover/smt/solver/theory-lra-internalize.ts +96 -53
  505. package/src/prover/smt/solver/theory-lra-model.ts +23 -53
  506. package/src/prover/smt/solver/theory-lra-propagate.ts +34 -42
  507. package/src/prover/smt/solver/theory-lra-state.ts +7 -28
  508. package/src/prover/smt/solver/theory-lra.ts +189 -9
  509. package/src/prover/smt/solver/theory-pb.ts +951 -0
  510. package/src/prover/smt/solver/theory-polymorphism.ts +58 -0
  511. package/src/prover/smt/solver/theory-recfun.ts +307 -0
  512. package/src/prover/smt/solver/theory-seq-regex.ts +867 -0
  513. package/src/prover/smt/solver/theory-seq-solve.ts +1373 -0
  514. package/src/prover/smt/solver/theory-seq-state.ts +852 -0
  515. package/src/prover/smt/solver/theory-seq.ts +961 -0
  516. package/src/prover/smt/solver/theory-without-terms.ts +24 -0
  517. package/src/prover/smt/solver/theory.ts +189 -0
  518. package/src/prover/smt/solver/tseitin-cnf.ts +486 -0
  519. package/src/prover/smt/solver/var-subst.ts +37 -39
  520. package/src/prover/smt/table.ts +3 -10
  521. package/src/prover/smt/types.ts +146 -0
  522. package/src/prover/tlapm/cache.ts +74 -48
  523. package/src/prover/tlapm/ocaml-marshal.ts +19 -21
  524. package/src/prover/tlapm/tlapm.ts +21 -20
  525. package/src/prover/tlapm-library.ts +3208 -0
  526. package/src/prover/verdict.ts +9 -2
  527. package/src/prover/zenon/check/check.ts +1 -11
  528. package/src/prover/zenon/check/definitions.ts +5 -15
  529. package/src/prover/zenon/check/equality.ts +0 -8
  530. package/src/prover/zenon/check/functions.ts +0 -4
  531. package/src/prover/zenon/check/keys.ts +0 -7
  532. package/src/prover/zenon/check/propositional.ts +0 -3
  533. package/src/prover/zenon/check/records.ts +1 -6
  534. package/src/prover/zenon/check/relations.ts +2 -14
  535. package/src/prover/zenon/check/rewrites.ts +2 -21
  536. package/src/prover/zenon/check/sets.ts +40 -61
  537. package/src/prover/zenon/check/terms.ts +1 -19
  538. package/src/prover/zenon/check/tla.ts +0 -6
  539. package/src/prover/zenon/decide.ts +10 -19
  540. package/src/prover/zenon/encode.ts +0 -9
  541. package/src/prover/zenon/eqrel.ts +2 -15
  542. package/src/prover/zenon/equality-rules.ts +24 -6
  543. package/src/prover/zenon/expr.ts +29 -28
  544. package/src/prover/zenon/index-table.ts +33 -61
  545. package/src/prover/zenon/isar-case.ts +9 -21
  546. package/src/prover/zenon/isar.ts +37 -67
  547. package/src/prover/zenon/limits.ts +0 -4
  548. package/src/prover/zenon/llproof.ts +2 -22
  549. package/src/prover/zenon/mltoll.ts +66 -106
  550. package/src/prover/zenon/node.ts +20 -15
  551. package/src/prover/zenon/ocaml.ts +1 -17
  552. package/src/prover/zenon/parse.ts +9 -13
  553. package/src/prover/zenon/phrase.ts +2 -14
  554. package/src/prover/zenon/proof.ts +0 -11
  555. package/src/prover/zenon/propositional-rules.ts +0 -7
  556. package/src/prover/zenon/rules.ts +3 -8
  557. package/src/prover/zenon/search.ts +11 -35
  558. package/src/prover/zenon/tla/functions.ts +59 -33
  559. package/src/prover/zenon/tla/llproof.ts +67 -78
  560. package/src/prover/zenon/tla/records.ts +57 -35
  561. package/src/prover/zenon/tla/rewrites.ts +12 -21
  562. package/src/prover/zenon/tla/sets.ts +88 -59
  563. package/src/prover/zenon/tla/terms.ts +0 -8
  564. package/src/prover/zenon/tla/tla.ts +66 -66
  565. package/src/randomization.ts +81 -35
  566. package/src/resolve.ts +1132 -430
  567. package/src/runtime.ts +33 -23
  568. package/src/sany/builtins.ts +11 -14
  569. package/src/sany/generation.ts +383 -0
  570. package/src/sany/generator-def-entries.ts +210 -0
  571. package/src/sany/generator-definitions.ts +688 -0
  572. package/src/sany/generator-expressions.ts +1108 -0
  573. package/src/sany/generator-proofs.ts +665 -0
  574. package/src/sany/generator.ts +192 -2764
  575. package/src/sany/levels.ts +5 -35
  576. package/src/sany/lexer.ts +61 -80
  577. package/src/sany/linter.ts +0 -10
  578. package/src/sany/modules.ts +5 -7
  579. package/src/sany/nodes.ts +6 -44
  580. package/src/sany/parse-error.ts +39 -117
  581. package/src/sany/report.ts +32 -69
  582. package/src/sany/selectors.ts +60 -82
  583. package/src/sany/source.ts +1 -17
  584. package/src/sany/xml.ts +37 -120
  585. package/src/search.ts +913 -227
  586. package/src/simulate.ts +765 -0
  587. package/src/spec-description.ts +198 -104
  588. package/src/standard-definitions.ts +4 -4
  589. package/src/standard-modules.ts +302 -99
  590. package/src/state-graph.ts +52 -33
  591. package/src/subexpressions.ts +578 -166
  592. package/src/substitution-levels.ts +7 -7
  593. package/src/successors.ts +299 -108
  594. package/src/symmetry.ts +37 -28
  595. package/src/tableau.ts +29 -26
  596. package/src/tlc/fingerprint.ts +267 -79
  597. package/src/tlc/jar-data.ts +122 -6
  598. package/src/tlc/messages.ts +127 -56
  599. package/src/tlc/order.ts +53 -72
  600. package/src/tlc/random.ts +38 -49
  601. package/src/tlc/replay.ts +579 -230
  602. package/src/tlc/summary.ts +64 -60
  603. package/src/tlc/tlc-operators.ts +83 -47
  604. package/src/tlc/tlcext-operators.ts +205 -127
  605. package/src/tlc/trace-spec.ts +235 -0
  606. package/src/tlc/value-stream.ts +139 -0
  607. package/src/tlc/version.ts +1 -4
  608. package/src/trace-liveness.ts +529 -0
  609. package/src/transfer.ts +22 -25
  610. package/src/typed-tier.ts +6556 -0
  611. package/src/typescript/actions.ts +479 -0
  612. package/src/typescript/collections.ts +614 -0
  613. package/src/typescript/compile.ts +63 -0
  614. package/src/typescript/context.ts +94 -0
  615. package/src/typescript/emit.ts +121 -0
  616. package/src/typescript/expressions.ts +496 -0
  617. package/src/typescript/formula.ts +154 -0
  618. package/src/typescript/functions.ts +284 -0
  619. package/src/typescript/model.ts +162 -0
  620. package/src/typescript/names.ts +114 -0
  621. package/src/typescript/program.ts +48 -0
  622. package/src/typescript/properties.ts +139 -0
  623. package/src/typescript/scope.ts +112 -0
  624. package/src/typescript/steps.ts +167 -0
  625. package/src/typescript/types.ts +171 -0
  626. package/src/values.ts +945 -526
  627. package/src/worker.ts +7 -8
  628. package/src/prover/isabelle/isar/statement.ts +0 -57
  629. package/src/prover/smt/solver/z3-license.txt +0 -10
  630. package/src/prover/tlaps-module.ts +0 -510
  631. package/src/prover/zenon/LICENSE +0 -32
@@ -1,50 +1,20 @@
1
- // Ported from Z3 (src/math/polynomial/polynomial.{h,cpp}, src/math/polynomial/polynomial_cache.cpp),
2
- // MIT license, see z3-license.txt. Multivariate polynomials over the integers for nlsat, with
3
- // Z3's factorization: univariate through upolynomial-factorization, quadratics through the square
4
- // root of the discriminant, and higher degrees through bivariate Hensel lifting. A polynomial keeps its monomials in the order Z3's som buffers
5
- // produce, with a monomial of maximal degree in the maximal variable first, because factorization
6
- // breaks ties on the order in which variables occur.
7
- //
8
- // Deviations from Z3, which only change the order of equal results:
9
- // - gcd computes with Z3's subresultant PRS (gcd_prs), not its modular algorithms (mod_gcd,
10
- // uni_mod_gcd). Both return the same polynomial, normalized to a positive leading coefficient,
11
- // but its monomials may come out in another order. Z3's modular gcd can also return a constant
12
- // other than 1 for coprime primitive polynomials, gcd(2x - 3, 2x - 1) = 2
13
- // (polynomial.cpp:4815), where this port returns 1. The callers in scope only test whether
14
- // the gcd is constant.
15
- // - Polynomial ids count up from zero. Z3 recycles the ids of deleted polynomials, so where nlsat
16
- // breaks a tie between two root functions on their ids it may pick the other one. Matching Z3
17
- // would take explicit reference counts at its roughly 490 polynomial_ref sites in polynomial,
18
- // algebraic_numbers, explain, levelwise and nra, and every pm routine allocating the same
19
- // temporaries as Z3's, not just returning the same result. Random differential tests hit such a
20
- // tie in about 1 of 300 levelwise and 1 of 3,000 explain programs, and no corpus trace yet.
21
1
  import { SmtInvariantError } from "../../../../errors";
2
+ import { RandomGen } from "../random-gen";
22
3
  import { getGcd, Rational } from "../rational";
23
- import { UpolynomialManager } from "./upolynomial";
4
+ import type { ResourceLimit } from "../rlimit";
5
+ import { BIG_PRIMES, getExtendedGcd, UpolynomialManager } from "./upolynomial";
24
6
  import {
25
7
  DEFAULT_FACTOR_PARAMS,
26
8
  factorSquareFree,
27
9
  getExactSquareRoot,
28
- type UpolynomialFactors,
10
+ mkFactors,
29
11
  } from "./upolynomial-factorization";
30
12
 
31
13
  export const NULL_VAR = -1;
32
14
 
33
- // s_factor_eval_values and s_factor_primes: the points multivariate factorization evaluates the
34
- // other variables at, and the primes it lifts modulo.
35
15
  const FACTOR_EVAL_VALUES = [0n, 1n, -1n, 2n, -2n, 3n, -3n];
36
16
  const FACTOR_PRIMES = [39103n, 104729n, 1000003n, 100000007n];
37
17
 
38
- // mpz div: rounds toward minus infinity.
39
- const floorDiv = (dividend: bigint, divisor: bigint) => {
40
- const quotient = dividend / divisor;
41
- return dividend % divisor !== 0n && dividend < 0n !== divisor < 0n ? quotient - 1n : quotient;
42
- };
43
-
44
- // Input outside what the port of nlsat supports so far: subresultants of polynomials of degree 2
45
- // or more in the variable being projected. The nra solver answers unknown on it, which is always
46
- // sound.
47
- // The arithmetic t_eval evaluates in: rationals, intervals or algebraic numbers.
48
18
  export interface ValueOps<T> {
49
19
  fromInteger(value: bigint): T;
50
20
  add(first: T, second: T): T;
@@ -62,10 +32,27 @@ const RATIONAL_OPS: ValueOps<Rational> = {
62
32
  const getMonomialKey = (vars: readonly number[], degrees: readonly number[]) =>
63
33
  vars.map((variable, index) => `${variable}^${degrees[index]}`).join(",");
64
34
 
35
+ const normalizeZp = (value: bigint, modulus: bigint) => {
36
+ const upper = modulus / 2n;
37
+ const lower = modulus % 2n === 0n ? -upper + 1n : -upper;
38
+ const rest = value % modulus;
39
+ return rest > upper ? rest - modulus : rest < lower ? rest + modulus : rest;
40
+ };
41
+
42
+ const divMpz = (dividend: bigint, divisor: bigint) => {
43
+ const quotient = dividend / divisor;
44
+ if (dividend >= 0n || dividend % divisor === 0n) return quotient;
45
+ return divisor < 0n ? quotient + 1n : quotient - 1n;
46
+ };
47
+
48
+ const modMpz = (value: bigint, modulus: bigint) => {
49
+ const rest = value % modulus;
50
+ return rest < 0n ? rest + (modulus < 0n ? -modulus : modulus) : rest;
51
+ };
52
+
65
53
  class Monomial {
66
54
  readonly totalDegree: number;
67
55
 
68
- // vars and degrees change only when the manager renames the variables.
69
56
  constructor(
70
57
  readonly id: number,
71
58
  public vars: readonly number[],
@@ -93,15 +80,18 @@ class Monomial {
93
80
  return index === -1 ? 0 : this.degrees[index];
94
81
  }
95
82
 
96
- // max_smaller_than: the largest variable of the monomial below x.
97
83
  maxSmallerThan(variable: number) {
98
84
  let result = NULL_VAR;
99
85
  for (const current of this.vars) if (current < variable) result = current;
100
86
  return result;
101
87
  }
88
+
89
+ isSquare() {
90
+ for (const degree of this.degrees) if (degree % 2 === 1) return false;
91
+ return true;
92
+ }
102
93
  }
103
94
 
104
- // lex_compare: the biggest variable dominates, then its degree.
105
95
  const lexCompare = (first: Monomial, second: Monomial) => {
106
96
  if (first === second) return 0;
107
97
  let firstIndex = first.size - 1;
@@ -124,6 +114,45 @@ const lexCompare = (first: Monomial, second: Monomial) => {
124
114
  return firstIndex < 0 ? -1 : 1;
125
115
  };
126
116
 
117
+ const lexCompare2 = (first: Monomial, second: Monomial, minVar: number) => {
118
+ if (first === second) return 0;
119
+ let firstIndex = first.size - 1;
120
+ let secondIndex = second.size - 1;
121
+ let firstMinVarDegree = 0;
122
+ let secondMinVarDegree = 0;
123
+ while (firstIndex >= 0 && secondIndex >= 0) {
124
+ const firstVar = first.vars[firstIndex];
125
+ const secondVar = second.vars[secondIndex];
126
+ if (firstVar === minVar) {
127
+ firstMinVarDegree = first.degrees[firstIndex];
128
+ firstIndex--;
129
+ if (secondVar === minVar) {
130
+ secondMinVarDegree = second.degrees[secondIndex];
131
+ secondIndex--;
132
+ }
133
+ continue;
134
+ }
135
+ if (secondVar === minVar) {
136
+ secondMinVarDegree = second.degrees[secondIndex];
137
+ secondIndex--;
138
+ continue;
139
+ }
140
+ if (firstVar === secondVar) {
141
+ const firstDegree = first.degrees[firstIndex];
142
+ const secondDegree = second.degrees[secondIndex];
143
+ if (firstDegree === secondDegree) {
144
+ firstIndex--;
145
+ secondIndex--;
146
+ continue;
147
+ }
148
+ return firstDegree < secondDegree ? -1 : 1;
149
+ }
150
+ return firstVar > secondVar ? 1 : -1;
151
+ }
152
+ if (firstIndex === secondIndex) return firstMinVarDegree < secondMinVarDegree ? -1 : 1;
153
+ return firstIndex < 0 ? -1 : 1;
154
+ };
155
+
127
156
  const gradedLexCompare = (first: Monomial, second: Monomial) =>
128
157
  first.totalDegree === second.totalDegree
129
158
  ? lexCompare(first, second)
@@ -131,7 +160,6 @@ const gradedLexCompare = (first: Monomial, second: Monomial) =>
131
160
  ? -1
132
161
  : 1;
133
162
 
134
- // po_gt: the order that puts a monomial with the maximal variable at its maximal degree first.
135
163
  const isPoGreater = (first: Monomial, second: Monomial) => {
136
164
  if (first.size === 0) return false;
137
165
  if (second.size === 0) return true;
@@ -141,6 +169,7 @@ const isPoGreater = (first: Monomial, second: Monomial) => {
141
169
 
142
170
  export class Polynomial {
143
171
  isLexSorted = false;
172
+ refCount = 0;
144
173
 
145
174
  constructor(
146
175
  readonly id: number,
@@ -150,7 +179,6 @@ export class Polynomial {
150
179
  this.makeFirstMaximal();
151
180
  }
152
181
 
153
- // make_first_maximal: a monomial with the maximal variable at its maximal degree first.
154
182
  makeFirstMaximal() {
155
183
  if (this.ms.length <= 1) return;
156
184
  let maxPos = 0;
@@ -174,8 +202,7 @@ export class Polynomial {
174
202
  this.ms[position] = monomial;
175
203
  }
176
204
 
177
- // lex_sort: puts the monomials in decreasing lexicographic order, which Z3 does in place whenever it
178
- // hashes the polynomial.
205
+ // Z3 sorts in place whenever it hashes or evaluates the polynomial, so later reads see this order.
179
206
  lexSort() {
180
207
  if (this.isLexSorted) return;
181
208
  this.isLexSorted = true;
@@ -190,7 +217,6 @@ export class Polynomial {
190
217
  }
191
218
  }
192
219
 
193
- // graded_lex_max_pos
194
220
  getGradedLexMaxPos() {
195
221
  if (this.ms.length === 0) return -1;
196
222
  let maxPos = 0;
@@ -199,6 +225,13 @@ export class Polynomial {
199
225
  return maxPos;
200
226
  }
201
227
 
228
+ getGradedLexMinPos() {
229
+ let minPos = 0;
230
+ for (let index = 1; index < this.ms.length; index++)
231
+ if (gradedLexCompare(this.ms[index], this.ms[minPos]) < 0) minPos = index;
232
+ return minPos;
233
+ }
234
+
202
235
  toString() {
203
236
  if (this.ms.length === 0) return "0";
204
237
  return this.ms
@@ -214,8 +247,112 @@ export class Polynomial {
214
247
  }
215
248
  }
216
249
 
217
- // som_buffer: a sum of monomials, each kept at the position where it first appeared. Zero entries
218
- // stay until mk removes them.
250
+ export class PolynomialRef {
251
+ private value: Polynomial | null = null;
252
+
253
+ constructor(private readonly pm: PolynomialManager) {}
254
+
255
+ get() {
256
+ const value = this.value;
257
+ if (value === null) throw new SmtInvariantError("polynomial reference is null");
258
+ return value;
259
+ }
260
+
261
+ getOrNull() {
262
+ return this.value;
263
+ }
264
+
265
+ set(polynomial: Polynomial) {
266
+ this.pm.incRef(polynomial);
267
+ if (this.value !== null) this.pm.decRef(this.value);
268
+ this.value = polynomial;
269
+ }
270
+
271
+ copy(other: PolynomialRef) {
272
+ if (this.value === other.value) return;
273
+ if (this.value !== null) this.pm.decRef(this.value);
274
+ this.value = other.value;
275
+ if (this.value !== null) this.pm.incRef(this.value);
276
+ }
277
+
278
+ move(other: PolynomialRef) {
279
+ if (this === other) return;
280
+ if (this.value !== null) this.pm.decRef(this.value);
281
+ this.value = other.value;
282
+ other.value = null;
283
+ }
284
+
285
+ swap(other: PolynomialRef) {
286
+ const value = this.value;
287
+ this.value = other.value;
288
+ other.value = value;
289
+ }
290
+
291
+ reset() {
292
+ if (this.value !== null) this.pm.decRef(this.value);
293
+ this.value = null;
294
+ }
295
+ }
296
+
297
+ export class PolynomialRefVector {
298
+ readonly items: Polynomial[] = [];
299
+
300
+ constructor(private readonly pm: PolynomialManager) {}
301
+
302
+ get size() {
303
+ return this.items.length;
304
+ }
305
+
306
+ get(index: number) {
307
+ return this.items[index];
308
+ }
309
+
310
+ push(polynomial: Polynomial) {
311
+ this.pm.incRef(polynomial);
312
+ this.items.push(polynomial);
313
+ }
314
+
315
+ set(index: number, polynomial: Polynomial) {
316
+ this.pm.incRef(polynomial);
317
+ this.pm.decRef(this.items[index]);
318
+ this.items[index] = polynomial;
319
+ }
320
+
321
+ append(other: PolynomialRefVector) {
322
+ for (const polynomial of other.items) this.push(polynomial);
323
+ }
324
+
325
+ shrink(size: number) {
326
+ for (let index = size; index < this.items.length; index++) this.pm.decRef(this.items[index]);
327
+ this.items.length = size;
328
+ }
329
+
330
+ reset() {
331
+ this.shrink(0);
332
+ }
333
+ }
334
+
335
+ export class Factors {
336
+ constant = 1n;
337
+ readonly factors: Polynomial[] = [];
338
+ readonly degrees: number[] = [];
339
+
340
+ constructor(private readonly pm: PolynomialManager) {}
341
+
342
+ push(polynomial: Polynomial, degree: number) {
343
+ this.factors.push(polynomial);
344
+ this.degrees.push(degree);
345
+ this.pm.incRef(polynomial);
346
+ }
347
+
348
+ reset() {
349
+ for (const factor of this.factors) this.pm.decRef(factor);
350
+ this.factors.length = 0;
351
+ this.degrees.length = 0;
352
+ this.constant = 1n;
353
+ }
354
+ }
355
+
219
356
  class SomBuffer {
220
357
  as: bigint[] = [];
221
358
  ms: Monomial[] = [];
@@ -231,54 +368,69 @@ class SomBuffer {
231
368
 
232
369
  addTerm(coeff: bigint, monomial: Monomial) {
233
370
  if (coeff === 0n) return;
371
+ const modulus = this.manager.modulus;
234
372
  const position = this.positions.get(monomial.id);
235
373
  if (position === undefined) {
236
374
  this.positions.set(monomial.id, this.ms.length);
237
375
  this.ms.push(monomial);
238
- this.as.push(coeff);
376
+ this.as.push(modulus === null ? coeff : normalizeZp(coeff, modulus));
239
377
  return;
240
378
  }
241
- this.as[position] += coeff;
379
+ const sum = this.as[position] + coeff;
380
+ this.as[position] = modulus === null ? sum : normalizeZp(sum, modulus);
242
381
  }
243
382
 
244
383
  add(polynomial: Polynomial) {
384
+ const modulus = this.manager.modulus;
245
385
  for (let index = 0; index < polynomial.size; index++) {
246
386
  const monomial = polynomial.ms[index];
247
387
  const position = this.positions.get(monomial.id);
248
388
  if (position === undefined) {
249
389
  this.positions.set(monomial.id, this.ms.length);
250
390
  this.ms.push(monomial);
251
- this.as.push(polynomial.as[index]);
252
- } else this.as[position] += polynomial.as[index];
391
+ const coeff = polynomial.as[index];
392
+ this.as.push(modulus === null ? coeff : normalizeZp(coeff, modulus));
393
+ continue;
394
+ }
395
+ const sum = this.as[position] + polynomial.as[index];
396
+ this.as[position] = modulus === null ? sum : normalizeZp(sum, modulus);
253
397
  }
254
398
  }
255
399
 
256
- // addmul: adds a*m*p.
257
400
  addmul(coeff: bigint, monomial: Monomial, polynomial: Polynomial) {
258
401
  if (coeff === 0n) return;
402
+ const modulus = this.manager.modulus;
259
403
  for (let index = 0; index < polynomial.size; index++) {
260
404
  const product = this.manager.mulMonomials(monomial, polynomial.ms[index]);
261
405
  const position = this.positions.get(product.id);
262
406
  if (position === undefined) {
263
407
  this.positions.set(product.id, this.ms.length);
264
408
  this.ms.push(product);
265
- this.as.push(coeff * polynomial.as[index]);
266
- } else this.as[position] += coeff * polynomial.as[index];
409
+ const value = coeff * polynomial.as[index];
410
+ this.as.push(modulus === null ? value : normalizeZp(value, modulus));
411
+ continue;
412
+ }
413
+ const sum = this.as[position] + coeff * polynomial.as[index];
414
+ this.as[position] = modulus === null ? sum : normalizeZp(sum, modulus);
267
415
  }
268
416
  }
269
417
 
270
- // addmul(a, m, buffer): adds a*m times each entry of another buffer, zero entries included,
271
- // which keeps their monomials at new positions as Z3 does.
418
+ // Like Z3, zero entries of the other buffer are added too, which keeps their monomials' positions.
272
419
  addmulBuffer(coeff: bigint, monomial: Monomial, buffer: SomBuffer) {
273
420
  if (coeff === 0n) return;
421
+ const modulus = this.manager.modulus;
274
422
  for (let index = 0; index < buffer.ms.length; index++) {
275
423
  const product = this.manager.mulMonomials(monomial, buffer.ms[index]);
276
424
  const position = this.positions.get(product.id);
277
425
  if (position === undefined) {
278
426
  this.positions.set(product.id, this.ms.length);
279
427
  this.ms.push(product);
280
- this.as.push(coeff * buffer.as[index]);
281
- } else this.as[position] += coeff * buffer.as[index];
428
+ const value = coeff * buffer.as[index];
429
+ this.as.push(modulus === null ? value : normalizeZp(value, modulus));
430
+ continue;
431
+ }
432
+ const sum = this.as[position] + coeff * buffer.as[index];
433
+ this.as[position] = modulus === null ? sum : normalizeZp(sum, modulus);
282
434
  }
283
435
  }
284
436
 
@@ -291,7 +443,6 @@ class SomBuffer {
291
443
  return maxPos;
292
444
  }
293
445
 
294
- // mk(normalize): the nonzero entries, divided by the gcd of their coefficients when normalizing.
295
446
  mk(isNormalized = false) {
296
447
  const as: bigint[] = [];
297
448
  const ms: Monomial[] = [];
@@ -301,32 +452,49 @@ class SomBuffer {
301
452
  ms.push(this.ms[index]);
302
453
  }
303
454
  this.reset();
304
- const gcd = isNormalized ? as.reduce((current, coeff) => getGcd(current, coeff), 0n) : 1n;
305
- return this.manager.mkPolynomialCore(gcd > 1n ? as.map((coeff) => coeff / gcd) : as, ms);
455
+ if (isNormalized) this.manager.normalizeNumerals(as);
456
+ return this.manager.mkPolynomialCore(as, ms);
306
457
  }
307
458
  }
308
459
 
309
- // cheap_som_buffer: each monomial is added at most once, so it needs no position map.
310
460
  class CheapSomBuffer {
311
461
  private as: bigint[] = [];
312
462
  private ms: Monomial[] = [];
313
463
 
314
464
  constructor(private manager: PolynomialManager) {}
315
465
 
316
- add(coeff: bigint, monomial: Monomial) {
466
+ addReset(coeff: bigint, monomial: Monomial) {
317
467
  if (coeff === 0n) return;
318
468
  this.as.push(coeff);
319
469
  this.ms.push(monomial);
320
470
  }
321
471
 
472
+ add(coeff: bigint, monomial: Monomial) {
473
+ if (coeff === 0n) return;
474
+ const modulus = this.manager.modulus;
475
+ this.as.push(modulus === null ? coeff : normalizeZp(coeff, modulus));
476
+ this.ms.push(monomial);
477
+ }
478
+
322
479
  addmul(coeff: bigint, monomial: Monomial, polynomial: Polynomial) {
323
480
  if (coeff === 0n) return;
481
+ const modulus = this.manager.modulus;
324
482
  for (let index = 0; index < polynomial.size; index++) {
325
- this.as.push(coeff * polynomial.as[index]);
483
+ const value = coeff * polynomial.as[index];
484
+ this.as.push(modulus === null ? value : normalizeZp(value, modulus));
326
485
  this.ms.push(this.manager.mulMonomials(monomial, polynomial.ms[index]));
327
486
  }
328
487
  }
329
488
 
489
+ normalize() {
490
+ this.manager.normalizeNumerals(this.as);
491
+ }
492
+
493
+ reset() {
494
+ this.as = [];
495
+ this.ms = [];
496
+ }
497
+
330
498
  mk() {
331
499
  const result = this.manager.mkPolynomialCore(this.as, this.ms);
332
500
  this.as = [];
@@ -335,31 +503,240 @@ class CheapSomBuffer {
335
503
  }
336
504
  }
337
505
 
338
- interface Factors {
339
- constant: bigint;
340
- factors: Polynomial[];
341
- degrees: number[];
506
+ class NewtonInterpolator {
507
+ readonly inputs: bigint[] = [];
508
+ private invs: bigint[] = [0n];
509
+ private vs: PolynomialRefVector;
510
+
511
+ constructor(private readonly pm: PolynomialManager) {
512
+ this.vs = new PolynomialRefVector(pm);
513
+ }
514
+
515
+ reset() {
516
+ this.inputs.length = 0;
517
+ this.invs.length = 1;
518
+ this.vs.reset();
519
+ }
520
+
521
+ add(input: bigint, output: Polynomial) {
522
+ const pm = this.pm;
523
+ const size = this.inputs.length;
524
+ if (size === 0) {
525
+ this.inputs.push(input);
526
+ this.vs.push(output);
527
+ return;
528
+ }
529
+ const k = size;
530
+ let product = pm.subNumeral(input, this.inputs[0]);
531
+ for (let index = 1; index <= k - 1; index++)
532
+ product = pm.mulNumeral(product, pm.subNumeral(input, this.inputs[index]));
533
+ product = pm.invNumeral(product);
534
+ this.inputs.push(input);
535
+ this.invs.push(product);
536
+ const temp = new PolynomialRef(pm);
537
+ const auxPoly = new PolynomialRef(pm);
538
+ temp.set(this.vs.get(k - 1));
539
+ for (let j = k - 2; j >= 0; j--) {
540
+ const aux = pm.subNumeral(input, this.inputs[j]);
541
+ auxPoly.set(pm.mulConst(aux, temp.get()));
542
+ temp.set(pm.add(auxPoly.get(), this.vs.get(j)));
543
+ }
544
+ auxPoly.set(pm.sub(output, temp.get()));
545
+ auxPoly.set(pm.mulConst(this.invs[size], auxPoly.get()));
546
+ this.vs.push(auxPoly.get());
547
+ auxPoly.reset();
548
+ temp.reset();
549
+ }
550
+
551
+ mk(x: number, r: PolynomialRef) {
552
+ const pm = this.pm;
553
+ const u = new PolynomialRef(pm);
554
+ const auxPoly = new PolynomialRef(pm);
555
+ const d = this.inputs.length - 1;
556
+ u.set(this.vs.get(d));
557
+ for (let k = d - 1; k >= 0; k--) {
558
+ const c = pm.negNumeral(this.inputs[k]);
559
+ auxPoly.set(pm.mkLinear([1n], [x], c));
560
+ auxPoly.set(pm.mul(u.get(), auxPoly.get()));
561
+ u.set(pm.add(auxPoly.get(), this.vs.get(k)));
562
+ }
563
+ r.copy(u);
564
+ auxPoly.reset();
565
+ u.reset();
566
+ }
567
+ }
568
+
569
+ interface SkeletonEntry {
570
+ monomial: Monomial;
571
+ firstPowerIndex: number;
572
+ numPowers: number;
573
+ }
574
+
575
+ class Skeleton {
576
+ readonly entries: SkeletonEntry[] = [];
577
+ readonly powers: number[] = [];
578
+ readonly origMonomials: Monomial[] = [];
579
+ maxPowers = 0;
580
+
581
+ constructor(pm: PolynomialManager, polynomial: Polynomial, x: number) {
582
+ const ms = [...polynomial.ms].sort((first, second) => lexCompare2(first, second, x));
583
+ let previous: Monomial | null = null;
584
+ for (const origMonomial of ms) {
585
+ const k = origMonomial.degreeOf(x);
586
+ const monomial = k > 0 ? pm.divX(origMonomial, x) : origMonomial;
587
+ if (monomial === previous) {
588
+ const entry = this.entries[this.entries.length - 1];
589
+ entry.numPowers++;
590
+ if (entry.numPowers > this.maxPowers) this.maxPowers = entry.numPowers;
591
+ } else {
592
+ previous = monomial;
593
+ this.entries.push({ monomial, firstPowerIndex: this.powers.length, numPowers: 1 });
594
+ if (this.maxPowers === 0) this.maxPowers = 1;
595
+ }
596
+ this.origMonomials.push(origMonomial);
597
+ this.powers.push(k);
598
+ }
599
+ }
600
+
601
+ getEntryIndex(monomial: Monomial) {
602
+ for (let index = 0; index < this.entries.length; index++)
603
+ if (this.entries[index].monomial === monomial) return index;
604
+ return -1;
605
+ }
606
+ }
607
+
608
+ const solveLinearEquations = (
609
+ pm: PolynomialManager,
610
+ rows: bigint[][],
611
+ b: bigint[],
612
+ xs: bigint[],
613
+ ) => {
614
+ const n = rows.length;
615
+ for (let k = 0; k < n; k++) {
616
+ let i = k;
617
+ for (; i < n; i++) if (rows[i][k] !== 0n) break;
618
+ if (i === n) return false;
619
+ const row = rows[k];
620
+ rows[k] = rows[i];
621
+ rows[i] = row;
622
+ const rowK = rows[k];
623
+ const pivot = rowK[k];
624
+ for (let column = k + 1; column < n; column++)
625
+ rowK[column] = pm.divNumeral(rowK[column], pivot);
626
+ b[k] = pm.divNumeral(b[k], pivot);
627
+ rowK[k] = pm.normalizeNumeral(1n);
628
+ for (let other = k + 1; other < n; other++) {
629
+ const rowI = rows[other];
630
+ const factor = rowI[k];
631
+ for (let column = k + 1; column < n; column++)
632
+ rowI[column] = pm.normalizeNumeral(rowI[column] - factor * rowK[column]);
633
+ b[other] = pm.normalizeNumeral(b[other] - factor * b[k]);
634
+ rowI[k] = 0n;
635
+ }
636
+ }
637
+ for (let k = n; k-- > 0;) {
638
+ xs[k] = b[k];
639
+ for (let other = k; other-- > 0;) {
640
+ b[other] = pm.normalizeNumeral(b[other] - rows[other][k] * b[k]);
641
+ rows[other][k] = 0n;
642
+ }
643
+ }
644
+ return true;
645
+ };
646
+
647
+ class SparseInterpolator {
648
+ private inputs: bigint[] = [];
649
+ private outputs: bigint[] = [];
650
+
651
+ constructor(
652
+ private readonly pm: PolynomialManager,
653
+ skeleton: Skeleton | null,
654
+ ) {
655
+ if (skeleton !== null)
656
+ for (const entry of skeleton.entries)
657
+ for (let index = 0; index < entry.numPowers; index++) this.outputs.push(0n);
658
+ }
659
+
660
+ reset() {
661
+ this.inputs.length = 0;
662
+ }
663
+
664
+ isReady(skeleton: Skeleton) {
665
+ return this.inputs.length === skeleton.maxPowers;
666
+ }
667
+
668
+ add(skeleton: Skeleton, input: bigint, q: Polynomial) {
669
+ const inputIndex = this.inputs.length;
670
+ this.inputs.push(this.pm.normalizeNumeral(input));
671
+ for (let index = 0; index < q.size; index++) {
672
+ const entryIndex = skeleton.getEntryIndex(q.ms[index]);
673
+ if (entryIndex === -1) return false;
674
+ const entry = skeleton.entries[entryIndex];
675
+ if (inputIndex >= entry.numPowers) continue;
676
+ this.outputs[entry.firstPowerIndex + inputIndex] = this.pm.normalizeNumeral(q.as[index]);
677
+ }
678
+ return true;
679
+ }
680
+
681
+ mk(skeleton: Skeleton, r: PolynomialRef) {
682
+ const pm = this.pm;
683
+ const as: bigint[] = [];
684
+ const ms: Monomial[] = [];
685
+ let rows: bigint[][] = [];
686
+ let b: bigint[] = [];
687
+ for (const entry of skeleton.entries) {
688
+ const numPowers = entry.numPowers;
689
+ if (rows.length !== numPowers) {
690
+ rows = Array.from({ length: numPowers }, () => Array.from({ length: numPowers }, () => 0n));
691
+ b = Array.from({ length: numPowers }, () => 0n);
692
+ }
693
+ const newAs = Array.from({ length: numPowers }, () => 0n);
694
+ for (let index = 0; index < numPowers; index++) {
695
+ const input = this.inputs[index];
696
+ for (let j = 0; j < numPowers; j++)
697
+ rows[index][j] = pm.powerNumeral(input, skeleton.powers[entry.firstPowerIndex + j]);
698
+ b[index] = this.outputs[entry.firstPowerIndex + index];
699
+ }
700
+ if (!solveLinearEquations(pm, rows, b, newAs)) return false;
701
+ for (let index = 0; index < numPowers; index++) {
702
+ if (newAs[index] === 0n) continue;
703
+ as.push(newAs[index]);
704
+ ms.push(skeleton.origMonomials[entry.firstPowerIndex + index]);
705
+ }
706
+ }
707
+ r.set(pm.mkPolynomial(as, ms));
708
+ return true;
709
+ }
342
710
  }
343
711
 
344
712
  export class PolynomialManager {
345
713
  private monomials = new Map<string, Monomial>();
346
714
  private nextPolynomialId = 0;
715
+ private freePolynomialIds: number[] = [];
716
+ private polynomials: (Polynomial | null)[] = [];
717
+ modulus: bigint | null = null;
347
718
  readonly unit: Monomial;
348
719
  readonly zero: Polynomial;
349
720
  readonly one: Polynomial;
350
- private um = new UpolynomialManager();
721
+ private um: UpolynomialManager;
351
722
  private som = new SomBuffer(this);
352
723
  private som2 = new SomBuffer(this);
353
724
  private cheap = new CheapSomBuffer(this);
354
-
355
- constructor() {
725
+ private cheap2 = new CheapSomBuffer(this);
726
+ private random = new RandomGen(0);
727
+ private mgcdInterpolators: NewtonInterpolator[] = [];
728
+ private mgcdSkeletons: (Skeleton | null)[] = [];
729
+ private iccpZpXBuffers: SomBuffer[] = [];
730
+
731
+ constructor(readonly limit: ResourceLimit) {
732
+ this.um = new UpolynomialManager(limit);
356
733
  this.unit = this.mkMonomial([], []);
357
734
  this.zero = this.mkPolynomialCore([], []);
358
- this.one = this.mkPolynomialCore([1n], [this.unit]);
735
+ this.incRef(this.zero);
736
+ this.one = this.mkConstCore(1n);
737
+ this.incRef(this.one);
359
738
  }
360
739
 
361
- // Monomials.
362
-
363
740
  mkMonomial(vars: readonly number[], degrees: readonly number[]) {
364
741
  const key = getMonomialKey(vars, degrees);
365
742
  const existing = this.monomials.get(key);
@@ -369,11 +746,7 @@ export class PolynomialManager {
369
746
  return monomial;
370
747
  }
371
748
 
372
- // rename: every variable x becomes permutation[x], in place in every monomial, as Z3 renames its
373
- // monomial table. Z3 then moves a maximal monomial first in every live polynomial. Here that is
374
- // the given polynomials, the ones nlsat keeps in its atoms. Others keep their order, which
375
- // matches again once the order is restored.
376
- rename(permutation: readonly number[], polynomials: Iterable<Polynomial>) {
749
+ rename(permutation: readonly number[]) {
377
750
  const monomials = new Map<string, Monomial>();
378
751
  for (const monomial of this.monomials.values()) {
379
752
  const order = monomial.vars
@@ -387,10 +760,10 @@ export class PolynomialManager {
387
760
  monomials.set(getMonomialKey(monomial.vars, monomial.degrees), monomial);
388
761
  }
389
762
  this.monomials = monomials;
390
- for (const polynomial of polynomials) polynomial.makeFirstMaximal();
763
+ for (const polynomial of this.polynomials)
764
+ if (polynomial !== null) polynomial.makeFirstMaximal();
391
765
  }
392
766
 
393
- // mk_monomial(x, k): x^k, the unit for k = 0.
394
767
  mkPower(variable: number, power: number) {
395
768
  return power === 0 ? this.unit : this.mkMonomial([variable], [power]);
396
769
  }
@@ -419,7 +792,6 @@ export class PolynomialManager {
419
792
  return this.mkMonomial(vars, degrees);
420
793
  }
421
794
 
422
- // div: m1/m2, or null when m2 does not divide m1.
423
795
  divMonomials(first: Monomial, second: Monomial) {
424
796
  const vars: number[] = [];
425
797
  const degrees: number[] = [];
@@ -439,7 +811,6 @@ export class PolynomialManager {
439
811
  return secondIndex < second.size ? null : this.mkMonomial(vars, degrees);
440
812
  }
441
813
 
442
- // div_x_k: m/x^k.
443
814
  private divXk(monomial: Monomial, variable: number, power: number) {
444
815
  const vars: number[] = [];
445
816
  const degrees: number[] = [];
@@ -455,25 +826,114 @@ export class PolynomialManager {
455
826
  return this.mkMonomial(vars, degrees);
456
827
  }
457
828
 
458
- // div_x: m with x removed.
459
- private divX(monomial: Monomial, variable: number) {
829
+ divX(monomial: Monomial, variable: number) {
460
830
  return this.divXk(monomial, variable, monomial.degreeOf(variable));
461
831
  }
462
832
 
463
- // Construction.
833
+ private sqrtMonomial(monomial: Monomial) {
834
+ return this.mkMonomial(
835
+ monomial.vars,
836
+ monomial.degrees.map((degree) => degree / 2),
837
+ );
838
+ }
839
+
840
+ normalizeNumeral(value: bigint) {
841
+ const modulus = this.modulus;
842
+ return modulus === null ? value : normalizeZp(value, modulus);
843
+ }
844
+
845
+ subNumeral(first: bigint, second: bigint) {
846
+ return this.normalizeNumeral(first - second);
847
+ }
848
+
849
+ mulNumeral(first: bigint, second: bigint) {
850
+ return this.normalizeNumeral(first * second);
851
+ }
852
+
853
+ negNumeral(value: bigint) {
854
+ return this.normalizeNumeral(-value);
855
+ }
856
+
857
+ invNumeral(value: bigint) {
858
+ const modulus = this.modulus;
859
+ if (modulus === null) throw new SmtInvariantError("inverse over Z");
860
+ return normalizeZp(getExtendedGcd(normalizeZp(value, modulus), modulus).x, modulus);
861
+ }
862
+
863
+ divNumeral(dividend: bigint, divisor: bigint) {
864
+ return this.modulus === null
865
+ ? divMpz(dividend, divisor)
866
+ : this.mulNumeral(dividend, this.invNumeral(divisor));
867
+ }
868
+
869
+ powerNumeral(base: bigint, exponent: number) {
870
+ if (exponent === 1) return this.normalizeNumeral(base);
871
+ if (exponent === 0) return this.normalizeNumeral(1n);
872
+ let mask = 1;
873
+ let power = this.normalizeNumeral(base);
874
+ let result = this.normalizeNumeral(1n);
875
+ while (mask <= exponent) {
876
+ if ((mask & exponent) !== 0) result = this.mulNumeral(result, power);
877
+ power = this.mulNumeral(power, power);
878
+ mask <<= 1;
879
+ }
880
+ return result;
881
+ }
882
+
883
+ private dividesNumeral(divisor: bigint, dividend: bigint) {
884
+ if (this.modulus !== null && divisor !== 0n) return true;
885
+ return divisor === 0n ? dividend === 0n : dividend % divisor === 0n;
886
+ }
887
+
888
+ private gcdNumerals(as: readonly bigint[]) {
889
+ let result = 0n;
890
+ for (const coeff of as) result = getGcd(result, coeff);
891
+ return result;
892
+ }
893
+
894
+ normalizeNumerals(as: bigint[]) {
895
+ if (as.length === 0) return;
896
+ const g = this.gcdNumerals(as);
897
+ if (g === 1n) return;
898
+ for (let index = 0; index < as.length; index++) as[index] = this.divNumeral(as[index], g);
899
+ }
900
+
901
+ setZp(prime: bigint) {
902
+ this.modulus = prime;
903
+ }
464
904
 
465
905
  mkPolynomialCore(as: bigint[], ms: Monomial[]) {
466
- return new Polynomial(this.nextPolynomialId++, as, ms);
906
+ const id = this.freePolynomialIds.pop() ?? this.nextPolynomialId++;
907
+ const polynomial = new Polynomial(id, as, ms);
908
+ this.polynomials[id] = polynomial;
909
+ return polynomial;
910
+ }
911
+
912
+ incRef(polynomial: Polynomial) {
913
+ polynomial.refCount++;
914
+ }
915
+
916
+ decRef(polynomial: Polynomial) {
917
+ if (--polynomial.refCount === 0) this.del(polynomial);
918
+ }
919
+
920
+ private del(polynomial: Polynomial) {
921
+ this.polynomials[polynomial.id] = null;
922
+ this.freePolynomialIds.push(polynomial.id);
923
+ }
924
+
925
+ private mkConstCore(value: bigint) {
926
+ return this.mkPolynomialCore([value], [this.unit]);
467
927
  }
468
928
 
469
929
  mkConst(value: bigint) {
470
930
  if (value === 0n) return this.zero;
471
931
  if (value === 1n) return this.one;
472
- return this.mkPolynomialCore([value], [this.unit]);
932
+ return this.mkConstCore(value);
473
933
  }
474
934
 
475
935
  mkVar(variable: number, degree = 1) {
476
- return this.mkPolynomialCore([1n], [this.mkMonomial([variable], [degree])]);
936
+ return this.mkPolynomialCore([1n], [this.mkPower(variable, degree)]);
477
937
  }
478
938
 
479
939
  mkPolynomial(as: readonly bigint[], ms: readonly Monomial[]) {
@@ -482,7 +942,17 @@ export class PolynomialManager {
482
942
  return this.som.mk();
483
943
  }
484
944
 
485
- // mk_linear: sum of as[i]*xs[i] plus c.
945
+ private mkUnivariate(variable: number, coeffs: readonly bigint[]) {
946
+ for (let power = coeffs.length - 1; power >= 0; power--)
947
+ this.cheap.addReset(coeffs[power], this.mkPower(variable, power));
948
+ return this.cheap.mk();
949
+ }
950
+
951
+ toPolynomial(coeffs: readonly bigint[], variable: number) {
952
+ if (coeffs.length === 0) return this.zero;
953
+ return this.mkUnivariate(variable, coeffs);
954
+ }
955
+
486
956
  mkLinear(as: readonly bigint[], vars: readonly number[], constant: bigint) {
487
957
  const coeffs: bigint[] = [];
488
958
  const ms: Monomial[] = [];
@@ -498,8 +968,6 @@ export class PolynomialManager {
498
968
  return this.mkPolynomial(coeffs, ms);
499
969
  }
500
970
 
501
- // Queries.
502
-
503
971
  isZero(polynomial: Polynomial) {
504
972
  return polynomial.size === 0;
505
973
  }
@@ -520,6 +988,15 @@ export class PolynomialManager {
520
988
  return polynomial.size === 0 ? NULL_VAR : polynomial.ms[0].maxVar;
521
989
  }
522
990
 
991
+ getMaxVarOfPolys(polynomials: readonly Polynomial[]) {
992
+ let result = NULL_VAR;
993
+ for (const polynomial of polynomials) {
994
+ const variable = this.maxVar(polynomial);
995
+ if (result === NULL_VAR || variable > result) result = variable;
996
+ }
997
+ return result;
998
+ }
999
+
523
1000
  degree(polynomial: Polynomial, variable: number) {
524
1001
  let result = 0;
525
1002
  for (const monomial of polynomial.ms) result = Math.max(result, monomial.degreeOf(variable));
@@ -532,7 +1009,6 @@ export class PolynomialManager {
532
1009
  return result;
533
1010
  }
534
1011
 
535
- // eq: the same monomials with the same coefficients, in any order.
536
1012
  eq(first: Polynomial, second: Polynomial) {
537
1013
  if (first === second) return true;
538
1014
  if (first.size !== second.size) return false;
@@ -546,8 +1022,6 @@ export class PolynomialManager {
546
1022
  return true;
547
1023
  }
548
1024
 
549
- // The key of the hash-consing table. It lexicographically sorts the polynomial in place, as Z3's
550
- // hash does.
551
1025
  getKey(polynomial: Polynomial) {
552
1026
  polynomial.lexSort();
553
1027
  let key = "";
@@ -556,32 +1030,47 @@ export class PolynomialManager {
556
1030
  return key;
557
1031
  }
558
1032
 
559
- // Arithmetic.
560
-
561
- private addmul(firstCoeff: bigint, first: Polynomial, secondCoeff: bigint, second: Polynomial) {
1033
+ addmulTerms(
1034
+ firstCoeff: bigint,
1035
+ firstMonomial: Monomial,
1036
+ first: Polynomial,
1037
+ secondCoeff: bigint,
1038
+ secondMonomial: Monomial,
1039
+ second: Polynomial,
1040
+ ) {
562
1041
  this.som.reset();
563
- this.som.addmul(firstCoeff, this.unit, first);
564
- this.som.addmul(secondCoeff, this.unit, second);
1042
+ this.som.addmul(firstCoeff, firstMonomial, first);
1043
+ this.som.addmul(secondCoeff, secondMonomial, second);
565
1044
  return this.som.mk();
566
1045
  }
567
1046
 
1047
+ addmul(first: Polynomial, secondCoeff: bigint, second: Polynomial) {
1048
+ return this.addmulTerms(1n, this.unit, first, secondCoeff, this.unit, second);
1049
+ }
1050
+
568
1051
  add(first: Polynomial, second: Polynomial) {
569
- return this.addmul(1n, first, 1n, second);
1052
+ return this.addmulTerms(1n, this.unit, first, 1n, this.unit, second);
570
1053
  }
571
1054
 
572
1055
  sub(first: Polynomial, second: Polynomial) {
573
- return this.addmul(1n, first, -1n, second);
1056
+ return this.addmulTerms(1n, this.unit, first, this.normalizeNumeral(-1n), this.unit, second);
574
1057
  }
575
1058
 
576
- mul(first: Polynomial, second: Polynomial) {
577
- if (first.size === 0 || second.size === 0) return this.zero;
1059
+ muladd(first: Polynomial, second: Polynomial, constant: bigint) {
1060
+ if (first.size === 0 || second.size === 0) return this.mkConst(constant);
578
1061
  this.som.reset();
579
- for (let index = 0; index < first.size; index++)
1062
+ for (let index = 0; index < first.size; index++) {
1063
+ this.limit.checkpoint();
580
1064
  this.som.addmul(first.as[index], first.ms[index], second);
1065
+ }
1066
+ this.som.addTerm(constant, this.unit);
581
1067
  return this.som.mk();
582
1068
  }
583
1069
 
584
- // mul(a, m, p): a*m*p.
1070
+ mul(first: Polynomial, second: Polynomial) {
1071
+ return this.muladd(first, second, 0n);
1072
+ }
1073
+
585
1074
  mulTerm(coeff: bigint, monomial: Monomial, polynomial: Polynomial) {
586
1075
  if (coeff === 0n) return this.zero;
587
1076
  if (coeff === 1n && monomial === this.unit) return polynomial;
@@ -593,30 +1082,42 @@ export class PolynomialManager {
593
1082
  return this.mulTerm(coeff, this.unit, polynomial);
594
1083
  }
595
1084
 
1085
+ private mulScaled(coeff: bigint, first: Polynomial, second: Polynomial) {
1086
+ if (coeff === 0n || first.size === 0 || second.size === 0) return this.zero;
1087
+ this.som.reset();
1088
+ for (let index = 0; index < first.size; index++) {
1089
+ this.limit.checkpoint();
1090
+ this.som.addmul(this.mulNumeral(coeff, first.as[index]), first.ms[index], second);
1091
+ }
1092
+ return this.som.mk();
1093
+ }
1094
+
596
1095
  neg(polynomial: Polynomial) {
597
1096
  for (let index = 0; index < polynomial.size; index++)
598
- this.cheap.add(-polynomial.as[index], polynomial.ms[index]);
1097
+ this.cheap.add(this.negNumeral(polynomial.as[index]), polynomial.ms[index]);
599
1098
  return this.cheap.mk();
600
1099
  }
601
1100
 
602
- pw(polynomial: Polynomial, power: number) {
603
- if (power === 0) return this.one;
604
- let result = polynomial;
605
- for (let index = 1; index < power; index++) result = this.mul(result, polynomial);
606
- return result;
1101
+ coeff(polynomial: Polynomial, variable: number, power: number) {
1102
+ for (let index = 0; index < polynomial.size; index++) {
1103
+ const monomial = polynomial.ms[index];
1104
+ if (monomial.degreeOf(variable) === power)
1105
+ this.cheap.add(polynomial.as[index], this.divX(monomial, variable));
1106
+ }
1107
+ return this.cheap.mk();
607
1108
  }
608
1109
 
609
- // coeff: the coefficient of x^k, a polynomial in the other variables.
610
- coeff(polynomial: Polynomial, variable: number, power: number) {
1110
+ coeffWithReduct(polynomial: Polynomial, variable: number, power: number, reduct: PolynomialRef) {
611
1111
  for (let index = 0; index < polynomial.size; index++) {
612
1112
  const monomial = polynomial.ms[index];
613
1113
  if (monomial.degreeOf(variable) === power)
614
1114
  this.cheap.add(polynomial.as[index], this.divX(monomial, variable));
1115
+ else this.cheap2.add(polynomial.as[index], monomial);
615
1116
  }
1117
+ reduct.set(this.cheap2.mk());
616
1118
  return this.cheap.mk();
617
1119
  }
618
1120
 
619
- // const_coeff: the coefficient of x^k when it is a number, else null.
620
1121
  getConstCoeff(polynomial: Polynomial, variable: number, power: number) {
621
1122
  let result = 0n;
622
1123
  for (let index = 0; index < polynomial.size; index++) {
@@ -628,6 +1129,17 @@ export class PolynomialManager {
628
1129
  return result;
629
1130
  }
630
1131
 
1132
+ isNonzeroConstCoeff(polynomial: Polynomial, variable: number, power: number) {
1133
+ const coeff = this.getConstCoeff(polynomial, variable, power);
1134
+ return coeff !== null && coeff !== 0n;
1135
+ }
1136
+
1137
+ private getUnivCoeff(polynomial: Polynomial, power: number) {
1138
+ for (let index = 0; index < polynomial.size; index++)
1139
+ if (polynomial.ms[index].totalDegree === power) return polynomial.as[index];
1140
+ return 0n;
1141
+ }
1142
+
631
1143
  lc(polynomial: Polynomial, variable: number) {
632
1144
  return this.coeff(polynomial, variable, this.degree(polynomial, variable));
633
1145
  }
@@ -637,18 +1149,19 @@ export class PolynomialManager {
637
1149
  const monomial = polynomial.ms[index];
638
1150
  const degree = monomial.degreeOf(variable);
639
1151
  if (degree > 0)
640
- this.cheap.add(polynomial.as[index] * BigInt(degree), this.divXk(monomial, variable, 1));
1152
+ this.cheap.addReset(
1153
+ this.mulNumeral(polynomial.as[index], BigInt(degree)),
1154
+ this.divXk(monomial, variable, 1),
1155
+ );
641
1156
  }
642
1157
  return this.cheap.mk();
643
1158
  }
644
1159
 
645
- // flip_sign_if_lm_neg: negates p when its graded-lex leading coefficient is negative.
646
1160
  flipSignIfLmNeg(polynomial: Polynomial) {
647
1161
  if (polynomial.size === 0) return polynomial;
648
1162
  return polynomial.as[polynomial.getGradedLexMaxPos()] < 0n ? this.neg(polynomial) : polynomial;
649
1163
  }
650
1164
 
651
- // ic: the integer content, the gcd of the coefficients.
652
1165
  private getIc(polynomial: Polynomial) {
653
1166
  if (polynomial.size === 0) return 0n;
654
1167
  if (this.isConst(polynomial)) return polynomial.as[0];
@@ -660,28 +1173,44 @@ export class PolynomialManager {
660
1173
  return result;
661
1174
  }
662
1175
 
663
- // ic(p, a, c): p = a*c, with the coefficients of c coprime.
664
- private icWithContent(polynomial: Polynomial): [bigint, Polynomial] {
665
- if (polynomial.size === 0) return [0n, polynomial];
666
- if (this.isConst(polynomial)) return [polynomial.as[0], this.one];
667
- let content = 0n;
668
- for (const coeff of polynomial.as) content = getGcd(content, coeff);
669
- if (content === 1n) return [1n, polynomial];
1176
+ private icWithContent(polynomial: Polynomial, c: PolynomialRef) {
1177
+ if (polynomial.size === 0) {
1178
+ c.set(polynomial);
1179
+ return 0n;
1180
+ }
1181
+ if (this.isConst(polynomial)) {
1182
+ c.set(this.one);
1183
+ return polynomial.as[0];
1184
+ }
1185
+ const content = this.gcdNumerals(polynomial.as);
1186
+ if (content === 1n) {
1187
+ c.set(polynomial);
1188
+ return content;
1189
+ }
1190
+ this.cheap.reset();
670
1191
  for (let index = 0; index < polynomial.size; index++)
671
- this.cheap.add(polynomial.as[index] / content, polynomial.ms[index]);
672
- return [content, this.cheap.mk()];
1192
+ this.cheap.addReset(this.divNumeral(polynomial.as[index], content), polynomial.ms[index]);
1193
+ c.set(this.cheap.mk());
1194
+ return content;
673
1195
  }
674
1196
 
675
- // iccp: the integer content, the content and the primitive part of p with respect to x.
676
- iccp(polynomial: Polynomial, variable: number): [bigint, Polynomial, Polynomial] {
677
- if (polynomial.size === 0) return [0n, this.one, polynomial];
678
- if (this.isConst(polynomial)) return [polynomial.as[0], this.one, this.one];
1197
+ iccp(polynomial: Polynomial, variable: number, c: PolynomialRef, pp: PolynomialRef) {
1198
+ if (polynomial.size === 0) {
1199
+ c.set(this.one);
1200
+ pp.set(polynomial);
1201
+ return 0n;
1202
+ }
1203
+ if (this.isConst(polynomial)) {
1204
+ c.set(this.one);
1205
+ pp.set(this.one);
1206
+ return polynomial.as[0];
1207
+ }
679
1208
  const degree = this.degree(polynomial, variable);
680
1209
  if (degree === 0) {
681
- const [integer, content] = this.icWithContent(polynomial);
682
- return [integer, content, this.one];
1210
+ const integer = this.icWithContent(polynomial, c);
1211
+ pp.set(this.one);
1212
+ return integer;
683
1213
  }
684
- // The quick filter: a power of x that occurs only as a pure power means the content is 1.
685
1214
  const filter = Array.from({ length: degree + 1 }, () => 0);
686
1215
  const powers: number[] = [];
687
1216
  for (const monomial of polynomial.ms) {
@@ -689,395 +1218,1265 @@ export class PolynomialManager {
689
1218
  if (filter[power] === 0) powers.push(power);
690
1219
  filter[power] += monomial.size === (power > 0 ? 1 : 0) ? 1 : 2;
691
1220
  }
692
- const [integer, primitive] = this.icWithContent(polynomial);
693
- for (const power of powers) if (filter[power] === 1) return [integer, this.one, primitive];
694
- let content = this.coeff(primitive, variable, powers[0]);
1221
+ for (const power of powers)
1222
+ if (filter[power] === 1) {
1223
+ const integer = this.icWithContent(polynomial, pp);
1224
+ c.set(this.one);
1225
+ return integer;
1226
+ }
1227
+ const integer = this.icWithContent(polynomial, pp);
1228
+ const ci = new PolynomialRef(this);
1229
+ c.set(this.coeff(pp.get(), variable, powers[0]));
695
1230
  for (let index = 1; index < powers.length; index++) {
696
- content = this.gcd(content, this.coeff(primitive, variable, powers[index]));
697
- if (this.isConst(content)) return [integer, this.one, primitive];
1231
+ ci.set(this.coeff(pp.get(), variable, powers[index]));
1232
+ this.gcd(c.get(), ci.get(), c);
1233
+ if (this.isConst(c.get())) {
1234
+ c.set(this.one);
1235
+ ci.reset();
1236
+ return integer;
1237
+ }
698
1238
  }
699
- content = this.flipSignIfLmNeg(content);
700
- return [integer, content, this.exactDiv(primitive, content)];
1239
+ c.set(this.flipSignIfLmNeg(c.get()));
1240
+ pp.set(this.exactDiv(pp.get(), c.get()));
1241
+ ci.reset();
1242
+ return integer;
701
1243
  }
702
1244
 
703
1245
  pp(polynomial: Polynomial, variable: number) {
704
- return this.iccp(polynomial, variable)[2];
1246
+ const c = new PolynomialRef(this);
1247
+ const result = new PolynomialRef(this);
1248
+ this.iccp(polynomial, variable, c, result);
1249
+ c.reset();
1250
+ return result;
705
1251
  }
706
1252
 
707
- // square_free: the integer content times the square-free parts of the content and the primitive
708
- // part in the maximal variable, or p itself when it is square-free.
709
- squareFree(polynomial: Polynomial): Polynomial {
710
- if (this.isConst(polynomial)) return polynomial;
711
- const variable = this.maxVar(polynomial);
712
- const [integer, content, primitive] = this.iccp(polynomial, variable);
713
- const squareFreeContent = this.squareFree(content);
714
- const g = this.gcd(primitive, this.derivative(primitive, variable));
715
- if (this.isConst(g) && this.eq(squareFreeContent, content)) return polynomial;
716
- const squareFreePrimitive = this.isConst(g) ? primitive : this.exactDiv(primitive, g);
717
- return this.mul(this.mulConst(integer, squareFreeContent), squareFreePrimitive);
1253
+ isPrimitive(polynomial: Polynomial, variable: number) {
1254
+ const c = new PolynomialRef(this);
1255
+ const pp = new PolynomialRef(this);
1256
+ this.iccp(polynomial, variable, c, pp);
1257
+ const result = this.eq(polynomial, pp.get());
1258
+ pp.reset();
1259
+ c.reset();
1260
+ return result;
718
1261
  }
719
1262
 
720
- // normalize: p divided by the gcd of its coefficients.
721
- normalize(polynomial: Polynomial) {
722
- if (polynomial.size === 0) return polynomial;
723
- let g = 0n;
724
- for (const coeff of polynomial.as) g = getGcd(g, coeff);
725
- if (g === 1n) return polynomial;
726
- for (let index = 0; index < polynomial.size; index++)
727
- this.cheap.add(polynomial.as[index] / g, polynomial.ms[index]);
728
- return this.cheap.mk();
1263
+ private gcdPrs(first: Polynomial, second: Polynomial, variable: number, r: PolynomialRef) {
1264
+ const isSwapped = this.degree(first, variable) < this.degree(second, variable);
1265
+ const u = isSwapped ? second : first;
1266
+ const v = isSwapped ? first : second;
1267
+ const cU = new PolynomialRef(this);
1268
+ const cV = new PolynomialRef(this);
1269
+ const ppU = new PolynomialRef(this);
1270
+ const ppV = new PolynomialRef(this);
1271
+ const dR = new PolynomialRef(this);
1272
+ const g = new PolynomialRef(this);
1273
+ const h = new PolynomialRef(this);
1274
+ const rem = new PolynomialRef(this);
1275
+ const newH = new PolynomialRef(this);
1276
+ const release = () => {
1277
+ newH.reset();
1278
+ rem.reset();
1279
+ h.reset();
1280
+ g.reset();
1281
+ dR.reset();
1282
+ ppV.reset();
1283
+ ppU.reset();
1284
+ cV.reset();
1285
+ cU.reset();
1286
+ };
1287
+ const iU = this.iccp(u, variable, cU, ppU);
1288
+ const iV = this.iccp(v, variable, cV, ppV);
1289
+ this.gcd(cU.get(), cV.get(), dR);
1290
+ const dA = getGcd(iU, iV);
1291
+ g.set(this.one);
1292
+ h.set(this.one);
1293
+ while (true) {
1294
+ this.limit.checkpoint();
1295
+ const delta = this.degree(ppU.get(), variable) - this.degree(ppV.get(), variable);
1296
+ this.exactPseudoRemainder(ppU.get(), ppV.get(), variable, rem);
1297
+ if (this.isZero(rem.get())) {
1298
+ ppV.set(this.flipSignIfLmNeg(ppV.get()));
1299
+ r.move(this.pp(ppV.get(), variable));
1300
+ r.set(this.mulScaled(dA, dR.get(), r.get()));
1301
+ release();
1302
+ return;
1303
+ }
1304
+ if (this.isConst(rem.get())) {
1305
+ r.set(this.mulConst(dA, dR.get()));
1306
+ release();
1307
+ return;
1308
+ }
1309
+ ppU.copy(ppV);
1310
+ ppV.set(this.exactDiv(rem.get(), g.get()));
1311
+ for (let index = 0; index < delta; index++) ppV.set(this.exactDiv(ppV.get(), h.get()));
1312
+ g.set(this.lc(ppU.get(), variable));
1313
+ newH.set(this.one);
1314
+ for (let index = 0; index < delta; index++) newH.set(this.mul(newH.get(), g.get()));
1315
+ if (delta > 1)
1316
+ for (let index = 0; index < delta - 1; index++)
1317
+ newH.set(this.exactDiv(newH.get(), h.get()));
1318
+ h.copy(newH);
1319
+ }
729
1320
  }
730
1321
 
731
- // nonzero_const_coeff: whether the coefficient of x^k is a nonzero number.
732
- isNonzeroConstCoeff(polynomial: Polynomial, variable: number, power: number) {
733
- const coeff = this.getConstCoeff(polynomial, variable, power);
734
- return coeff !== null && coeff !== 0n;
1322
+ private gcdContent(u: Polynomial, variable: number, v: Polynomial, r: PolynomialRef) {
1323
+ const cU = new PolynomialRef(this);
1324
+ const ppU = new PolynomialRef(this);
1325
+ const iU = this.iccp(u, variable, cU, ppU);
1326
+ cU.set(this.mulConst(iU, cU.get()));
1327
+ this.gcd(cU.get(), v, r);
1328
+ ppU.reset();
1329
+ cU.reset();
735
1330
  }
736
1331
 
737
- // exact_div: p/q, where q divides p.
738
- exactDiv(polynomial: Polynomial, divisor: Polynomial) {
739
- if (polynomial.size === 0) return polynomial;
740
- const remainder = this.som;
741
- const quotient = this.som2;
742
- remainder.reset();
743
- quotient.reset();
744
- remainder.add(polynomial);
745
- const maxPos = divisor.getGradedLexMaxPos();
746
- const divisorMonomial = divisor.ms[maxPos];
747
- const divisorCoeff = divisor.as[maxPos];
1332
+ private euclidGcd(u: Polynomial, v: Polynomial, r: PolynomialRef) {
1333
+ if (this.isZero(u)) {
1334
+ r.set(v);
1335
+ r.set(this.flipSignIfLmNeg(r.get()));
1336
+ return;
1337
+ }
1338
+ if (this.isZero(v)) {
1339
+ r.set(u);
1340
+ r.set(this.flipSignIfLmNeg(r.get()));
1341
+ return;
1342
+ }
1343
+ if (u === v) {
1344
+ r.set(u);
1345
+ r.set(this.flipSignIfLmNeg(r.get()));
1346
+ return;
1347
+ }
1348
+ if (this.isConst(u) || this.isConst(v)) {
1349
+ const iV = this.getIc(v);
1350
+ const iU = this.getIc(u);
1351
+ r.set(this.mkConst(getGcd(iV, iU)));
1352
+ return;
1353
+ }
1354
+ this.gcdPrs(u, v, this.maxVar(u), r);
1355
+ }
1356
+
1357
+ private craCombineImages(
1358
+ c1: Polynomial,
1359
+ b1: bigint,
1360
+ c2: Polynomial,
1361
+ b2: bigint,
1362
+ r: PolynomialRef,
1363
+ ) {
1364
+ c1.lexSort();
1365
+ c2.lexSort();
1366
+ const inverses = getExtendedGcd(b1, b2);
1367
+ const inv1 = modMpz(inverses.x, b2);
1368
+ const inv2 = modMpz(inverses.y, b1);
1369
+ const a1 = this.mulNumeral(b2, inv2);
1370
+ const a2 = this.mulNumeral(b1, inv1);
1371
+ const newBound = this.mulNumeral(b1, b2);
1372
+ const upper = divMpz(newBound, 2n);
1373
+ const add = (first: bigint, second: bigint, monomial: Monomial) => {
1374
+ const tmp3 = this.normalizeNumeral(this.mulNumeral(first, a1) + this.mulNumeral(second, a2));
1375
+ const value = modMpz(tmp3, newBound);
1376
+ this.cheap.add(value > upper ? this.subNumeral(value, newBound) : value, monomial);
1377
+ };
1378
+ let i1 = 0;
1379
+ let i2 = 0;
748
1380
  while (true) {
749
- const remainderPos = remainder.getGradedLexMaxPos();
750
- if (remainderPos === -1) {
751
- remainder.reset();
752
- return quotient.mk();
1381
+ if (i1 === c1.size) {
1382
+ for (; i2 < c2.size; i2++) add(0n, c2.as[i2], c2.ms[i2]);
1383
+ break;
1384
+ }
1385
+ if (i2 === c2.size) {
1386
+ for (; i1 < c1.size; i1++) add(c1.as[i1], 0n, c1.ms[i1]);
1387
+ break;
1388
+ }
1389
+ const m1 = c1.ms[i1];
1390
+ const m2 = c2.ms[i2];
1391
+ const s = lexCompare(m1, m2);
1392
+ if (s === 0) {
1393
+ add(c1.as[i1], c2.as[i2], m1);
1394
+ i1++;
1395
+ i2++;
1396
+ } else if (s > 0) {
1397
+ add(c1.as[i1], 0n, m1);
1398
+ i1++;
1399
+ } else {
1400
+ add(0n, c2.as[i2], m2);
1401
+ i2++;
1402
+ }
1403
+ }
1404
+ r.set(this.cheap.mk());
1405
+ return newBound;
1406
+ }
1407
+
1408
+ private uniModGcd(u: Polynomial, v: Polynomial, r: PolynomialRef) {
1409
+ const x = this.maxVar(u);
1410
+ const ppU = new PolynomialRef(this);
1411
+ const ppV = new PolynomialRef(this);
1412
+ const cU = this.icWithContent(u, ppU);
1413
+ const cV = this.icWithContent(v, ppV);
1414
+ const dA = getGcd(cU, cV);
1415
+ const dU = this.degree(ppU.get(), x);
1416
+ const dV = this.degree(ppV.get(), x);
1417
+ const lcU = this.getUnivCoeff(ppU.get(), dU);
1418
+ const lcV = this.getUnivCoeff(ppV.get(), dV);
1419
+ const lcG = getGcd(lcU, lcV);
1420
+ const uZp = new PolynomialRef(this);
1421
+ const vZp = new PolynomialRef(this);
1422
+ const cStar = new PolynomialRef(this);
1423
+ let bound = 0n;
1424
+ const q = new PolynomialRef(this);
1425
+ const candidate = new PolynomialRef(this);
1426
+ const release = () => {
1427
+ candidate.reset();
1428
+ q.reset();
1429
+ cStar.reset();
1430
+ vZp.reset();
1431
+ uZp.reset();
1432
+ ppV.reset();
1433
+ ppU.reset();
1434
+ };
1435
+ for (const prime of BIG_PRIMES) {
1436
+ const savedModulus = this.modulus;
1437
+ this.setZp(prime);
1438
+ uZp.set(this.normalize(ppU.get()));
1439
+ vZp.set(this.normalize(ppV.get()));
1440
+ const isBadPrime = this.degree(uZp.get(), x) < dU || this.degree(vZp.get(), x) < dV;
1441
+ if (!isBadPrime) {
1442
+ this.euclidGcd(uZp.get(), vZp.get(), q);
1443
+ q.set(this.mkGlexMonic(q.get()));
1444
+ q.set(this.mulConst(this.normalizeNumeral(lcG), q.get()));
1445
+ }
1446
+ this.modulus = savedModulus;
1447
+ if (isBadPrime) continue;
1448
+ if (this.isConst(q.get())) {
1449
+ // Deviation from Z3: when d_a is 1, uni_mod_gcd returns a constant q other than 1, so gcd(2x - 3, 2x - 1) is 2 there.
1450
+ r.set(dA === 1n && q.get().as[0] === 1n ? q.get() : this.mkConst(dA));
1451
+ release();
1452
+ return;
1453
+ }
1454
+ if (cStar.getOrNull() === null) {
1455
+ cStar.copy(q);
1456
+ bound = prime;
1457
+ } else if (this.degree(q.get(), x) < this.degree(cStar.get(), x)) {
1458
+ cStar.copy(q);
1459
+ bound = prime;
1460
+ } else bound = this.craCombineImages(q.get(), prime, cStar.get(), bound, cStar);
1461
+ candidate.move(this.pp(cStar.get(), x));
1462
+ const lcCandidate = this.getUnivCoeff(candidate.get(), this.degree(candidate.get(), x));
1463
+ if (
1464
+ this.dividesNumeral(lcCandidate, lcG) &&
1465
+ this.divides(candidate.get(), ppU.get()) &&
1466
+ this.divides(candidate.get(), ppV.get())
1467
+ ) {
1468
+ r.set(this.mulConst(dA, candidate.get()));
1469
+ r.set(this.flipSignIfLmNeg(r.get()));
1470
+ release();
1471
+ return;
753
1472
  }
754
- const monomial = this.divMonomials(remainder.ms[remainderPos], divisorMonomial);
755
- if (monomial === null) throw new SmtInvariantError("exact_div: the divisor does not divide");
756
- const coeff = remainder.as[remainderPos] / divisorCoeff;
757
- quotient.addTerm(coeff, monomial);
758
- remainder.addmul(-coeff, monomial, divisor);
759
1473
  }
1474
+ this.gcdPrs(u, v, x, r);
1475
+ release();
760
1476
  }
761
1477
 
762
- // exact_pseudo_division: Q and R with lc(q)^(deg(p) - deg(q) + 1) * p = Q*q + R. The
763
- // quotient is only built when asked for, as in pseudo_division_core.
764
- exactPseudoDivision(
765
- polynomial: Polynomial,
766
- divisor: Polynomial,
767
- variable: number,
768
- isQuotient = true,
769
- ) {
770
- return this.pseudoDivisionCore(polynomial, divisor, variable, true, isQuotient);
1478
+ private iccpZpX(polynomial: Polynomial, x: number, c: PolynomialRef, pp: PolynomialRef): bigint {
1479
+ if (polynomial.size === 0) {
1480
+ c.set(this.one);
1481
+ pp.set(polynomial);
1482
+ return 0n;
1483
+ }
1484
+ if (this.isConst(polynomial)) {
1485
+ c.set(this.one);
1486
+ pp.set(this.one);
1487
+ return polynomial.as[0];
1488
+ }
1489
+ const degree = this.degree(polynomial, x);
1490
+ if (degree === 0) {
1491
+ const ci = this.icWithContent(polynomial, pp);
1492
+ c.set(this.one);
1493
+ return ci;
1494
+ }
1495
+ const marks = new Map<number, number>();
1496
+ const noXMonomials: Monomial[] = [];
1497
+ let minDegree = Infinity;
1498
+ for (const monomial of polynomial.ms) {
1499
+ const k = monomial.degreeOf(x);
1500
+ if (k === 0 && !marks.has(monomial.id)) {
1501
+ noXMonomials.push(monomial);
1502
+ marks.set(monomial.id, 1);
1503
+ }
1504
+ if (k < minDegree) minDegree = k;
1505
+ }
1506
+ if (minDegree > 0) {
1507
+ const xmin = new PolynomialRef(this);
1508
+ const newP = new PolynomialRef(this);
1509
+ xmin.set(this.mkVar(x, minDegree));
1510
+ newP.set(this.exactDiv(polynomial, xmin.get()));
1511
+ const ci = this.iccpZpX(newP.get(), x, c, pp);
1512
+ c.set(this.mul(xmin.get(), c.get()));
1513
+ newP.reset();
1514
+ xmin.reset();
1515
+ return ci;
1516
+ }
1517
+ const numMarked = noXMonomials.length;
1518
+ let numUnmarked = 0;
1519
+ for (const monomial of polynomial.ms) {
1520
+ if (monomial.degreeOf(x) === 0) continue;
1521
+ const reduced = this.divX(monomial, x);
1522
+ if (marks.get(reduced.id) === 1) {
1523
+ numUnmarked++;
1524
+ marks.delete(reduced.id);
1525
+ }
1526
+ }
1527
+ if (numUnmarked < numMarked) {
1528
+ const ci = this.icWithContent(polynomial, pp);
1529
+ c.set(this.one);
1530
+ return ci;
1531
+ }
1532
+ const ci = this.icWithContent(polynomial, pp);
1533
+ marks.clear();
1534
+ noXMonomials.length = 0;
1535
+ const buffers = this.iccpZpXBuffers;
1536
+ const ppValue = pp.get();
1537
+ for (let index = 0; index < polynomial.size; index++) {
1538
+ let monomial = ppValue.ms[index];
1539
+ const k = monomial.degreeOf(x);
1540
+ if (k !== 0) monomial = this.divX(monomial, x);
1541
+ let position = marks.get(monomial.id);
1542
+ if (position === undefined) {
1543
+ position = noXMonomials.length;
1544
+ noXMonomials.push(monomial);
1545
+ marks.set(monomial.id, position);
1546
+ }
1547
+ while (buffers.length <= position) buffers.push(new SomBuffer(this));
1548
+ buffers[position].addTerm(ppValue.as[index], this.mkPower(x, k));
1549
+ }
1550
+ const numMonomials = noXMonomials.length;
1551
+ const g = new PolynomialRef(this);
1552
+ const newG = new PolynomialRef(this);
1553
+ g.set(buffers[0].mk());
1554
+ for (let index = 1; index < numMonomials; index++) {
1555
+ const a = new PolynomialRef(this);
1556
+ a.set(buffers[index].mk());
1557
+ this.euclidGcd(g.get(), a.get(), newG);
1558
+ g.copy(newG);
1559
+ const isDone = this.isConst(g.get());
1560
+ a.reset();
1561
+ if (isDone) break;
1562
+ }
1563
+ if (!this.isConst(g.get())) {
1564
+ c.copy(g);
1565
+ pp.set(this.exactDiv(pp.get(), c.get()));
1566
+ } else c.set(this.one);
1567
+ for (let index = 0; index < numMonomials; index++) buffers[index].reset();
1568
+ newG.reset();
1569
+ g.reset();
1570
+ return ci;
1571
+ }
1572
+
1573
+ private lcGlexZpX(polynomial: Polynomial, x: number) {
1574
+ this.som.reset();
1575
+ let maxMonomial: Monomial | null = null;
1576
+ for (let index = 0; index < polynomial.size; index++) {
1577
+ let monomial = polynomial.ms[index];
1578
+ const k = monomial.degreeOf(x);
1579
+ if (k !== 0) monomial = this.divX(monomial, x);
1580
+ if (maxMonomial === null || gradedLexCompare(monomial, maxMonomial) > 0) {
1581
+ this.som.reset();
1582
+ maxMonomial = monomial;
1583
+ this.som.addTerm(polynomial.as[index], this.mkPower(x, k));
1584
+ } else if (maxMonomial === monomial)
1585
+ this.som.addTerm(polynomial.as[index], this.mkPower(x, k));
1586
+ }
1587
+ return this.som.mk();
1588
+ }
1589
+
1590
+ private primitiveZpX(polynomial: Polynomial, x: number, pp: PolynomialRef) {
1591
+ const c = new PolynomialRef(this);
1592
+ this.iccpZpX(polynomial, x, c, pp);
1593
+ c.reset();
1594
+ }
1595
+
1596
+ private peekFresh(values: readonly bigint[], prime: number) {
1597
+ while (true) {
1598
+ const hi = this.random.next();
1599
+ const lo = this.random.next();
1600
+ const value = this.normalizeNumeral(BigInt(((hi << 15) | lo) % prime));
1601
+ if (!values.includes(value)) return value;
1602
+ }
1603
+ }
1604
+
1605
+ private univEval(polynomial: Polynomial, value: bigint) {
1606
+ if (polynomial.size === 0) return 0n;
1607
+ if (this.isConst(polynomial)) return this.normalizeNumeral(polynomial.as[0]);
1608
+ polynomial.lexSort();
1609
+ let result = 0n;
1610
+ for (let index = 0; index < polynomial.size; index++)
1611
+ result = this.normalizeNumeral(
1612
+ result +
1613
+ this.mulNumeral(
1614
+ polynomial.as[index],
1615
+ this.powerNumeral(value, polynomial.ms[index].totalDegree),
1616
+ ),
1617
+ );
1618
+ return result;
1619
+ }
1620
+
1621
+ private modGcdRec(
1622
+ u: Polynomial,
1623
+ v: Polynomial,
1624
+ prime: number,
1625
+ idx: number,
1626
+ vars: readonly number[],
1627
+ r: PolynomialRef,
1628
+ ): boolean {
1629
+ if (idx === vars.length - 1) {
1630
+ this.euclidGcd(u, v, r);
1631
+ return true;
1632
+ }
1633
+ const x = vars[idx];
1634
+ const cU = new PolynomialRef(this);
1635
+ const ppU = new PolynomialRef(this);
1636
+ const lcU = new PolynomialRef(this);
1637
+ const cV = new PolynomialRef(this);
1638
+ const ppV = new PolynomialRef(this);
1639
+ const lcV = new PolynomialRef(this);
1640
+ const cG = new PolynomialRef(this);
1641
+ const lcG = new PolynomialRef(this);
1642
+ const u1 = new PolynomialRef(this);
1643
+ const v1 = new PolynomialRef(this);
1644
+ const q = new PolynomialRef(this);
1645
+ const h = new PolynomialRef(this);
1646
+ const c = new PolynomialRef(this);
1647
+ const lcH = new PolynomialRef(this);
1648
+ try {
1649
+ const ciU = this.iccpZpX(u, x, cU, ppU);
1650
+ const ciV = this.iccpZpX(v, x, cV, ppV);
1651
+ lcU.set(this.lcGlexZpX(ppU.get(), x));
1652
+ lcV.set(this.lcGlexZpX(ppV.get(), x));
1653
+ const ciG = getGcd(ciU, ciV);
1654
+ this.euclidGcd(cU.get(), cV.get(), cG);
1655
+ this.euclidGcd(lcU.get(), lcV.get(), lcG);
1656
+ const skeleton = this.mgcdSkeletons[idx];
1657
+ while (this.mgcdInterpolators.length <= idx)
1658
+ this.mgcdInterpolators.push(new NewtonInterpolator(this));
1659
+ const interpolator = this.mgcdInterpolators[idx];
1660
+ const sparseInterpolator = new SparseInterpolator(this, skeleton);
1661
+ let minDegQ = Infinity;
1662
+ while (true) {
1663
+ let value = 0n;
1664
+ let lcGValue = 0n;
1665
+ while (true) {
1666
+ value = this.peekFresh(interpolator.inputs, prime);
1667
+ lcGValue = this.univEval(lcG.get(), value);
1668
+ if (lcGValue !== 0n) break;
1669
+ }
1670
+ u1.set(this.substitute(ppU.get(), [x], [value]));
1671
+ v1.set(this.substitute(ppV.get(), [x], [value]));
1672
+ if (!this.modGcdRec(u1.get(), v1.get(), prime, idx + 1, vars, q)) return false;
1673
+ q.set(this.mkGlexMonic(q.get()));
1674
+ q.set(this.mulConst(lcGValue, q.get()));
1675
+ const qVar = this.maxVar(q.get());
1676
+ const degQ = qVar === NULL_VAR ? 0 : this.degree(q.get(), qVar);
1677
+ if (degQ < minDegQ) {
1678
+ minDegQ = degQ;
1679
+ if (skeleton === null) {
1680
+ interpolator.reset();
1681
+ interpolator.add(value, q.get());
1682
+ } else {
1683
+ sparseInterpolator.reset();
1684
+ if (!sparseInterpolator.add(skeleton, value, q.get())) return false;
1685
+ }
1686
+ } else if (degQ === minDegQ) {
1687
+ if (skeleton === null) interpolator.add(value, q.get());
1688
+ else if (!sparseInterpolator.add(skeleton, value, q.get())) return false;
1689
+ } else continue;
1690
+ let isCandidate = false;
1691
+ if (skeleton === null) {
1692
+ interpolator.mk(x, h);
1693
+ lcH.set(this.lcGlexZpX(h.get(), x));
1694
+ if (this.eq(lcH.get(), lcG.get())) isCandidate = true;
1695
+ } else if (sparseInterpolator.isReady(skeleton)) {
1696
+ if (!sparseInterpolator.mk(skeleton, h)) return false;
1697
+ isCandidate = true;
1698
+ }
1699
+ if (!isCandidate) continue;
1700
+ if (this.degree(h.get(), x) > 0) this.primitiveZpX(h.get(), x, c);
1701
+ else c.set(this.normalize(h.get()));
1702
+ if (this.divides(c.get(), ppU.get()) && this.divides(c.get(), ppV.get())) {
1703
+ r.set(this.mul(cG.get(), c.get()));
1704
+ r.set(this.mulConst(ciG, r.get()));
1705
+ } else if (minDegQ === 0) {
1706
+ r.copy(cG);
1707
+ r.set(this.mulConst(ciG, r.get()));
1708
+ } else if (skeleton !== null) return false;
1709
+ else continue;
1710
+ if (skeleton === null) this.mgcdSkeletons[idx] = new Skeleton(this, h.get(), x);
1711
+ return true;
1712
+ }
1713
+ } finally {
1714
+ lcH.reset();
1715
+ c.reset();
1716
+ h.reset();
1717
+ q.reset();
1718
+ v1.reset();
1719
+ u1.reset();
1720
+ lcG.reset();
1721
+ cG.reset();
1722
+ lcV.reset();
1723
+ ppV.reset();
1724
+ cV.reset();
1725
+ lcU.reset();
1726
+ ppU.reset();
1727
+ cU.reset();
1728
+ }
1729
+ }
1730
+
1731
+ private modGcd(
1732
+ u: Polynomial,
1733
+ v: Polynomial,
1734
+ uDegrees: readonly [number, number][],
1735
+ vDegrees: readonly [number, number][],
1736
+ r: PolynomialRef,
1737
+ ): boolean {
1738
+ const minDegrees = uDegrees.map((entry, index): [number, number] => [
1739
+ entry[0],
1740
+ Math.min(entry[1], vDegrees[index][1]),
1741
+ ]);
1742
+ minDegrees.sort((first, second) => first[1] - second[1] || first[0] - second[0]);
1743
+ this.mgcdSkeletons = minDegrees.map(() => null);
1744
+ const vars = minDegrees.map((entry) => entry[0]);
1745
+ const ppU = new PolynomialRef(this);
1746
+ const ppV = new PolynomialRef(this);
1747
+ const uZp = new PolynomialRef(this);
1748
+ const vZp = new PolynomialRef(this);
1749
+ const cStar = new PolynomialRef(this);
1750
+ const q = new PolynomialRef(this);
1751
+ const candidate = new PolynomialRef(this);
1752
+ try {
1753
+ const cU = this.icWithContent(u, ppU);
1754
+ const cV = this.icWithContent(v, ppV);
1755
+ const dA = getGcd(cU, cV);
1756
+ const lcU = ppU.get().as[ppU.get().getGradedLexMaxPos()];
1757
+ const lcV = ppV.get().as[ppV.get().getGradedLexMaxPos()];
1758
+ const lcG = getGcd(lcU, lcV);
1759
+ let bound = 0n;
1760
+ for (const prime of BIG_PRIMES) {
1761
+ const savedModulus = this.modulus;
1762
+ this.setZp(prime);
1763
+ try {
1764
+ uZp.set(this.normalize(ppU.get()));
1765
+ if (uZp.get().size !== ppU.get().size) continue;
1766
+ vZp.set(this.normalize(ppV.get()));
1767
+ if (vZp.get().size !== ppV.get().size) continue;
1768
+ if (!this.modGcdRec(uZp.get(), vZp.get(), Number(prime), 0, vars, q)) return false;
1769
+ q.set(this.mkGlexMonic(q.get()));
1770
+ q.set(this.mulConst(this.normalizeNumeral(lcG), q.get()));
1771
+ } finally {
1772
+ this.modulus = savedModulus;
1773
+ }
1774
+ if (this.isConst(q.get())) {
1775
+ r.set(this.mkConst(dA));
1776
+ return true;
1777
+ }
1778
+ if (cStar.getOrNull() === null) {
1779
+ cStar.copy(q);
1780
+ bound = prime;
1781
+ } else {
1782
+ const maxCStar = cStar.get().ms[cStar.get().getGradedLexMaxPos()];
1783
+ const maxQ = q.get().ms[q.get().getGradedLexMaxPos()];
1784
+ if (gradedLexCompare(maxQ, maxCStar) < 0) {
1785
+ cStar.copy(q);
1786
+ bound = prime;
1787
+ } else bound = this.craCombineImages(q.get(), prime, cStar.get(), bound, cStar);
1788
+ }
1789
+ candidate.set(this.normalize(cStar.get()));
1790
+ const lcCandidate = candidate.get().as[candidate.get().getGradedLexMaxPos()];
1791
+ if (
1792
+ this.dividesNumeral(lcCandidate, lcG) &&
1793
+ this.divides(candidate.get(), ppU.get()) &&
1794
+ this.divides(candidate.get(), ppV.get())
1795
+ ) {
1796
+ r.set(this.mulConst(dA, candidate.get()));
1797
+ r.set(this.flipSignIfLmNeg(r.get()));
1798
+ return true;
1799
+ }
1800
+ }
1801
+ this.gcdPrs(u, v, this.maxVar(u), r);
1802
+ return true;
1803
+ } finally {
1804
+ candidate.reset();
1805
+ q.reset();
1806
+ cStar.reset();
1807
+ vZp.reset();
1808
+ uZp.reset();
1809
+ ppV.reset();
1810
+ ppU.reset();
1811
+ }
1812
+ }
1813
+
1814
+ private getVarMaxDegrees(polynomial: Polynomial) {
1815
+ return [...this.getMaxDegrees(polynomial).entries()].sort(
1816
+ (first, second) => first[0] - second[0],
1817
+ );
1818
+ }
1819
+
1820
+ gcd(u: Polynomial, v: Polynomial, r: PolynomialRef) {
1821
+ if (this.isZero(u)) {
1822
+ r.set(v);
1823
+ r.set(this.flipSignIfLmNeg(r.get()));
1824
+ return;
1825
+ }
1826
+ if (this.isZero(v)) {
1827
+ r.set(u);
1828
+ r.set(this.flipSignIfLmNeg(r.get()));
1829
+ return;
1830
+ }
1831
+ if (u === v) {
1832
+ r.set(u);
1833
+ r.set(this.flipSignIfLmNeg(r.get()));
1834
+ return;
1835
+ }
1836
+ if (this.isConst(u) || this.isConst(v)) {
1837
+ const iV = this.getIc(v);
1838
+ const iU = this.getIc(u);
1839
+ r.set(this.mkConst(getGcd(iV, iU)));
1840
+ return;
1841
+ }
1842
+ const uDegrees = this.getVarMaxDegrees(u);
1843
+ const vDegrees = this.getVarMaxDegrees(v);
1844
+ const size = Math.min(uDegrees.length, vDegrees.length);
1845
+ for (let index = 0; index < size; index++) {
1846
+ const xu = uDegrees[index][0];
1847
+ const xv = vDegrees[index][0];
1848
+ if (xu < xv) {
1849
+ this.gcdContent(u, xu, v, r);
1850
+ return;
1851
+ }
1852
+ if (xu > xv) {
1853
+ this.gcdContent(v, xv, u, r);
1854
+ return;
1855
+ }
1856
+ }
1857
+ if (size < uDegrees.length) {
1858
+ this.gcdContent(u, uDegrees[size][0], v, r);
1859
+ return;
1860
+ }
1861
+ if (size < vDegrees.length) {
1862
+ this.gcdContent(v, vDegrees[size][0], u, r);
1863
+ return;
1864
+ }
1865
+ const x = uDegrees[size - 1][0];
1866
+ if (this.modulus !== null) {
1867
+ this.gcdPrs(u, v, x, r);
1868
+ return;
1869
+ }
1870
+ if (this.isUnivariate(u)) {
1871
+ this.uniModGcd(u, v, r);
1872
+ return;
1873
+ }
1874
+ if (!this.modGcd(u, v, uDegrees, vDegrees, r)) this.gcdPrs(u, v, x, r);
1875
+ }
1876
+
1877
+ squareFree(polynomial: Polynomial, r: PolynomialRef) {
1878
+ if (this.isZero(polynomial)) {
1879
+ r.set(this.zero);
1880
+ return;
1881
+ }
1882
+ if (this.isConst(polynomial)) {
1883
+ r.set(polynomial);
1884
+ return;
1885
+ }
1886
+ const x = this.maxVar(polynomial);
1887
+ const c = new PolynomialRef(this);
1888
+ const pp = new PolynomialRef(this);
1889
+ const integer = this.iccp(polynomial, x, c, pp);
1890
+ const sqfC = new PolynomialRef(this);
1891
+ this.squareFree(c.get(), sqfC);
1892
+ const ppPrime = new PolynomialRef(this);
1893
+ ppPrime.set(this.derivative(pp.get(), x));
1894
+ const g = new PolynomialRef(this);
1895
+ this.gcd(pp.get(), ppPrime.get(), g);
1896
+ const release = () => {
1897
+ g.reset();
1898
+ ppPrime.reset();
1899
+ sqfC.reset();
1900
+ pp.reset();
1901
+ c.reset();
1902
+ };
1903
+ if (this.isConst(g.get())) {
1904
+ if (this.eq(sqfC.get(), c.get())) {
1905
+ r.set(polynomial);
1906
+ release();
1907
+ return;
1908
+ }
1909
+ } else pp.set(this.exactDiv(pp.get(), g.get()));
1910
+ r.set(this.mulConst(integer, sqfC.get()));
1911
+ r.set(this.mul(r.get(), pp.get()));
1912
+ release();
1913
+ }
1914
+
1915
+ private squareFreeIn(polynomial: Polynomial, x: number, r: PolynomialRef) {
1916
+ if (this.isZero(polynomial)) {
1917
+ r.set(this.zero);
1918
+ return;
1919
+ }
1920
+ if (this.isConst(polynomial)) {
1921
+ r.set(polynomial);
1922
+ return;
1923
+ }
1924
+ const pPrime = new PolynomialRef(this);
1925
+ pPrime.set(this.derivative(polynomial, x));
1926
+ const g = new PolynomialRef(this);
1927
+ this.gcd(polynomial, pPrime.get(), g);
1928
+ if (this.isConst(g.get())) r.set(polynomial);
1929
+ else r.set(this.exactDiv(polynomial, g.get()));
1930
+ g.reset();
1931
+ pPrime.reset();
1932
+ }
1933
+
1934
+ private isSquareFreeIn(polynomial: Polynomial, x: number) {
1935
+ const r = new PolynomialRef(this);
1936
+ this.squareFreeIn(polynomial, x, r);
1937
+ const result = polynomial === r.get();
1938
+ r.reset();
1939
+ return result;
1940
+ }
1941
+
1942
+ pw(polynomial: Polynomial, k: number, r: PolynomialRef) {
1943
+ if (k === 0) {
1944
+ r.set(this.one);
1945
+ return;
1946
+ }
1947
+ if (k === 1) {
1948
+ r.set(polynomial);
1949
+ return;
1950
+ }
1951
+ const result = new PolynomialRef(this);
1952
+ result.set(polynomial);
1953
+ for (let index = 1; index < k; index++) result.set(this.mul(result.get(), polynomial));
1954
+ r.copy(result);
1955
+ result.reset();
1956
+ }
1957
+
1958
+ composeXDivY(polynomial: Polynomial, y: number) {
1959
+ if (this.isConst(polynomial)) return polynomial;
1960
+ const x = this.maxVar(polynomial);
1961
+ const n = this.degree(polynomial, x);
1962
+ for (let index = 0; index < polynomial.size; index++) {
1963
+ const k = polynomial.ms[index].degreeOf(x);
1964
+ const vars: number[] = [];
1965
+ const degrees: number[] = [];
1966
+ const push = (variable: number, degree: number) => {
1967
+ if (degree === 0) return;
1968
+ vars.push(variable);
1969
+ degrees.push(degree);
1970
+ };
1971
+ if (x < y) {
1972
+ push(x, k);
1973
+ push(y, n - k);
1974
+ } else {
1975
+ push(y, n - k);
1976
+ push(x, k);
1977
+ }
1978
+ this.cheap.add(polynomial.as[index], this.mkMonomial(vars, degrees));
1979
+ }
1980
+ return this.cheap.mk();
771
1981
  }
772
1982
 
773
- // pseudo_remainder: R with lc(q)^d * p = Q*q + R, where d counts the division steps.
774
- pseudoRemainder(polynomial: Polynomial, divisor: Polynomial, variable: number) {
775
- return this.pseudoDivisionCore(polynomial, divisor, variable, false, false);
1983
+ private compose(polynomial: Polynomial, q: Polynomial, r: PolynomialRef) {
1984
+ if (this.isConst(polynomial)) {
1985
+ r.set(polynomial);
1986
+ return;
1987
+ }
1988
+ const x = this.maxVar(polynomial);
1989
+ const d = this.degree(polynomial, x);
1990
+ const degree2pos = Array.from({ length: d + 1 }, () => -1);
1991
+ for (let index = 0; index < polynomial.size; index++)
1992
+ degree2pos[polynomial.ms[index].totalDegree] = index;
1993
+ r.set(this.mkConst(polynomial.as[degree2pos[d]]));
1994
+ for (let index = 1; index <= d; index++) {
1995
+ const position = degree2pos[d - index];
1996
+ r.set(this.muladd(q, r.get(), position === -1 ? 0n : polynomial.as[position]));
1997
+ }
1998
+ }
1999
+
2000
+ private mkXMinusY(x: number, y: number) {
2001
+ return this.mkLinear([1n, this.normalizeNumeral(-1n)], [x, y], 0n);
2002
+ }
2003
+
2004
+ composeXMinusY(polynomial: Polynomial, y: number, r: PolynomialRef) {
2005
+ const x = this.maxVar(polynomial);
2006
+ if (y === x) {
2007
+ r.set(this.coeff(polynomial, x, 0));
2008
+ return;
2009
+ }
2010
+ const xMinusY = new PolynomialRef(this);
2011
+ xMinusY.set(this.mkXMinusY(x, y));
2012
+ this.compose(polynomial, xMinusY.get(), r);
2013
+ xMinusY.reset();
776
2014
  }
777
2015
 
778
2016
  private pseudoDivisionCore(
779
- polynomial: Polynomial,
780
- divisor: Polynomial,
781
- variable: number,
2017
+ p: Polynomial,
2018
+ q: Polynomial,
2019
+ x: number,
782
2020
  isExact: boolean,
783
2021
  isQuotient: boolean,
2022
+ quotient: PolynomialRef,
2023
+ remainder: PolynomialRef,
784
2024
  ) {
785
- const degA = this.degree(polynomial, variable);
786
- const degB = this.degree(divisor, variable);
2025
+ const a = p;
2026
+ const b = q;
2027
+ const degA = this.degree(a, x);
2028
+ const degB = this.degree(b, x);
787
2029
  if (degB === 0) {
788
- const steps = isExact ? degA + 1 : 1;
789
- if (!isQuotient || !isExact || degA === 0)
790
- return { quotient: polynomial, remainder: this.zero, steps };
791
- return {
792
- quotient: this.mul(polynomial, this.pw(divisor, degA)),
793
- remainder: this.zero,
794
- steps,
795
- };
2030
+ remainder.set(this.zero);
2031
+ if (!isQuotient) return 0;
2032
+ if (!isExact) {
2033
+ quotient.set(a);
2034
+ return 1;
2035
+ }
2036
+ const d = degA + 1;
2037
+ if (d === 1) {
2038
+ quotient.set(a);
2039
+ return d;
2040
+ }
2041
+ const bdm1 = new PolynomialRef(this);
2042
+ this.pw(b, d - 1, bdm1);
2043
+ quotient.set(this.mul(a, bdm1.get()));
2044
+ bdm1.reset();
2045
+ return d;
796
2046
  }
797
- const lcB = this.coeff(divisor, variable, degB);
798
- const reductB = this.reduct(divisor, variable, degB);
799
- let remainder = polynomial;
800
- let quotient = this.zero;
801
- let steps = 0;
2047
+ if (degB > degA) {
2048
+ quotient.set(this.zero);
2049
+ remainder.set(a);
2050
+ }
2051
+ const lB = new PolynomialRef(this);
2052
+ const rB = new PolynomialRef(this);
2053
+ lB.set(this.coeffWithReduct(b, x, degB, rB));
2054
+ let d = 0;
2055
+ remainder.set(a);
2056
+ quotient.set(this.zero);
802
2057
  while (true) {
803
- const degR = this.degree(remainder, variable);
2058
+ this.limit.checkpoint();
2059
+ const r = remainder.get();
2060
+ const degR = this.degree(r, x);
804
2061
  if (degB > degR) {
805
- const exactSteps = degA - degB + 1;
806
- if (isExact && steps < exactSteps) {
807
- const power = this.pw(lcB, exactSteps - steps);
808
- if (isQuotient) quotient = this.mul(power, quotient);
809
- remainder = this.mul(power, remainder);
2062
+ if (isExact) {
2063
+ const exactD = degA - degB + 1;
2064
+ if (d < exactD) {
2065
+ const lBE = new PolynomialRef(this);
2066
+ this.pw(lB.get(), exactD - d, lBE);
2067
+ if (isQuotient) quotient.set(this.mul(lBE.get(), quotient.get()));
2068
+ remainder.set(this.mul(lBE.get(), remainder.get()));
2069
+ lBE.reset();
2070
+ }
810
2071
  }
811
- return { quotient, remainder, steps };
2072
+ rB.reset();
2073
+ lB.reset();
2074
+ return d;
812
2075
  }
813
2076
  this.som.reset();
814
2077
  this.som2.reset();
815
- for (let index = 0; index < remainder.size; index++) {
816
- const monomial = remainder.ms[index];
817
- const coeff = remainder.as[index];
818
- if (monomial.degreeOf(variable) === degR) {
819
- const shifted = this.divXk(monomial, variable, degB);
2078
+ for (let index = 0; index < r.size; index++) {
2079
+ if (r.size > 100 && index % 100 === 0) this.limit.checkpoint();
2080
+ const monomial = r.ms[index];
2081
+ const coeff = r.as[index];
2082
+ if (monomial.degreeOf(x) === degR) {
2083
+ const shifted = this.divXk(monomial, x, degB);
820
2084
  if (isQuotient) this.som2.addTerm(coeff, shifted);
821
- this.som.addmul(-coeff, shifted, reductB);
822
- } else this.som.addmul(coeff, monomial, lcB);
2085
+ this.som.addmul(this.negNumeral(coeff), shifted, rB.get());
2086
+ } else this.som.addmul(coeff, monomial, lB.get());
823
2087
  }
824
- remainder = this.som.mk();
2088
+ remainder.set(this.som.mk());
825
2089
  if (isQuotient) {
826
- for (let index = 0; index < quotient.size; index++)
827
- this.som2.addmul(quotient.as[index], quotient.ms[index], lcB);
828
- quotient = this.som2.mk();
2090
+ const current = quotient.get();
2091
+ for (let index = 0; index < current.size; index++)
2092
+ this.som2.addmul(current.as[index], current.ms[index], lB.get());
2093
+ quotient.set(this.som2.mk());
829
2094
  }
830
- steps++;
2095
+ d++;
831
2096
  }
832
2097
  }
833
2098
 
834
- exactPseudoRemainder(polynomial: Polynomial, divisor: Polynomial, variable: number) {
835
- return this.exactPseudoDivision(polynomial, divisor, variable, false).remainder;
2099
+ exactPseudoRemainder(p: Polynomial, q: Polynomial, x: number, remainder: PolynomialRef) {
2100
+ const quotient = new PolynomialRef(this);
2101
+ this.pseudoDivisionCore(p, q, x, true, false, quotient, remainder);
2102
+ quotient.reset();
836
2103
  }
837
2104
 
838
- // The reduct of coeff(p, x, k, reduct): p without its x^k monomials.
839
- reduct(polynomial: Polynomial, variable: number, power: number) {
840
- for (let index = 0; index < polynomial.size; index++)
841
- if (polynomial.ms[index].degreeOf(variable) !== power)
842
- this.cheap.add(polynomial.as[index], polynomial.ms[index]);
843
- return this.cheap.mk();
2105
+ pseudoRemainder(p: Polynomial, q: Polynomial, x: number, remainder: PolynomialRef) {
2106
+ const quotient = new PolynomialRef(this);
2107
+ const d = this.pseudoDivisionCore(p, q, x, false, false, quotient, remainder);
2108
+ quotient.reset();
2109
+ return d;
844
2110
  }
845
2111
 
846
- // var_max_degrees, sorted by variable.
847
- private getVarMaxDegrees(polynomial: Polynomial) {
848
- const degrees = new Map<number, number>();
849
- for (const monomial of polynomial.ms)
850
- for (let index = 0; index < monomial.size; index++) {
851
- const variable = monomial.vars[index];
852
- degrees.set(variable, Math.max(degrees.get(variable) ?? 0, monomial.degrees[index]));
853
- }
854
- return [...degrees.entries()].sort((first, second) => first[0] - second[0]);
855
- }
856
-
857
- // gcd: the greatest common divisor, with a positive integer content and leading coefficient.
858
- gcd(first: Polynomial, second: Polynomial): Polynomial {
859
- if (first.size === 0) return this.flipSignIfLmNeg(second);
860
- if (second.size === 0) return this.flipSignIfLmNeg(first);
861
- if (first === second) return this.flipSignIfLmNeg(first);
862
- if (this.isConst(first) || this.isConst(second))
863
- return this.mkConst(getGcd(this.getIc(second), this.getIc(first)));
864
- const firstDegrees = this.getVarMaxDegrees(first);
865
- const secondDegrees = this.getVarMaxDegrees(second);
866
- const size = Math.min(firstDegrees.length, secondDegrees.length);
867
- for (let index = 0; index < size; index++) {
868
- const firstVar = firstDegrees[index][0];
869
- const secondVar = secondDegrees[index][0];
870
- if (firstVar < secondVar) return this.gcdContent(first, firstVar, second);
871
- if (firstVar > secondVar) return this.gcdContent(second, secondVar, first);
872
- }
873
- if (size < firstDegrees.length) return this.gcdContent(first, firstDegrees[size][0], second);
874
- if (size < secondDegrees.length) return this.gcdContent(second, secondDegrees[size][0], first);
875
- return this.gcdPrs(first, second, firstDegrees[size - 1][0]);
876
- }
877
-
878
- // gcd_content: gcd(content(u, x), v).
879
- private gcdContent(polynomial: Polynomial, variable: number, other: Polynomial) {
880
- const [integer, content] = this.iccp(polynomial, variable);
881
- return this.gcd(this.mulConst(integer, content), other);
882
- }
883
-
884
- // gcd_prs: Collins' subresultant polynomial remainder sequence.
885
- private gcdPrs(first: Polynomial, second: Polynomial, variable: number) {
886
- const [u, v] =
887
- this.degree(first, variable) < this.degree(second, variable)
888
- ? [second, first]
889
- : [first, second];
890
- const [integerU, contentU, primitiveU] = this.iccp(u, variable);
891
- const [integerV, contentV, primitiveV] = this.iccp(v, variable);
892
- const contentGcd = this.gcd(contentU, contentV);
893
- const integerGcd = getGcd(integerU, integerV);
894
- let ppU = primitiveU;
895
- let ppV = primitiveV;
896
- let g = this.one;
897
- let h = this.one;
898
- while (true) {
899
- const delta = this.degree(ppU, variable) - this.degree(ppV, variable);
900
- const remainder = this.exactPseudoRemainder(ppU, ppV, variable);
901
- if (remainder.size === 0) {
902
- const result = this.pp(this.flipSignIfLmNeg(ppV), variable);
903
- return this.mulConst(integerGcd, this.mul(contentGcd, result));
904
- }
905
- if (this.isConst(remainder)) return this.mulConst(integerGcd, contentGcd);
906
- ppU = ppV;
907
- ppV = this.exactDiv(remainder, g);
908
- for (let index = 0; index < delta; index++) ppV = this.exactDiv(ppV, h);
909
- g = this.lc(ppU, variable);
910
- let newH = this.one;
911
- for (let index = 0; index < delta; index++) newH = this.mul(newH, g);
912
- for (let index = 1; index < delta; index++) newH = this.exactDiv(newH, h);
913
- h = newH;
914
- }
2112
+ exactPseudoDivision(
2113
+ p: Polynomial,
2114
+ q: Polynomial,
2115
+ x: number,
2116
+ quotient: PolynomialRef,
2117
+ remainder: PolynomialRef,
2118
+ ) {
2119
+ this.pseudoDivisionCore(p, q, x, true, true, quotient, remainder);
915
2120
  }
916
2121
 
917
- // get_min_degree_var: the first variable, in order of occurrence, of minimal degree.
918
- private getMinDegreeVar(polynomial: Polynomial) {
919
- const degrees = new Map<number, number>();
920
- for (const monomial of polynomial.ms)
921
- for (let index = 0; index < monomial.size; index++) {
922
- const variable = monomial.vars[index];
923
- if (monomial.degrees[index] > (degrees.get(variable) ?? 0))
924
- degrees.set(variable, monomial.degrees[index]);
925
- }
926
- let result = NULL_VAR;
927
- let minDegree = Infinity;
928
- for (const [variable, degree] of degrees)
929
- if (degree < minDegree) {
930
- result = variable;
931
- minDegree = degree;
2122
+ exactDiv(polynomial: Polynomial, divisor: Polynomial) {
2123
+ if (polynomial.size === 0) return polynomial;
2124
+ const remainder = this.som;
2125
+ const quotient = this.som2;
2126
+ remainder.reset();
2127
+ quotient.reset();
2128
+ remainder.add(polynomial);
2129
+ const maxPos = divisor.getGradedLexMaxPos();
2130
+ const divisorMonomial = divisor.ms[maxPos];
2131
+ const divisorCoeff = divisor.as[maxPos];
2132
+ while (true) {
2133
+ this.limit.checkpoint();
2134
+ const remainderPos = remainder.getGradedLexMaxPos();
2135
+ if (remainderPos === -1) {
2136
+ remainder.reset();
2137
+ return quotient.mk();
932
2138
  }
933
- return result;
2139
+ const monomial = this.divMonomials(remainder.ms[remainderPos], divisorMonomial);
2140
+ if (monomial === null) throw new SmtInvariantError("exact_div: the divisor does not divide");
2141
+ const coeff = this.divNumeral(remainder.as[remainderPos], divisorCoeff);
2142
+ quotient.addTerm(coeff, monomial);
2143
+ remainder.addmul(this.negNumeral(coeff), monomial, divisor);
2144
+ }
934
2145
  }
935
2146
 
936
- // factor: the constant and the irreducible factors, each with its multiplicity. A square-free
937
- // primitive part of degree 2 or more in its variable of minimal degree is out of scope.
938
- factor(polynomial: Polynomial): Factors {
939
- const result: Factors = { constant: 1n, factors: [], degrees: [] };
940
- if (polynomial.size === 0) result.constant = 0n;
941
- else this.factorCore(polynomial, result);
942
- return result;
2147
+ private divides(divisor: Polynomial, polynomial: Polynomial) {
2148
+ if (polynomial.size === 0) return true;
2149
+ const remainder = this.som;
2150
+ this.som.reset();
2151
+ this.som2.reset();
2152
+ remainder.add(polynomial);
2153
+ const maxPos = divisor.getGradedLexMaxPos();
2154
+ const divisorMonomial = divisor.ms[maxPos];
2155
+ const divisorCoeff = divisor.as[maxPos];
2156
+ while (true) {
2157
+ this.limit.checkpoint();
2158
+ const remainderPos = remainder.getGradedLexMaxPos();
2159
+ if (remainderPos === -1) return true;
2160
+ const monomial = this.divMonomials(remainder.ms[remainderPos], divisorMonomial);
2161
+ if (monomial === null) return false;
2162
+ if (!this.dividesNumeral(divisorCoeff, remainder.as[remainderPos])) return false;
2163
+ const coeff = this.divNumeral(remainder.as[remainderPos], divisorCoeff);
2164
+ remainder.addmul(this.negNumeral(coeff), monomial, divisor);
2165
+ }
943
2166
  }
944
2167
 
945
- private factorCore(polynomial: Polynomial, result: Factors) {
946
- if (this.isConst(polynomial)) {
947
- result.constant *= polynomial.as[0];
2168
+ resultant(p: Polynomial, q: Polynomial, x: number, result: PolynomialRef) {
2169
+ const a = new PolynomialRef(this);
2170
+ const b = new PolynomialRef(this);
2171
+ a.set(p);
2172
+ b.set(q);
2173
+ if (this.isZero(a.get()) || this.isZero(b.get())) {
2174
+ result.set(this.zero);
2175
+ b.reset();
2176
+ a.reset();
948
2177
  return;
949
2178
  }
950
- const variable = this.getMinDegreeVar(polynomial);
951
- const [integer, content, primitive] = this.iccp(polynomial, variable);
952
- result.constant *= integer;
953
- this.factorCore(content, result);
954
- let square = this.gcd(primitive, this.derivative(primitive, variable));
955
- if (this.isConst(square)) {
956
- this.factorSqfPp(primitive, variable, 1, result);
2179
+ if (this.isConst(a.get())) {
2180
+ if (this.isConst(b.get())) result.set(this.one);
2181
+ else this.pw(a.get(), this.degree(b.get(), x), result);
2182
+ b.reset();
2183
+ a.reset();
957
2184
  return;
958
2185
  }
959
- let product = this.exactDiv(primitive, square);
960
- for (let multiplicity = 1; !this.isConst(product); multiplicity++) {
961
- const next = this.gcd(product, square);
962
- const factor = this.exactDiv(product, next);
963
- if (!this.isConst(factor)) this.factorSqfPp(factor, variable, multiplicity, result);
964
- else if (factor.as[0] === -1n && multiplicity % 2 === 1) result.constant = -result.constant;
965
- square = this.exactDiv(square, next);
966
- product = next;
2186
+ if (this.isConst(b.get())) {
2187
+ this.pw(b.get(), this.degree(a.get(), x), result);
2188
+ b.reset();
2189
+ a.reset();
2190
+ return;
2191
+ }
2192
+ const cA = new PolynomialRef(this);
2193
+ const cB = new PolynomialRef(this);
2194
+ const ppA = new PolynomialRef(this);
2195
+ const ppB = new PolynomialRef(this);
2196
+ const iA = this.iccp(a.get(), x, cA, ppA);
2197
+ const iB = this.iccp(b.get(), x, cB, ppB);
2198
+ cA.set(this.mulConst(iA, cA.get()));
2199
+ cB.set(this.mulConst(iB, cB.get()));
2200
+ const t = new PolynomialRef(this);
2201
+ this.pw(cA.get(), this.degree(b.get(), x), cA);
2202
+ this.pw(cB.get(), this.degree(a.get(), x), cB);
2203
+ t.set(this.mul(cA.get(), cB.get()));
2204
+ a.copy(ppA);
2205
+ b.copy(ppB);
2206
+ let s = 1;
2207
+ let degA = this.degree(a.get(), x);
2208
+ let degB = this.degree(b.get(), x);
2209
+ if (degA < degB) {
2210
+ a.swap(b);
2211
+ if (degA % 2 === 1 && degB % 2 === 1) s = -1;
2212
+ }
2213
+ const remainder = new PolynomialRef(this);
2214
+ const g = new PolynomialRef(this);
2215
+ const h = new PolynomialRef(this);
2216
+ const newH = new PolynomialRef(this);
2217
+ g.set(this.one);
2218
+ h.set(this.one);
2219
+ while (true) {
2220
+ this.limit.checkpoint();
2221
+ degA = this.degree(a.get(), x);
2222
+ degB = this.degree(b.get(), x);
2223
+ const delta = degA - degB;
2224
+ if (degA % 2 === 1 && degB % 2 === 1) s = -s;
2225
+ this.exactPseudoRemainder(a.get(), b.get(), x, remainder);
2226
+ a.copy(b);
2227
+ b.set(this.exactDiv(remainder.get(), g.get()));
2228
+ for (let index = 0; index < delta; index++) b.set(this.exactDiv(b.get(), h.get()));
2229
+ g.set(this.lc(a.get(), x));
2230
+ newH.set(this.one);
2231
+ this.pw(g.get(), delta, newH);
2232
+ if (delta > 1)
2233
+ for (let index = 0; index < delta - 1; index++)
2234
+ newH.set(this.exactDiv(newH.get(), h.get()));
2235
+ h.copy(newH);
2236
+ if (this.degree(b.get(), x) === 0) {
2237
+ const lastDegA = this.degree(a.get(), x);
2238
+ newH.set(this.lc(b.get(), x));
2239
+ this.pw(newH.get(), lastDegA, newH);
2240
+ if (lastDegA > 1)
2241
+ for (let index = 0; index < lastDegA - 1; index++)
2242
+ newH.set(this.exactDiv(newH.get(), h.get()));
2243
+ h.copy(newH);
2244
+ result.set(this.mul(t.get(), h.get()));
2245
+ if (s < 0) result.set(this.neg(result.get()));
2246
+ newH.reset();
2247
+ h.reset();
2248
+ g.reset();
2249
+ remainder.reset();
2250
+ t.reset();
2251
+ ppB.reset();
2252
+ ppA.reset();
2253
+ cB.reset();
2254
+ cA.reset();
2255
+ b.reset();
2256
+ a.reset();
2257
+ return;
2258
+ }
967
2259
  }
968
2260
  }
969
2261
 
970
- // factor_sqf_pp: the factors of a primitive square-free p of positive degree in x.
971
- private factorSqfPp(polynomial: Polynomial, variable: number, k: number, result: Factors) {
972
- const degree = this.degree(polynomial, variable);
973
- if (degree === 1) this.pushFactor(result, polynomial, k);
974
- else if (this.isUnivariate(polynomial)) this.factorSqfPpUniv(polynomial, k, result);
975
- else if (degree === 2) this.factorQuadratic(polynomial, variable, k, result);
976
- else if (!this.factorMultivariate(polynomial, variable, k, result))
977
- this.pushFactor(result, polynomial, k);
978
- }
979
-
980
- private pushFactor(result: Factors, polynomial: Polynomial, k: number) {
981
- result.factors.push(polynomial);
982
- result.degrees.push(k);
2262
+ private seLazard(d: number, lcSd: Polynomial, sd1: Polynomial, x: number, se: PolynomialRef) {
2263
+ let n = d - this.degree(sd1, x) - 1;
2264
+ if (n === 0) {
2265
+ se.set(sd1);
2266
+ return;
2267
+ }
2268
+ const xLc = new PolynomialRef(this);
2269
+ xLc.set(this.lc(sd1, x));
2270
+ const y = lcSd;
2271
+ let a = 1 << (31 - Math.clz32(n));
2272
+ const c = new PolynomialRef(this);
2273
+ c.copy(xLc);
2274
+ n -= a;
2275
+ while (a !== 1) {
2276
+ a /= 2;
2277
+ c.set(this.mul(c.get(), c.get()));
2278
+ c.set(this.exactDiv(c.get(), y));
2279
+ if (n >= a) {
2280
+ c.set(this.mul(c.get(), xLc.get()));
2281
+ c.set(this.exactDiv(c.get(), y));
2282
+ n -= a;
2283
+ }
2284
+ }
2285
+ se.set(this.mul(c.get(), sd1));
2286
+ se.set(this.exactDiv(se.get(), y));
2287
+ c.reset();
2288
+ xLc.reset();
983
2289
  }
984
2290
 
985
- // to_numeral_vector: the coefficients of a univariate p by degree. Z3 normalizes p first but
986
- // reads the coefficients of p itself.
987
- // to_numeral_vector: a univariate p as its coefficients, low to high.
988
- toCoeffs(polynomial: Polynomial) {
989
- const coeffs = Array.from({ length: this.totalDegree(polynomial) + 1 }, () => 0n);
990
- for (let index = 0; index < polynomial.size; index++)
991
- coeffs[polynomial.ms[index].totalDegree] = polynomial.as[index];
992
- return this.um.set(coeffs);
2291
+ private optimizedSe1(
2292
+ d: number,
2293
+ e: number,
2294
+ a: Polynomial,
2295
+ sd1: Polynomial,
2296
+ se: Polynomial,
2297
+ s: Polynomial,
2298
+ x: number,
2299
+ se1: PolynomialRef,
2300
+ ) {
2301
+ const cD1 = new PolynomialRef(this);
2302
+ const sE = new PolynomialRef(this);
2303
+ const xJ = new PolynomialRef(this);
2304
+ const tmp = new PolynomialRef(this);
2305
+ cD1.set(this.lc(sd1, x));
2306
+ sE.set(this.lc(se, x));
2307
+ const h = new PolynomialRefVector(this);
2308
+ xJ.set(this.one);
2309
+ for (let j = 0; j <= e - 1; j++) {
2310
+ xJ.set(this.mkVar(x, j));
2311
+ h.push(this.mul(sE.get(), xJ.get()));
2312
+ }
2313
+ xJ.set(this.mkVar(x, e));
2314
+ xJ.set(this.mul(sE.get(), xJ.get()));
2315
+ h.push(this.sub(xJ.get(), se));
2316
+ const xPol = new PolynomialRef(this);
2317
+ const xH = new PolynomialRef(this);
2318
+ const xHe = new PolynomialRef(this);
2319
+ xPol.set(this.mkVar(x, 1));
2320
+ for (let j = e + 1; j <= d - 1; j++) {
2321
+ xH.set(this.mul(xPol.get(), h.get(j - 1)));
2322
+ xHe.set(this.coeff(xH.get(), x, e));
2323
+ tmp.set(this.mul(xHe.get(), sd1));
2324
+ tmp.set(this.exactDiv(tmp.get(), cD1.get()));
2325
+ h.push(this.sub(xH.get(), tmp.get()));
2326
+ }
2327
+ const dPolynomial = new PolynomialRef(this);
2328
+ dPolynomial.set(this.zero);
2329
+ for (let j = 0; j < d; j++) {
2330
+ tmp.set(this.coeff(a, x, j));
2331
+ tmp.set(this.mul(tmp.get(), h.get(j)));
2332
+ dPolynomial.set(this.add(dPolynomial.get(), tmp.get()));
2333
+ }
2334
+ const lcA = new PolynomialRef(this);
2335
+ lcA.set(this.lc(a, x));
2336
+ dPolynomial.set(this.exactDiv(dPolynomial.get(), lcA.get()));
2337
+ xH.set(this.mul(xPol.get(), h.get(d - 1)));
2338
+ xHe.set(this.coeff(xH.get(), x, e));
2339
+ xHe.set(this.mul(xHe.get(), sd1));
2340
+ se1.set(this.add(xH.get(), dPolynomial.get()));
2341
+ se1.set(this.mul(cD1.get(), se1.get()));
2342
+ se1.set(this.sub(se1.get(), xHe.get()));
2343
+ se1.set(this.exactDiv(se1.get(), s));
2344
+ if ((d - e + 1) % 2 === 1) se1.set(this.neg(se1.get()));
2345
+ lcA.reset();
2346
+ dPolynomial.reset();
2347
+ xHe.reset();
2348
+ xH.reset();
2349
+ xPol.reset();
2350
+ h.reset();
2351
+ tmp.reset();
2352
+ xJ.reset();
2353
+ sE.reset();
2354
+ cD1.reset();
2355
+ }
2356
+
2357
+ private pscChainOptimizedCore(
2358
+ p: Polynomial,
2359
+ q: Polynomial,
2360
+ x: number,
2361
+ chain: PolynomialRefVector,
2362
+ ) {
2363
+ const degP = this.degree(p, x);
2364
+ const degQ = this.degree(q, x);
2365
+ const a = new PolynomialRef(this);
2366
+ const b = new PolynomialRef(this);
2367
+ const c = new PolynomialRef(this);
2368
+ const minusQ = new PolynomialRef(this);
2369
+ const lcQ = new PolynomialRef(this);
2370
+ const ps = new PolynomialRef(this);
2371
+ lcQ.set(this.lc(q, x));
2372
+ const s = new PolynomialRef(this);
2373
+ const release = () => {
2374
+ s.reset();
2375
+ ps.reset();
2376
+ lcQ.reset();
2377
+ minusQ.reset();
2378
+ c.reset();
2379
+ b.reset();
2380
+ a.reset();
2381
+ };
2382
+ this.pw(lcQ.get(), degP - degQ, s);
2383
+ minusQ.set(this.neg(q));
2384
+ a.set(q);
2385
+ this.exactPseudoRemainder(p, minusQ.get(), x, b);
2386
+ while (true) {
2387
+ const d = this.degree(a.get(), x);
2388
+ const e = this.degree(b.get(), x);
2389
+ if (this.isZero(b.get())) {
2390
+ release();
2391
+ return;
2392
+ }
2393
+ ps.set(this.coeff(b.get(), x, d - 1));
2394
+ if (!this.isZero(ps.get())) chain.push(ps.get());
2395
+ const delta = d - e;
2396
+ if (delta > 1) {
2397
+ this.seLazard(d, s.get(), b.get(), x, c);
2398
+ ps.set(this.coeff(c.get(), x, e));
2399
+ if (!this.isZero(ps.get())) chain.push(ps.get());
2400
+ } else c.copy(b);
2401
+ if (e === 0) {
2402
+ release();
2403
+ return;
2404
+ }
2405
+ this.optimizedSe1(d, e, a.get(), b.get(), c.get(), s.get(), x, b);
2406
+ a.copy(c);
2407
+ s.set(this.lc(a.get(), x));
2408
+ }
993
2409
  }
994
2410
 
995
- // to_polynomial, mk_univariate: the monomials from the highest degree down.
996
- fromCoeffs(coeffs: readonly bigint[], variable: number) {
997
- for (let power = coeffs.length - 1; power >= 0; power--)
998
- this.cheap.add(coeffs[power], this.mkPower(variable, power));
999
- return this.cheap.mk();
2411
+ pscChain(p: Polynomial, q: Polynomial, x: number, chain: PolynomialRefVector) {
2412
+ chain.reset();
2413
+ if (this.degree(p, x) >= this.degree(q, x)) this.pscChainOptimizedCore(p, q, x, chain);
2414
+ else this.pscChainOptimizedCore(q, p, x, chain);
2415
+ if (chain.size === 0) chain.push(this.zero);
2416
+ chain.items.reverse();
1000
2417
  }
1001
2418
 
1002
- // factor_sqf_pp_univ
1003
- private factorSqfPpUniv(polynomial: Polynomial, k: number, result: Factors) {
1004
- const variable = this.maxVar(polynomial);
1005
- const fs: UpolynomialFactors = { constant: 1n, factors: [], degrees: [] };
1006
- factorSquareFree(this.um, this.toCoeffs(polynomial), fs, 1, DEFAULT_FACTOR_PARAMS);
1007
- if (fs.factors.length === 1 && fs.degrees[0] === 1) {
1008
- this.pushFactor(result, polynomial, k);
1009
- return;
1010
- }
1011
- for (let index = 0; index < fs.factors.length; index++)
1012
- this.pushFactor(result, this.fromCoeffs(fs.factors[index], variable), k * fs.degrees[index]);
1013
- if (fs.constant === -1n && k % 2 === 1) result.constant = -result.constant;
1014
- }
1015
-
1016
- // factor_2_sqf_pp: a*x^2 + b*x + c splits into the primitive parts of 2*a*x + b -/+ sqrt(disc)
1017
- // when the discriminant b^2 - 4*a*c is a square.
1018
- private factorQuadratic(polynomial: Polynomial, variable: number, k: number, result: Factors) {
1019
- let a = this.coeff(polynomial, variable, 2);
1020
- let b = this.coeff(polynomial, variable, 1);
1021
- let c = this.coeff(polynomial, variable, 0);
1022
- const isFlipped = a.as[a.getGradedLexMaxPos()] < 0n;
1023
- if (isFlipped) {
1024
- a = this.neg(a);
1025
- b = this.neg(b);
1026
- c = this.neg(c);
1027
- }
1028
- const root = this.sqrt(this.addmul(1n, this.mul(b, b), -4n, this.mul(a, c)));
1029
- if (root === null) {
1030
- this.pushFactor(result, polynomial, k);
1031
- return;
2419
+ normalize(polynomial: Polynomial) {
2420
+ if (polynomial.size === 0) return polynomial;
2421
+ const modulus = this.modulus;
2422
+ if (modulus !== null) {
2423
+ let index = 0;
2424
+ for (; index < polynomial.size; index++)
2425
+ if (normalizeZp(polynomial.as[index], modulus) !== polynomial.as[index]) break;
2426
+ if (index < polynomial.size) {
2427
+ this.cheap.reset();
2428
+ for (let other = 0; other < polynomial.size; other++)
2429
+ this.cheap.addReset(normalizeZp(polynomial.as[other], modulus), polynomial.ms[other]);
2430
+ this.cheap.normalize();
2431
+ return this.cheap.mk();
2432
+ }
1032
2433
  }
1033
- if (isFlipped && k % 2 === 1) result.constant = -result.constant;
1034
- const linear = this.add(this.mulTerm(2n, this.mkPower(variable, 1), a), b);
1035
- this.pushFactor(result, this.pp(this.sub(linear, root), variable), k);
1036
- this.pushFactor(result, this.pp(this.add(linear, root), variable), k);
2434
+ const g = this.gcdNumerals(polynomial.as);
2435
+ if (g === 1n) return polynomial;
2436
+ this.cheap.reset();
2437
+ for (let index = 0; index < polynomial.size; index++)
2438
+ this.cheap.addReset(this.divNumeral(polynomial.as[index], g), polynomial.ms[index]);
2439
+ return this.cheap.mk();
1037
2440
  }
1038
2441
 
1039
- // is_perfect_square for the monomial at a position: the square root of its coefficient when the
1040
- // whole term is a square.
1041
2442
  private getTermSquareRoot(polynomial: Polynomial, position: number) {
1042
- const monomial = polynomial.ms[position];
1043
- if (monomial.degrees.some((degree) => degree % 2 === 1)) return null;
2443
+ if (!polynomial.ms[position].isSquare()) return null;
1044
2444
  return getExactSquareRoot(polynomial.as[position]);
1045
2445
  }
1046
2446
 
1047
- // sqrt: the square root of p with a positive graded-lex leading coefficient, or null.
1048
- sqrt(polynomial: Polynomial) {
1049
- if (polynomial.size === 0) return polynomial;
1050
- if (this.getTermSquareRoot(polynomial, this.getGradedLexMinPos(polynomial)) === null)
1051
- return null;
2447
+ sqrt(polynomial: Polynomial, r: PolynomialRef) {
2448
+ if (polynomial.size === 0) {
2449
+ r.set(polynomial);
2450
+ return true;
2451
+ }
2452
+ if (this.getTermSquareRoot(polynomial, polynomial.getGradedLexMinPos()) === null) return false;
1052
2453
  const maxPos = polynomial.getGradedLexMaxPos();
1053
2454
  const a = this.getTermSquareRoot(polynomial, maxPos);
1054
- if (a === null) return null;
1055
- const maxMonomial = polynomial.ms[maxPos];
1056
- const m1 = this.mkMonomial(
1057
- maxMonomial.vars,
1058
- maxMonomial.degrees.map((degree) => degree / 2),
1059
- );
2455
+ if (a === null) return false;
2456
+ const m1 = this.sqrtMonomial(polynomial.ms[maxPos]);
1060
2457
  const root = this.som;
1061
2458
  const rest = this.som2;
1062
2459
  root.reset();
1063
2460
  rest.reset();
1064
- const twoA = 2n * a;
2461
+ const twoA = a * 2n;
1065
2462
  root.addTerm(a, m1);
1066
2463
  for (let index = 0; index < polynomial.size; index++)
1067
2464
  if (index !== maxPos) rest.addTerm(polynomial.as[index], polynomial.ms[index]);
1068
2465
  while (true) {
2466
+ this.limit.checkpoint();
1069
2467
  const restMax = rest.getGradedLexMaxPos();
1070
2468
  if (restMax === -1) {
2469
+ r.set(root.mk());
1071
2470
  rest.reset();
1072
- return root.mk();
2471
+ return true;
1073
2472
  }
1074
2473
  const monomial = this.divMonomials(rest.ms[restMax], m1);
1075
- if (monomial === null || rest.as[restMax] % twoA !== 0n) {
1076
- root.reset();
2474
+ if (monomial === null || !this.dividesNumeral(twoA, rest.as[restMax])) {
1077
2475
  rest.reset();
1078
- return null;
2476
+ root.reset();
2477
+ return false;
1079
2478
  }
1080
- const coeff = floorDiv(rest.as[restMax], twoA);
2479
+ const coeff = this.divNumeral(rest.as[restMax], twoA);
1081
2480
  const rootSize = root.as.length;
1082
2481
  for (let index = 0; index < rootSize; index++) {
1083
2482
  if (root.as[index] === 0n) continue;
@@ -1088,16 +2487,6 @@ export class PolynomialManager {
1088
2487
  }
1089
2488
  }
1090
2489
 
1091
- // graded_lex_min_pos
1092
- private getGradedLexMinPos(polynomial: Polynomial) {
1093
- let minPos = 0;
1094
- for (let index = 1; index < polynomial.size; index++)
1095
- if (gradedLexCompare(polynomial.ms[index], polynomial.ms[minPos]) < 0) minPos = index;
1096
- return minPos;
1097
- }
1098
-
1099
- // vars: the variables of p in order of occurrence.
1100
- // vars: the variables of p in the order they first occur.
1101
2490
  getVars(polynomial: Polynomial) {
1102
2491
  const vars: number[] = [];
1103
2492
  for (const monomial of polynomial.ms)
@@ -1105,12 +2494,22 @@ export class PolynomialManager {
1105
2494
  return vars;
1106
2495
  }
1107
2496
 
1108
- // substitute: p with each xs[i] replaced by the integer values[i].
2497
+ private getMaxDegrees(polynomial: Polynomial) {
2498
+ const degrees = new Map<number, number>();
2499
+ for (const monomial of polynomial.ms)
2500
+ for (let index = 0; index < monomial.size; index++) {
2501
+ const variable = monomial.vars[index];
2502
+ if (monomial.degrees[index] > (degrees.get(variable) ?? 0))
2503
+ degrees.set(variable, monomial.degrees[index]);
2504
+ }
2505
+ return degrees;
2506
+ }
2507
+
1109
2508
  substitute(polynomial: Polynomial, vars: readonly number[], values: readonly bigint[]) {
1110
2509
  this.som.reset();
1111
2510
  for (let index = 0; index < polynomial.size; index++) {
1112
2511
  const monomial = polynomial.ms[index];
1113
- let coeff = polynomial.as[index];
2512
+ let coeff = this.normalizeNumeral(polynomial.as[index]);
1114
2513
  const keptVars: number[] = [];
1115
2514
  const keptDegrees: number[] = [];
1116
2515
  for (let power = 0; power < monomial.size; power++) {
@@ -1118,14 +2517,17 @@ export class PolynomialManager {
1118
2517
  if (position === -1) {
1119
2518
  keptVars.push(monomial.vars[power]);
1120
2519
  keptDegrees.push(monomial.degrees[power]);
1121
- } else coeff *= values[position] ** BigInt(monomial.degrees[power]);
2520
+ } else
2521
+ coeff = this.mulNumeral(
2522
+ this.powerNumeral(values[position], monomial.degrees[power]),
2523
+ coeff,
2524
+ );
1122
2525
  }
1123
2526
  this.som.addTerm(coeff, this.mkMonomial(keptVars, keptDegrees));
1124
2527
  }
1125
2528
  return this.som.mk();
1126
2529
  }
1127
2530
 
1128
- // translate: p(x + v), by Horner on the coefficients of p in x.
1129
2531
  translate(polynomial: Polynomial, variable: number, value: bigint) {
1130
2532
  const degree = this.degree(polynomial, variable);
1131
2533
  if (degree === 0 || value === 0n) return polynomial;
@@ -1137,27 +2539,19 @@ export class PolynomialManager {
1137
2539
  this.divX(monomial, variable),
1138
2540
  );
1139
2541
  }
1140
- for (let step = 1; step <= degree; step++)
2542
+ for (let step = 1; step <= degree; step++) {
2543
+ this.limit.checkpoint();
1141
2544
  for (let power = degree - step; power <= degree - 1; power++)
1142
2545
  coeffs[power].addmulBuffer(value, this.unit, coeffs[power + 1]);
2546
+ }
1143
2547
  this.som.reset();
1144
2548
  for (let power = 0; power <= degree; power++)
1145
2549
  this.som.addmulBuffer(1n, this.mkPower(variable, power), coeffs[power]);
1146
2550
  return this.som.mk();
1147
2551
  }
1148
2552
 
1149
- // substitute(p, x2v): p with the rational values of its assigned variables, each term scaled by
1150
- // the denominators to the maximal degree of their variable, and the content divided out. p itself
1151
- // when it has no assigned variable.
1152
2553
  substituteRational(polynomial: Polynomial, values: readonly (Rational | undefined)[]) {
1153
- // Map keeps the order in which the variables first occur, as var_max_degree does.
1154
- const maxDegrees = new Map<number, number>();
1155
- for (const monomial of polynomial.ms)
1156
- for (let index = 0; index < monomial.size; index++) {
1157
- const variable = monomial.vars[index];
1158
- if (monomial.degrees[index] > (maxDegrees.get(variable) ?? 0))
1159
- maxDegrees.set(variable, monomial.degrees[index]);
1160
- }
2554
+ const maxDegrees = this.getMaxDegrees(polynomial);
1161
2555
  if (![...maxDegrees.keys()].some((variable) => values[variable] !== undefined))
1162
2556
  return polynomial;
1163
2557
  this.som.reset();
@@ -1184,400 +2578,538 @@ export class PolynomialManager {
1184
2578
  if (value !== undefined && monomial.degreeOf(variable) === 0)
1185
2579
  coeff *= value.den ** BigInt(maxDegree);
1186
2580
  }
1187
- this.som.addTerm(coeff, this.mkMonomial(keptVars, keptDegrees));
2581
+ if (coeff !== 0n) this.som.addTerm(coeff, this.mkMonomial(keptVars, keptDegrees));
1188
2582
  }
1189
2583
  return this.som.mk(true);
1190
2584
  }
1191
2585
 
1192
- // muladd: p*q + a.
1193
- private muladd(first: Polynomial, second: Polynomial, constant: bigint) {
1194
- if (first.size === 0 || second.size === 0) return this.mkConst(constant);
1195
- this.som.reset();
1196
- for (let index = 0; index < first.size; index++)
1197
- this.som.addmul(first.as[index], first.ms[index], second);
1198
- this.som.addTerm(constant, this.unit);
1199
- return this.som.mk();
2586
+ private mkGlexMonic(polynomial: Polynomial) {
2587
+ if (polynomial.size === 0) return polynomial;
2588
+ const position = polynomial.getGradedLexMaxPos();
2589
+ if (polynomial.as[position] === 1n) return polynomial;
2590
+ const inverse = this.invNumeral(polynomial.as[position]);
2591
+ this.cheap.reset();
2592
+ for (let index = 0; index < polynomial.size; index++)
2593
+ this.cheap.add(this.mulNumeral(polynomial.as[index], inverse), polynomial.ms[index]);
2594
+ return this.cheap.mk();
1200
2595
  }
1201
2596
 
1202
- // compose: p(q) for a univariate p, by Horner.
1203
- private compose(polynomial: Polynomial, inner: Polynomial) {
1204
- if (this.isConst(polynomial)) return polynomial;
1205
- const variable = this.maxVar(polynomial);
1206
- const degree = this.degree(polynomial, variable);
1207
- const coeffs = Array.from({ length: degree + 1 }, () => 0n);
1208
- for (let index = 0; index < polynomial.size; index++)
1209
- coeffs[polynomial.ms[index].degreeOf(variable)] = polynomial.as[index];
1210
- let result = this.mkConst(coeffs[degree]);
1211
- for (let power = degree - 1; power >= 0; power--)
1212
- result = this.muladd(inner, result, coeffs[power]);
2597
+ private getMinDegreeVar(polynomial: Polynomial) {
2598
+ let result = NULL_VAR;
2599
+ let minDegree = Infinity;
2600
+ for (const [variable, degree] of this.getMaxDegrees(polynomial))
2601
+ if (degree < minDegree) {
2602
+ result = variable;
2603
+ minDegree = degree;
2604
+ }
1213
2605
  return result;
1214
2606
  }
1215
2607
 
1216
- // compose_x_minus_y: p(x - y) for a univariate p in x.
1217
- composeXMinusY(polynomial: Polynomial, variable: number) {
1218
- const x = this.maxVar(polynomial);
1219
- if (variable === x) return this.coeff(polynomial, x, 0);
1220
- return this.compose(polynomial, this.mkLinear([1n, -1n], [x, variable], 0n));
2608
+ toCoeffs(polynomial: Polynomial) {
2609
+ // Z3's to_numeral_vector builds normalize(p) and drops it, which takes and frees an id.
2610
+ const normalized = this.normalize(polynomial);
2611
+ if (normalized !== polynomial) {
2612
+ this.incRef(normalized);
2613
+ this.decRef(normalized);
2614
+ }
2615
+ const coeffs = Array.from({ length: this.totalDegree(polynomial) + 1 }, () => 0n);
2616
+ for (let index = 0; index < polynomial.size; index++)
2617
+ coeffs[polynomial.ms[index].totalDegree] = polynomial.as[index];
2618
+ return this.um.set(coeffs);
1221
2619
  }
1222
2620
 
1223
- // compose_x_div_y: y^n * p(x/y) for a univariate p in x of degree n.
1224
- composeXDivY(polynomial: Polynomial, variable: number) {
1225
- if (this.isConst(polynomial)) return polynomial;
1226
- const x = this.maxVar(polynomial);
1227
- const degree = this.degree(polynomial, x);
1228
- for (let index = 0; index < polynomial.size; index++) {
1229
- const power = polynomial.ms[index].degreeOf(x);
1230
- const powers: [number, number][] =
1231
- x < variable
1232
- ? [
1233
- [x, power],
1234
- [variable, degree - power],
1235
- ]
1236
- : [
1237
- [variable, degree - power],
1238
- [x, power],
1239
- ];
1240
- const kept = powers.filter((entry) => entry[1] > 0);
1241
- this.cheap.add(
1242
- polynomial.as[index],
1243
- this.mkMonomial(
1244
- kept.map((entry) => entry[0]),
1245
- kept.map((entry) => entry[1]),
1246
- ),
1247
- );
2621
+ factor(polynomial: Polynomial, r: Factors) {
2622
+ if (polynomial.size === 0) {
2623
+ r.constant = 0n;
2624
+ return;
1248
2625
  }
1249
- return this.cheap.mk();
2626
+ this.factorCore(polynomial, r);
1250
2627
  }
1251
2628
 
1252
- // resultant: Res(p, q) in x, by the subresultant PRS on the primitive parts, times the contents.
1253
- resultant(first: Polynomial, second: Polynomial, variable: number) {
1254
- if (first.size === 0 || second.size === 0) return this.zero;
1255
- if (this.isConst(first))
1256
- return this.isConst(second) ? this.one : this.pw(first, this.degree(second, variable));
1257
- if (this.isConst(second)) return this.pw(second, this.degree(first, variable));
1258
- const [integerA, contentA, ppA] = this.iccp(first, variable);
1259
- const [integerB, contentB, ppB] = this.iccp(second, variable);
1260
- const scale = this.mul(
1261
- this.pw(this.mulConst(integerA, contentA), this.degree(second, variable)),
1262
- this.pw(this.mulConst(integerB, contentB), this.degree(first, variable)),
1263
- );
1264
- let a = ppA;
1265
- let b = ppB;
1266
- let sign = 1;
1267
- if (this.degree(a, variable) < this.degree(b, variable)) {
1268
- if (this.degree(a, variable) % 2 === 1 && this.degree(b, variable) % 2 === 1) sign = -1;
1269
- [a, b] = [b, a];
1270
- }
1271
- let g = this.one;
1272
- let h = this.one;
1273
- while (true) {
1274
- const degreeA = this.degree(a, variable);
1275
- const degreeB = this.degree(b, variable);
1276
- const delta = degreeA - degreeB;
1277
- if (degreeA % 2 === 1 && degreeB % 2 === 1) sign = -sign;
1278
- const remainder = this.exactPseudoRemainder(a, b, variable);
1279
- a = b;
1280
- b = this.exactDiv(remainder, g);
1281
- for (let index = 0; index < delta; index++) b = this.exactDiv(b, h);
1282
- g = this.lc(a, variable);
1283
- let nextH = this.pw(g, delta);
1284
- for (let index = 1; index < delta; index++) nextH = this.exactDiv(nextH, h);
1285
- h = nextH;
1286
- if (this.degree(b, variable) === 0) {
1287
- const degree = this.degree(a, variable);
1288
- let lastH = this.pw(this.lc(b, variable), degree);
1289
- for (let index = 1; index < degree; index++) lastH = this.exactDiv(lastH, h);
1290
- const result = this.mul(scale, lastH);
1291
- return sign < 0 ? this.neg(result) : result;
2629
+ private factorCore(polynomial: Polynomial, r: Factors) {
2630
+ if (this.isConst(polynomial)) {
2631
+ r.constant *= polynomial.as[0];
2632
+ return;
2633
+ }
2634
+ const x = this.getMinDegreeVar(polynomial);
2635
+ const c = new PolynomialRef(this);
2636
+ const pp = new PolynomialRef(this);
2637
+ const integer = this.iccp(polynomial, x, c, pp);
2638
+ r.constant *= integer;
2639
+ this.factorCore(c.get(), r);
2640
+ const cPart = new PolynomialRef(this);
2641
+ cPart.copy(pp);
2642
+ const cPrime = new PolynomialRef(this);
2643
+ cPrime.set(this.derivative(cPart.get(), x));
2644
+ const b = new PolynomialRef(this);
2645
+ const a = new PolynomialRef(this);
2646
+ const d = new PolynomialRef(this);
2647
+ this.gcd(cPart.get(), cPrime.get(), b);
2648
+ if (this.isConst(b.get())) this.factorSqfPp(cPart.get(), r, x, 1);
2649
+ else {
2650
+ a.set(this.exactDiv(cPart.get(), b.get()));
2651
+ for (let j = 1; !this.isConst(a.get()); j++) {
2652
+ this.limit.checkpoint();
2653
+ this.gcd(a.get(), b.get(), d);
2654
+ cPart.set(this.exactDiv(a.get(), d.get()));
2655
+ if (!this.isConst(cPart.get())) this.factorSqfPp(cPart.get(), r, x, j);
2656
+ else if (cPart.get().as[0] === -1n && j % 2 === 1) r.constant = -r.constant;
2657
+ b.set(this.exactDiv(b.get(), d.get()));
2658
+ a.copy(d);
1292
2659
  }
1293
2660
  }
2661
+ d.reset();
2662
+ a.reset();
2663
+ b.reset();
2664
+ cPrime.reset();
2665
+ cPart.reset();
2666
+ pp.reset();
2667
+ c.reset();
1294
2668
  }
1295
2669
 
1296
- private isSquareFreeIn(polynomial: Polynomial, variable: number) {
1297
- if (this.isConst(polynomial)) return polynomial.size > 0;
1298
- return this.isConst(this.gcd(polynomial, this.derivative(polynomial, variable)));
2670
+ private factorSqfPp(polynomial: Polynomial, r: Factors, x: number, k: number) {
2671
+ const degree = this.degree(polynomial, x);
2672
+ if (degree === 1) r.push(polynomial, k);
2673
+ else if (this.isUnivariate(polynomial)) this.factorSqfPpUniv(polynomial, r, k);
2674
+ else if (degree === 2) this.factor2SqfPp(polynomial, r, x, k);
2675
+ else this.factorNSqfPp(polynomial, r, x, k);
2676
+ }
2677
+
2678
+ private factor2SqfPp(polynomial: Polynomial, r: Factors, x: number, k: number) {
2679
+ const a = new PolynomialRef(this);
2680
+ const b = new PolynomialRef(this);
2681
+ const c = new PolynomialRef(this);
2682
+ a.set(this.coeff(polynomial, x, 2));
2683
+ b.set(this.coeff(polynomial, x, 1));
2684
+ c.set(this.coeff(polynomial, x, 0));
2685
+ let isFlipped = false;
2686
+ if (a.get().as[a.get().getGradedLexMaxPos()] < 0n) {
2687
+ a.set(this.neg(a.get()));
2688
+ b.set(this.neg(b.get()));
2689
+ c.set(this.neg(c.get()));
2690
+ isFlipped = true;
2691
+ }
2692
+ const b2 = new PolynomialRef(this);
2693
+ b2.set(this.mul(b.get(), b.get()));
2694
+ const ac = new PolynomialRef(this);
2695
+ ac.set(this.mul(a.get(), c.get()));
2696
+ const disc = new PolynomialRef(this);
2697
+ disc.set(this.addmul(b2.get(), -4n, ac.get()));
2698
+ const discSqrt = new PolynomialRef(this);
2699
+ const f1 = new PolynomialRef(this);
2700
+ const f2 = new PolynomialRef(this);
2701
+ const twoAx = new PolynomialRef(this);
2702
+ if (!this.sqrt(disc.get(), discSqrt)) r.push(polynomial, k);
2703
+ else {
2704
+ if (isFlipped && k % 2 === 1) r.constant = -r.constant;
2705
+ twoAx.set(this.mulTerm(2n, this.mkPower(x, 1), a.get()));
2706
+ f1.set(this.add(twoAx.get(), b.get()));
2707
+ f2.copy(f1);
2708
+ f1.set(this.sub(f1.get(), discSqrt.get()));
2709
+ f2.set(this.add(f2.get(), discSqrt.get()));
2710
+ f1.move(this.pp(f1.get(), x));
2711
+ f2.move(this.pp(f2.get(), x));
2712
+ r.push(f1.get(), k);
2713
+ r.push(f2.get(), k);
2714
+ }
2715
+ twoAx.reset();
2716
+ f2.reset();
2717
+ f1.reset();
2718
+ discSqrt.reset();
2719
+ disc.reset();
2720
+ ac.reset();
2721
+ b2.reset();
2722
+ c.reset();
2723
+ b.reset();
2724
+ a.reset();
2725
+ }
2726
+
2727
+ private factorSqfPpUniv(polynomial: Polynomial, r: Factors, k: number) {
2728
+ const x = this.maxVar(polynomial);
2729
+ const pRef = new PolynomialRef(this);
2730
+ pRef.set(polynomial);
2731
+ const fs = mkFactors();
2732
+ factorSquareFree(this.um, this.toCoeffs(polynomial), fs, 1, DEFAULT_FACTOR_PARAMS);
2733
+ if (fs.factors.length === 1 && fs.degrees[0] === 1) r.push(polynomial, k);
2734
+ else {
2735
+ const f = new PolynomialRef(this);
2736
+ for (let index = 0; index < fs.factors.length; index++) {
2737
+ f.set(this.toPolynomial(fs.factors[index], x));
2738
+ r.push(f.get(), k * fs.degrees[index]);
2739
+ }
2740
+ if (fs.constant === -1n && k % 2 === 1) r.constant = -r.constant;
2741
+ f.reset();
2742
+ }
2743
+ pRef.reset();
2744
+ }
2745
+
2746
+ private factorNSqfPp(polynomial: Polynomial, r: Factors, x: number, k: number) {
2747
+ if (this.isUnivariate(polynomial)) {
2748
+ this.factorSqfPpUniv(polynomial, r, k);
2749
+ return;
2750
+ }
2751
+ if (this.tryMultivarFactor(polynomial, r, x, k)) return;
2752
+ r.push(polynomial, k);
1299
2753
  }
1300
2754
 
1301
- private isPrimitive(polynomial: Polynomial, variable: number) {
1302
- return this.eq(polynomial, this.pp(polynomial, variable));
2755
+ private pushSmallFactor(part: PolynomialRef, r: Factors, x: number, k: number) {
2756
+ const d = this.degree(part.get(), x);
2757
+ if (d === 1) r.push(part.get(), k);
2758
+ else if (d === 2 && this.isPrimitive(part.get(), x) && this.isSquareFreeIn(part.get(), x))
2759
+ this.factor2SqfPp(part.get(), r, x, k);
2760
+ else r.push(part.get(), k);
1303
2761
  }
1304
2762
 
1305
- // factor_n_sqf_pp, try_multivar_factor: reduces p to two variables by evaluating the others,
1306
- // factors it at a point of the lifting variable, lifts a split of the univariate factors with
1307
- // Hensel's lemma and keeps it when the lifted factors multiply back to p. Returns false when no
1308
- // split lifts, leaving p unfactored.
1309
- private factorMultivariate(polynomial: Polynomial, x: number, k: number, result: Factors) {
2763
+ private tryMultivarFactor(polynomial: Polynomial, r: Factors, x: number, k: number) {
1310
2764
  const allVars = this.getVars(polynomial);
1311
- const mainVars = [
1312
- x,
1313
- ...allVars
1314
- .filter((variable) => variable !== x)
1315
- .map((variable) => [this.degree(polynomial, variable), variable])
1316
- .sort((first, second) => second[0] - first[0] || second[1] - first[1])
1317
- .filter((entry) => entry[0] > 1)
1318
- .map((entry) => entry[1]),
1319
- ];
2765
+ const mainVars = [x];
2766
+ const varsByDegree: [number, number][] = [];
2767
+ for (const variable of allVars)
2768
+ if (variable !== x) varsByDegree.push([this.degree(polynomial, variable), variable]);
2769
+ varsByDegree.sort((first, second) => second[0] - first[0] || second[1] - first[1]);
2770
+ for (const [degree, variable] of varsByDegree) if (degree > 1) mainVars.push(variable);
1320
2771
  for (const mainVar of mainVars) {
1321
2772
  const degMain = this.degree(polynomial, mainVar);
1322
2773
  if (degMain <= 1) continue;
1323
2774
  for (const liftVar of allVars) {
1324
2775
  if (liftVar === mainVar) continue;
1325
- const evalVars = allVars.filter((variable) => variable !== mainVar && variable !== liftVar);
1326
- const maxCombos = evalVars.length === 0 ? 1 : 5;
2776
+ this.limit.checkpoint();
2777
+ const evalVars: number[] = [];
2778
+ for (const variable of allVars)
2779
+ if (variable !== mainVar && variable !== liftVar) evalVars.push(variable);
2780
+ const nEval = evalVars.length;
2781
+ const maxCombos = nEval === 0 ? 1 : Math.min(FACTOR_EVAL_VALUES.length, 5);
1327
2782
  for (let combo = 0; combo < maxCombos; combo++) {
1328
- const bivariate =
1329
- evalVars.length === 0
1330
- ? polynomial
1331
- : this.substitute(
1332
- polynomial,
1333
- evalVars,
1334
- evalVars.map(
1335
- (_variable, index) =>
1336
- FACTOR_EVAL_VALUES[
1337
- Math.floor(combo / FACTOR_EVAL_VALUES.length ** index) %
1338
- FACTOR_EVAL_VALUES.length
1339
- ],
1340
- ),
1341
- );
1342
- if (this.degree(bivariate, mainVar) !== degMain) continue;
1343
- const degLift = this.degree(bivariate, liftVar);
1344
- if (degLift === 0) continue;
1345
- for (const point of FACTOR_EVAL_VALUES) {
1346
- const univariate = this.substitute(bivariate, [liftVar], [point]);
1347
- if (!this.isUnivariate(univariate)) continue;
1348
- if (this.degree(univariate, mainVar) !== degMain) continue;
1349
- if (!this.isSquareFreeIn(univariate, mainVar)) continue;
1350
- const univariateFs: UpolynomialFactors = { constant: 1n, factors: [], degrees: [] };
1351
- factorSquareFree(
1352
- this.um,
1353
- this.um.getPrimitive(this.toCoeffs(univariate)),
1354
- univariateFs,
1355
- 1,
1356
- DEFAULT_FACTOR_PARAMS,
1357
- );
1358
- const factorCount = univariateFs.factors.length;
1359
- if (factorCount <= 1) continue;
1360
- const translated = this.translate(bivariate, liftVar, point);
1361
- const lcPolynomial = this.coeff(translated, mainVar, degMain);
1362
- const lcAtZero = this.isConst(lcPolynomial)
1363
- ? (lcPolynomial.as[0] ?? 0n)
1364
- : this.getConstValue(this.substitute(lcPolynomial, [liftVar], [0n]));
1365
- if (lcAtZero === null) continue;
1366
- for (const prime of FACTOR_PRIMES) {
1367
- if (getGcd(prime, lcAtZero) !== 1n) continue;
1368
- for (let split = 1; split <= Math.floor(factorCount / 2); split++) {
1369
- let h1 = univariateFs.factors[0];
1370
- for (let index = 1; index < split; index++)
1371
- h1 = this.um.mul(h1, univariateFs.factors[index]);
1372
- let h2 = univariateFs.factors[split];
1373
- for (let index = split + 1; index < factorCount; index++)
1374
- h2 = this.um.mul(h2, univariateFs.factors[index]);
1375
- const lifted = this.liftBivariate(
1376
- translated,
1377
- mainVar,
1378
- liftVar,
1379
- degLift,
1380
- this.um.flipSignIfLmNeg(h1),
1381
- this.um.flipSignIfLmNeg(h2),
1382
- lcAtZero,
1383
- prime,
1384
- );
1385
- if (lifted === null) continue;
1386
- const candidates = lifted.map((factor) => this.translate(factor, liftVar, -point));
1387
- if (evalVars.length === 0) {
1388
- for (const candidate of candidates) {
1389
- if (this.isConst(candidate) || this.degree(candidate, x) === 0) continue;
1390
- this.pushSmallFactor(candidate, x, k, result);
1391
- }
1392
- return true;
1393
- }
1394
- for (const candidate of candidates) {
1395
- if (this.isConst(candidate)) continue;
1396
- const division = this.exactPseudoDivision(
1397
- polynomial,
1398
- candidate,
1399
- this.maxVar(candidate),
1400
- );
1401
- if (division.remainder.size !== 0) continue;
1402
- if (!this.eq(this.mul(candidate, division.quotient), polynomial)) continue;
1403
- for (const part of [candidate, division.quotient]) {
1404
- if (this.isConst(part)) result.constant *= part.as[0];
1405
- else if (this.degree(part, x) !== 0) this.pushSmallFactor(part, x, k, result);
1406
- }
1407
- return true;
1408
- }
1409
- }
1410
- }
1411
- }
2783
+ this.limit.checkpoint();
2784
+ const pBivar = new PolynomialRef(this);
2785
+ const isFound = this.tryMultivarFactorCombo(
2786
+ polynomial,
2787
+ r,
2788
+ x,
2789
+ k,
2790
+ mainVar,
2791
+ degMain,
2792
+ liftVar,
2793
+ evalVars,
2794
+ combo,
2795
+ pBivar,
2796
+ );
2797
+ pBivar.reset();
2798
+ if (isFound) return true;
1412
2799
  }
1413
2800
  }
1414
2801
  }
1415
2802
  return false;
1416
2803
  }
1417
2804
 
1418
- // The factors of a lifted part, splitting only linear and quadratic ones further.
1419
- private pushSmallFactor(polynomial: Polynomial, x: number, k: number, result: Factors) {
1420
- const degree = this.degree(polynomial, x);
1421
- if (degree === 2 && this.isPrimitive(polynomial, x) && this.isSquareFreeIn(polynomial, x))
1422
- this.factorQuadratic(polynomial, x, k, result);
1423
- else this.pushFactor(result, polynomial, k);
2805
+ private tryMultivarFactorCombo(
2806
+ polynomial: Polynomial,
2807
+ r: Factors,
2808
+ x: number,
2809
+ k: number,
2810
+ mainVar: number,
2811
+ degMain: number,
2812
+ liftVar: number,
2813
+ evalVars: readonly number[],
2814
+ combo: number,
2815
+ pBivar: PolynomialRef,
2816
+ ) {
2817
+ const nEval = evalVars.length;
2818
+ if (nEval > 0) {
2819
+ const evalValues: bigint[] = [];
2820
+ for (let index = 0; index < nEval; index++) {
2821
+ let c = combo;
2822
+ for (let skip = 0; skip < index; skip++) c = Math.floor(c / FACTOR_EVAL_VALUES.length);
2823
+ evalValues.push(FACTOR_EVAL_VALUES[c % FACTOR_EVAL_VALUES.length]);
2824
+ }
2825
+ pBivar.set(this.substitute(polynomial, evalVars, evalValues));
2826
+ } else pBivar.set(polynomial);
2827
+ if (this.degree(pBivar.get(), mainVar) !== degMain) return false;
2828
+ const degLift = this.degree(pBivar.get(), liftVar);
2829
+ if (degLift === 0) return false;
2830
+ for (const point of FACTOR_EVAL_VALUES) {
2831
+ const pUniv = new PolynomialRef(this);
2832
+ const pUnivRef = new PolynomialRef(this);
2833
+ const q = new PolynomialRef(this);
2834
+ const lcPoly = new PolynomialRef(this);
2835
+ const isFound = this.tryMultivarFactorPoint(
2836
+ polynomial,
2837
+ r,
2838
+ x,
2839
+ k,
2840
+ mainVar,
2841
+ degMain,
2842
+ liftVar,
2843
+ nEval,
2844
+ degLift,
2845
+ point,
2846
+ pBivar,
2847
+ pUniv,
2848
+ pUnivRef,
2849
+ q,
2850
+ lcPoly,
2851
+ );
2852
+ lcPoly.reset();
2853
+ q.reset();
2854
+ pUnivRef.reset();
2855
+ pUniv.reset();
2856
+ if (isFound) return true;
2857
+ }
2858
+ return false;
1424
2859
  }
1425
2860
 
1426
- private getConstValue(polynomial: Polynomial) {
1427
- if (!this.isConst(polynomial)) return null;
1428
- return polynomial.as[0] ?? 0n;
2861
+ private tryMultivarFactorPoint(
2862
+ polynomial: Polynomial,
2863
+ r: Factors,
2864
+ x: number,
2865
+ k: number,
2866
+ mainVar: number,
2867
+ degMain: number,
2868
+ liftVar: number,
2869
+ nEval: number,
2870
+ degLift: number,
2871
+ point: bigint,
2872
+ pBivar: PolynomialRef,
2873
+ pUniv: PolynomialRef,
2874
+ pUnivRef: PolynomialRef,
2875
+ q: PolynomialRef,
2876
+ lcPoly: PolynomialRef,
2877
+ ) {
2878
+ pUniv.set(this.substitute(pBivar.get(), [liftVar], [point]));
2879
+ if (!this.isUnivariate(pUniv.get())) return false;
2880
+ if (this.degree(pUniv.get(), mainVar) !== degMain) return false;
2881
+ if (!this.isSquareFreeIn(pUniv.get(), mainVar)) return false;
2882
+ pUnivRef.copy(pUniv);
2883
+ const univariateFs = mkFactors();
2884
+ factorSquareFree(
2885
+ this.um,
2886
+ this.um.getPrimitive(this.toCoeffs(pUnivRef.get())),
2887
+ univariateFs,
2888
+ 1,
2889
+ DEFAULT_FACTOR_PARAMS,
2890
+ );
2891
+ const nf = univariateFs.factors.length;
2892
+ if (nf <= 1) return false;
2893
+ q.set(this.translate(pBivar.get(), liftVar, point));
2894
+ lcPoly.set(this.coeff(q.get(), mainVar, degMain));
2895
+ let lcAtZero = 0n;
2896
+ if (this.isConst(lcPoly.get())) lcAtZero = lcPoly.get().as[0] ?? 0n;
2897
+ else {
2898
+ const lcEval = new PolynomialRef(this);
2899
+ lcEval.set(this.substitute(lcPoly.get(), [liftVar], [0n]));
2900
+ const isConstant = this.isConst(lcEval.get());
2901
+ if (isConstant) lcAtZero = lcEval.get().as[0] ?? 0n;
2902
+ lcEval.reset();
2903
+ if (!isConstant) return false;
2904
+ }
2905
+ for (const prime of FACTOR_PRIMES) {
2906
+ if (getGcd(prime, lcAtZero) !== 1n) continue;
2907
+ for (let split = 1; split <= Math.floor(nf / 2); split++) {
2908
+ this.limit.checkpoint();
2909
+ let h1 = this.um.set(univariateFs.factors[0]);
2910
+ for (let index = 1; index < split; index++)
2911
+ h1 = this.um.mul(h1, univariateFs.factors[index]);
2912
+ let h2 = this.um.set(univariateFs.factors[split]);
2913
+ for (let index = split + 1; index < nf; index++)
2914
+ h2 = this.um.mul(h2, univariateFs.factors[index]);
2915
+ if (h1.length > 0 && h1[h1.length - 1] < 0n) h1 = h1.map((coeff) => -coeff);
2916
+ if (h2.length > 0 && h2[h2.length - 1] < 0n) h2 = h2.map((coeff) => -coeff);
2917
+ const f1 = new PolynomialRef(this);
2918
+ const f2 = new PolynomialRef(this);
2919
+ const isFound =
2920
+ this.tryBivarHenselLift(
2921
+ q.get(),
2922
+ mainVar,
2923
+ liftVar,
2924
+ degLift,
2925
+ h1,
2926
+ h2,
2927
+ lcAtZero,
2928
+ prime,
2929
+ f1,
2930
+ f2,
2931
+ ) && this.pushLiftedFactors(polynomial, r, x, k, nEval, liftVar, point, f1, f2);
2932
+ f2.reset();
2933
+ f1.reset();
2934
+ if (isFound) return true;
2935
+ }
2936
+ }
2937
+ return false;
1429
2938
  }
1430
2939
 
1431
- // try_bivar_hensel_lift: lifts q(x, 0) = lc * h1 * h2 to q = F1 * F2 in Z_p[x][y] by linear
1432
- // Hensel lifting on the coefficients of y, then reads F1 and F2 back over Z. Null when h1 and h2
1433
- // are not coprime in Z_p, q is not bivariate, or the product of the lifted factors is not q.
1434
- private liftBivariate(
2940
+ private pushLiftedFactors(
2941
+ polynomial: Polynomial,
2942
+ r: Factors,
2943
+ x: number,
2944
+ k: number,
2945
+ nEval: number,
2946
+ liftVar: number,
2947
+ point: bigint,
2948
+ f1: PolynomialRef,
2949
+ f2: PolynomialRef,
2950
+ ) {
2951
+ f1.set(this.translate(f1.get(), liftVar, -point));
2952
+ f2.set(this.translate(f2.get(), liftVar, -point));
2953
+ if (nEval === 0) {
2954
+ const bivarFs = [new PolynomialRef(this), new PolynomialRef(this)];
2955
+ bivarFs[0].copy(f1);
2956
+ bivarFs[1].copy(f2);
2957
+ for (const bf of bivarFs) {
2958
+ if (this.isConst(bf.get()) || this.degree(bf.get(), x) === 0) continue;
2959
+ this.pushSmallFactor(bf, r, x, k);
2960
+ }
2961
+ bivarFs[1].reset();
2962
+ bivarFs[0].reset();
2963
+ return true;
2964
+ }
2965
+ const cands = [new PolynomialRef(this), new PolynomialRef(this)];
2966
+ cands[0].copy(f1);
2967
+ cands[1].copy(f2);
2968
+ let isFound = false;
2969
+ for (const cand of cands) {
2970
+ if (this.isConst(cand.get())) continue;
2971
+ const qDiv = new PolynomialRef(this);
2972
+ const rDiv = new PolynomialRef(this);
2973
+ const divVar = this.maxVar(cand.get());
2974
+ this.exactPseudoDivision(polynomial, cand.get(), divVar, qDiv, rDiv);
2975
+ if (!this.isZero(rDiv.get())) {
2976
+ rDiv.reset();
2977
+ qDiv.reset();
2978
+ continue;
2979
+ }
2980
+ const check = new PolynomialRef(this);
2981
+ check.set(this.mul(cand.get(), qDiv.get()));
2982
+ if (this.eq(check.get(), polynomial)) {
2983
+ const parts = [new PolynomialRef(this), new PolynomialRef(this)];
2984
+ parts[0].copy(cand);
2985
+ parts[1].copy(qDiv);
2986
+ for (const part of parts) {
2987
+ if (this.isConst(part.get())) {
2988
+ r.constant *= part.get().as[0];
2989
+ continue;
2990
+ }
2991
+ if (this.degree(part.get(), x) === 0) continue;
2992
+ this.pushSmallFactor(part, r, x, k);
2993
+ }
2994
+ parts[1].reset();
2995
+ parts[0].reset();
2996
+ isFound = true;
2997
+ }
2998
+ check.reset();
2999
+ rDiv.reset();
3000
+ qDiv.reset();
3001
+ if (isFound) break;
3002
+ }
3003
+ cands[1].reset();
3004
+ cands[0].reset();
3005
+ return isFound;
3006
+ }
3007
+
3008
+ private tryBivarHenselLift(
1435
3009
  q: Polynomial,
1436
3010
  x: number,
1437
3011
  y: number,
1438
3012
  degY: number,
1439
3013
  h1: readonly bigint[],
1440
3014
  h2: readonly bigint[],
1441
- lc: bigint,
3015
+ lcValue: bigint,
1442
3016
  prime: bigint,
3017
+ f1Out: PolynomialRef,
3018
+ f2Out: PolynomialRef,
1443
3019
  ) {
1444
- const zp = new UpolynomialManager(prime);
3020
+ const zp = new UpolynomialManager(this.limit, prime);
1445
3021
  const f1 = zp.mkMonic(zp.set(h1));
1446
3022
  const f2 = zp.mkMonic(zp.set(h2));
1447
3023
  const ext = zp.extGcd(f1, f2);
1448
- if (ext.d.length !== 1 || ext.d[0] !== 1n) return null;
3024
+ if (ext.d.length !== 1 || ext.d[0] !== 1n) return false;
1449
3025
  const qCoeffs: bigint[][] = [];
1450
- for (let power = 0; power <= degY; power++) {
1451
- const coeff = this.coeff(q, y, power);
1452
- if (coeff.size !== 0 && !this.isUnivariate(coeff) && !this.isConst(coeff)) return null;
1453
- qCoeffs.push(zp.set(coeff.size === 0 ? [] : this.toCoeffs(coeff)));
3026
+ for (let j = 0; j <= degY; j++) {
3027
+ const cj = new PolynomialRef(this);
3028
+ cj.set(this.coeff(q, y, j));
3029
+ const isBivariate = this.isZero(cj.get()) || this.isUnivariate(cj.get());
3030
+ if (isBivariate) qCoeffs.push(zp.set(this.isZero(cj.get()) ? [] : this.toCoeffs(cj.get())));
3031
+ cj.reset();
3032
+ if (!isBivariate) return false;
1454
3033
  }
1455
3034
  const f1Coeffs: bigint[][] = Array.from({ length: degY + 1 }, () => []);
1456
3035
  const f2Coeffs: bigint[][] = Array.from({ length: degY + 1 }, () => []);
1457
3036
  f1Coeffs[0] = zp.set(f1);
1458
- f2Coeffs[0] = zp.mulConst(f2, zp.normalizeNumeral(lc));
1459
- const lcInv = zp.inv(lc);
1460
- for (let power = 1; power <= degY; power++) {
1461
- let error = zp.set(qCoeffs[power]);
1462
- for (let first = 0; first <= power; first++) {
1463
- const second = power - first;
1464
- if (second > degY || second === 0 || first === 0) continue;
3037
+ f2Coeffs[0] = zp.mulConst(zp.set(f2), zp.normalizeNumeral(lcValue));
3038
+ const lcInv = zp.inv(lcValue);
3039
+ for (let j = 1; j <= degY; j++) {
3040
+ this.limit.checkpoint();
3041
+ let e = zp.set(qCoeffs[j]);
3042
+ for (let first = 0; first <= j; first++) {
3043
+ const second = j - first;
3044
+ if (second > degY) continue;
3045
+ if (first === j && second === 0) continue;
3046
+ if (first === 0 && second === j) continue;
1465
3047
  if (f1Coeffs[first].length === 0 || f2Coeffs[second].length === 0) continue;
1466
- error = zp.sub(error, zp.mul(f1Coeffs[first], f2Coeffs[second]));
1467
- }
1468
- if (error.length === 0) continue;
1469
- const a = zp.divRem(zp.mul(error, ext.v), f1).remainder;
1470
- const b = zp.divRem(zp.mul(error, ext.u), f2).remainder;
1471
- f1Coeffs[power] = zp.mulConst(a, lcInv);
1472
- f2Coeffs[power] = zp.set(b);
1473
- }
1474
- const toPolynomial = (coeffs: readonly bigint[][]) => {
1475
- let result = this.zero;
1476
- for (let power = 0; power <= degY; power++) {
1477
- if (coeffs[power].length === 0) continue;
1478
- const univariate = this.fromCoeffs(coeffs[power], x);
1479
- if (univariate.size === 0) continue;
1480
- result = this.add(result, this.mulTerm(1n, this.mkPower(y, power), univariate));
3048
+ e = zp.sub(e, zp.mul(f1Coeffs[first], f2Coeffs[second]));
1481
3049
  }
1482
- return result;
1483
- };
1484
- const first = toPolynomial(f1Coeffs);
1485
- const second = toPolynomial(f2Coeffs);
1486
- return this.eq(this.mul(first, second), q) ? [first, second] : null;
1487
- }
1488
-
1489
- // psc_chain: the nonzero principal subresultant coefficients of p and q in x, the resultant
1490
- // first, or [0] when there are none. psc_chain_optimized: Ducos's subresultant chain with
1491
- // Lazard's dichotomous S_e.
1492
- pscChain(first: Polynomial, second: Polynomial, variable: number) {
1493
- const chain =
1494
- this.degree(first, variable) >= this.degree(second, variable)
1495
- ? this.pscChainCore(first, second, variable)
1496
- : this.pscChainCore(second, first, variable);
1497
- return chain.length === 0 ? [this.zero] : chain.reverse();
1498
- }
1499
-
1500
- private pscChainCore(p: Polynomial, q: Polynomial, x: number) {
1501
- const chain: Polynomial[] = [];
1502
- let s = this.pw(this.lc(q, x), this.degree(p, x) - this.degree(q, x));
1503
- let a = q;
1504
- let b = this.exactPseudoRemainder(p, this.neg(q), x);
1505
- while (b.size > 0) {
1506
- const d = this.degree(a, x);
1507
- const e = this.degree(b, x);
1508
- // b is S_{d-1}.
1509
- const principal = this.coeff(b, x, d - 1);
1510
- if (principal.size > 0) chain.push(principal);
1511
- let c = b;
1512
- if (d - e > 1) {
1513
- c = this.getSeLazard(d, s, b, x);
1514
- const principalE = this.coeff(c, x, e);
1515
- if (principalE.size > 0) chain.push(principalE);
1516
- }
1517
- if (e === 0) break;
1518
- b = this.getOptimizedSe1(d, e, a, b, c, s, x);
1519
- a = c;
1520
- s = this.lc(a, x);
3050
+ if (e.length === 0) continue;
3051
+ const a = zp.divRem(zp.mul(e, ext.v), f1).remainder;
3052
+ const b = zp.divRem(zp.mul(e, ext.u), f2).remainder;
3053
+ f1Coeffs[j] = zp.mulConst(a, lcInv);
3054
+ f2Coeffs[j] = zp.set(b);
1521
3055
  }
1522
- return chain;
3056
+ return this.reconstructLiftedFactors(q, x, y, degY, f1Coeffs, f2Coeffs, f1Out, f2Out);
1523
3057
  }
1524
3058
 
1525
- // Se_Lazard: S_e from S_{d-1} and lc(S_d) by dichotomous Lazard.
1526
- private getSeLazard(d: number, lcSd: Polynomial, sd1: Polynomial, x: number) {
1527
- let n = d - this.degree(sd1, x) - 1;
1528
- if (n === 0) return sd1;
1529
- const lcSd1 = this.lc(sd1, x);
1530
- let a = 1 << (31 - Math.clz32(n));
1531
- let c = lcSd1;
1532
- n -= a;
1533
- while (a !== 1) {
1534
- a /= 2;
1535
- c = this.exactDiv(this.mul(c, c), lcSd);
1536
- if (n >= a) {
1537
- c = this.exactDiv(this.mul(c, lcSd1), lcSd);
1538
- n -= a;
3059
+ private reconstructLiftedFactors(
3060
+ q: Polynomial,
3061
+ x: number,
3062
+ y: number,
3063
+ degY: number,
3064
+ f1Coeffs: readonly bigint[][],
3065
+ f2Coeffs: readonly bigint[][],
3066
+ f1Out: PolynomialRef,
3067
+ f2Out: PolynomialRef,
3068
+ ) {
3069
+ const f1Poly = new PolynomialRef(this);
3070
+ const f2Poly = new PolynomialRef(this);
3071
+ f1Poly.set(this.zero);
3072
+ f2Poly.set(this.zero);
3073
+ const addTerm = (coeffs: readonly bigint[], power: number, target: PolynomialRef) => {
3074
+ if (coeffs.length === 0) return;
3075
+ const univ = new PolynomialRef(this);
3076
+ univ.set(this.toPolynomial(coeffs, x));
3077
+ if (!this.isZero(univ.get())) {
3078
+ const term = new PolynomialRef(this);
3079
+ term.set(this.mulTerm(1n, this.mkPower(y, power), univ.get()));
3080
+ target.set(this.add(target.get(), term.get()));
3081
+ term.reset();
1539
3082
  }
3083
+ univ.reset();
3084
+ };
3085
+ for (let j = 0; j <= degY; j++) {
3086
+ addTerm(f1Coeffs[j], j, f1Poly);
3087
+ addTerm(f2Coeffs[j], j, f2Poly);
1540
3088
  }
1541
- return this.exactDiv(this.mul(c, sd1), lcSd);
3089
+ const product = new PolynomialRef(this);
3090
+ product.set(this.mul(f1Poly.get(), f2Poly.get()));
3091
+ const isEqual = this.eq(product.get(), q);
3092
+ if (isEqual) {
3093
+ f1Out.copy(f1Poly);
3094
+ f2Out.copy(f2Poly);
3095
+ }
3096
+ product.reset();
3097
+ f2Poly.reset();
3098
+ f1Poly.reset();
3099
+ return isEqual;
1542
3100
  }
1543
3101
 
1544
- // optimized_S_e_1: S_{e-1} from A = S_{d+1}, S_{d-1}, S_e and s = lc(S_d).
1545
- private getOptimizedSe1(
1546
- d: number,
1547
- e: number,
1548
- a: Polynomial,
1549
- sd1: Polynomial,
1550
- se: Polynomial,
1551
- s: Polynomial,
1552
- x: number,
1553
- ) {
1554
- const cd1 = this.lc(sd1, x);
1555
- const lcSe = this.lc(se, x);
1556
- const getPower = (power: number) => (power === 0 ? this.one : this.mkVar(x, power));
1557
- const h: Polynomial[] = [];
1558
- for (let j = 0; j < e; j++) h.push(this.mul(lcSe, getPower(j)));
1559
- h.push(this.sub(this.mul(lcSe, getPower(e)), se));
1560
- const xPolynomial = this.mkVar(x);
1561
- for (let j = e + 1; j < d; j++) {
1562
- const xh = this.mul(xPolynomial, h[j - 1]);
1563
- h.push(this.sub(xh, this.exactDiv(this.mul(this.coeff(xh, x, e), sd1), cd1)));
1564
- }
1565
- let sum = this.zero;
1566
- for (let j = 0; j < d; j++) sum = this.add(sum, this.mul(this.coeff(a, x, j), h[j]));
1567
- const dPolynomial = this.exactDiv(sum, this.lc(a, x));
1568
- const xh = this.mul(xPolynomial, h[d - 1]);
1569
- const result = this.exactDiv(
1570
- this.sub(this.mul(cd1, this.add(xh, dPolynomial)), this.mul(this.coeff(xh, x, e), sd1)),
1571
- s,
1572
- );
1573
- return (d - e + 1) % 2 === 1 ? this.neg(result) : result;
3102
+ evaluateWith<T>(polynomial: Polynomial, ops: ValueOps<T>, getValue: (variable: number) => T) {
3103
+ const result = this.evaluatePartially(polynomial, ops, getValue);
3104
+ if (result === null) throw new SmtInvariantError("a total evaluation stopped early");
3105
+ return result;
1574
3106
  }
1575
3107
 
1576
- // Evaluation.
1577
-
1578
- // t_eval: p at the values of its variables, by Horner on the lexicographically sorted monomials,
1579
- // which sorts p in place as Z3 does.
1580
- evaluateWith<T>(polynomial: Polynomial, ops: ValueOps<T>, getValue: (variable: number) => T) {
3108
+ private evaluatePartially<T>(
3109
+ polynomial: Polynomial,
3110
+ ops: ValueOps<T>,
3111
+ getValue: (variable: number) => T | null,
3112
+ ) {
1581
3113
  if (polynomial.size === 0) return ops.fromInteger(0n);
1582
3114
  if (this.isConst(polynomial)) return ops.fromInteger(polynomial.as[0]);
1583
3115
  polynomial.lexSort();
@@ -1591,38 +3123,41 @@ export class PolynomialManager {
1591
3123
  );
1592
3124
  }
1593
3125
 
1594
- // t_eval_core: the monomials in [start, end), ignoring the variables above x.
1595
3126
  private evaluateCore<T>(
1596
3127
  polynomial: Polynomial,
1597
3128
  ops: ValueOps<T>,
1598
- getValue: (variable: number) => T,
3129
+ getValue: (variable: number) => T | null,
1599
3130
  start: number,
1600
3131
  end: number,
1601
3132
  x: number,
1602
- ): T {
3133
+ ): T | null {
1603
3134
  if (end === start + 1) {
1604
3135
  let result = ops.fromInteger(polynomial.as[start]);
1605
3136
  const monomial = polynomial.ms[start];
1606
3137
  for (let index = 0; index < monomial.size; index++) {
1607
3138
  const variable = monomial.vars[index];
1608
3139
  if (variable > x) break;
1609
- result = ops.mul(result, ops.power(getValue(variable), monomial.degrees[index]));
3140
+ const value = getValue(variable);
3141
+ if (value === null) return null;
3142
+ result = ops.mul(result, ops.power(value, monomial.degrees[index]));
1610
3143
  }
1611
3144
  return result;
1612
3145
  }
1613
3146
  const value = getValue(x);
3147
+ if (value === null) return null;
1614
3148
  let result = ops.fromInteger(0n);
1615
3149
  let index = start;
1616
3150
  while (index < end) {
3151
+ this.limit.checkpoint();
1617
3152
  const degree = polynomial.ms[index].degreeOf(x);
1618
3153
  if (degree === 0) {
1619
3154
  const below = this.maxSmallerThan(polynomial, index, end, x);
1620
- result = ops.add(
1621
- result,
3155
+ const rest =
1622
3156
  below === NULL_VAR
1623
3157
  ? ops.fromInteger(polynomial.as[index])
1624
- : this.evaluateCore(polynomial, ops, getValue, index, end, below),
1625
- );
3158
+ : this.evaluateCore(polynomial, ops, getValue, index, end, below);
3159
+ if (rest === null) return null;
3160
+ result = ops.add(result, rest);
1626
3161
  break;
1627
3162
  }
1628
3163
  let next = index + 1;
@@ -1635,19 +3170,17 @@ export class PolynomialManager {
1635
3170
  }
1636
3171
  }
1637
3172
  const below = this.maxSmallerThan(polynomial, index, next, x);
1638
- result = ops.add(
1639
- result,
3173
+ const coeff =
1640
3174
  below === NULL_VAR
1641
3175
  ? ops.fromInteger(polynomial.as[index])
1642
- : this.evaluateCore(polynomial, ops, getValue, index, next, below),
1643
- );
1644
- result = ops.mul(result, ops.power(value, degree - nextDegree));
3176
+ : this.evaluateCore(polynomial, ops, getValue, index, next, below);
3177
+ if (coeff === null) return null;
3178
+ result = ops.mul(ops.add(result, coeff), ops.power(value, degree - nextDegree));
1645
3179
  index = next;
1646
3180
  }
1647
3181
  return result;
1648
3182
  }
1649
3183
 
1650
- // max_smaller_than: the largest variable below x in the monomials in [start, end).
1651
3184
  private maxSmallerThan(polynomial: Polynomial, start: number, end: number, x: number) {
1652
3185
  let max = NULL_VAR;
1653
3186
  for (let index = start; index < end; index++)
@@ -1655,68 +3188,88 @@ export class PolynomialManager {
1655
3188
  return max;
1656
3189
  }
1657
3190
 
1658
- evaluate(polynomial: Polynomial, values: readonly (Rational | undefined)[]) {
1659
- return this.evaluateWith(polynomial, RATIONAL_OPS, (variable) => {
1660
- const value = values[variable];
1661
- if (value === undefined) throw new SmtInvariantError(`x${variable} is unassigned`);
1662
- return value;
1663
- });
1664
- }
1665
-
1666
- getSign(polynomial: Polynomial, values: readonly (Rational | undefined)[]) {
1667
- const value = this.evaluate(polynomial, values);
1668
- return value.isZero() ? 0 : value.isPositive() ? 1 : -1;
3191
+ getRationalSign(polynomial: Polynomial, values: readonly (Rational | undefined)[]) {
3192
+ const value = this.evaluatePartially(
3193
+ polynomial,
3194
+ RATIONAL_OPS,
3195
+ (variable) => values[variable] ?? null,
3196
+ );
3197
+ return value === null ? null : value.isZero() ? 0 : value.isPositive() ? 1 : -1;
1669
3198
  }
1670
3199
  }
1671
3200
 
1672
- // polynomial::cache: hash-conses polynomials and memoizes their subresultants and factors.
1673
3201
  export class PolynomialCache {
1674
3202
  private table = new Map<string, Polynomial>();
1675
- private inCache = new Set<number>();
3203
+ private cachedPolys: PolynomialRefVector;
3204
+ private inCache: boolean[] = [];
1676
3205
  private pscChains = new Map<string, Polynomial[]>();
1677
3206
  private factorizations = new Map<number, Polynomial[]>();
1678
3207
 
1679
- constructor(readonly pm: PolynomialManager) {}
3208
+ constructor(readonly pm: PolynomialManager) {
3209
+ this.cachedPolys = new PolynomialRefVector(pm);
3210
+ }
1680
3211
 
1681
3212
  reset() {
1682
3213
  this.table.clear();
1683
- this.inCache.clear();
1684
3214
  this.pscChains.clear();
1685
3215
  this.factorizations.clear();
3216
+ this.inCache = [];
3217
+ this.cachedPolys.reset();
1686
3218
  }
1687
3219
 
1688
3220
  mkUnique(polynomial: Polynomial) {
1689
- if (this.inCache.has(polynomial.id)) return polynomial;
3221
+ if (this.inCache[polynomial.id] === true) return polynomial;
1690
3222
  const key = this.pm.getKey(polynomial);
1691
3223
  const existing = this.table.get(key);
1692
3224
  if (existing !== undefined) return existing;
1693
3225
  this.table.set(key, polynomial);
1694
- this.inCache.add(polynomial.id);
3226
+ this.cachedPolys.push(polynomial);
3227
+ this.inCache[polynomial.id] = true;
1695
3228
  return polynomial;
1696
3229
  }
1697
3230
 
1698
3231
  contains(polynomial: Polynomial) {
1699
- return this.inCache.has(polynomial.id);
3232
+ return this.inCache[polynomial.id] === true;
1700
3233
  }
1701
3234
 
1702
- pscChain(first: Polynomial, second: Polynomial, variable: number) {
3235
+ pscChain(first: Polynomial, second: Polynomial, variable: number, chain: PolynomialRefVector) {
1703
3236
  const p = this.mkUnique(first);
1704
3237
  const q = this.mkUnique(second);
1705
3238
  const key = `${p.id},${q.id},${variable}`;
1706
3239
  const cached = this.pscChains.get(key);
1707
- if (cached !== undefined) return cached;
1708
- const chain = this.pm.pscChain(p, q, variable).map((element) => this.mkUnique(element));
1709
- this.pscChains.set(key, chain);
1710
- return chain;
1711
- }
1712
-
1713
- // factor: the distinct factors, without the constant.
1714
- factor(polynomial: Polynomial) {
1715
- const unique = this.mkUnique(polynomial);
1716
- const cached = this.factorizations.get(unique.id);
1717
- if (cached !== undefined) return cached;
1718
- const factors = this.pm.factor(unique).factors.map((factor) => this.mkUnique(factor));
1719
- this.factorizations.set(unique.id, factors);
1720
- return factors;
3240
+ if (cached !== undefined) {
3241
+ chain.reset();
3242
+ for (const element of cached) chain.push(element);
3243
+ return;
3244
+ }
3245
+ this.pm.pscChain(p, q, variable, chain);
3246
+ const result: Polynomial[] = [];
3247
+ for (let index = 0; index < chain.size; index++) {
3248
+ const unique = this.mkUnique(chain.get(index));
3249
+ chain.set(index, unique);
3250
+ result.push(unique);
3251
+ }
3252
+ this.pscChains.set(key, result);
3253
+ }
3254
+
3255
+ factor(polynomial: Polynomial, distinctFactors: PolynomialRefVector) {
3256
+ distinctFactors.reset();
3257
+ const p = this.mkUnique(polynomial);
3258
+ const cached = this.factorizations.get(p.id);
3259
+ if (cached !== undefined) {
3260
+ distinctFactors.reset();
3261
+ for (const factor of cached) distinctFactors.push(factor);
3262
+ return;
3263
+ }
3264
+ const fs = new Factors(this.pm);
3265
+ this.pm.factor(p, fs);
3266
+ const result: Polynomial[] = [];
3267
+ for (const factor of fs.factors) {
3268
+ const unique = this.mkUnique(factor);
3269
+ distinctFactors.push(unique);
3270
+ result.push(unique);
3271
+ }
3272
+ this.factorizations.set(p.id, result);
3273
+ fs.reset();
1721
3274
  }
1722
3275
  }