nx_math.nx source
↩ module page · 54 lines · 2161 B
1// nx_math.nx -- canonical pure-integer math helpers.
2//
3// Single-source-of-truth for numeric utilities that were previously
4// duplicated across nx_geom, nx_light, nx_pc, nx_theorems7, and
5// likely many more. This is THE home of integer sqrt and friends.
6//
7// Consolidation principle (per CAPTAIN_MORONI + deduped-substrate
8// doctrine): exactly one implementation per pure-math utility.
9// All consumers import nx_math and call the canonical version.
10//
11// Equivalence verified via nx_func_compare:
12// nx_geom_isqrt, nx_light_isqrt, nx_pc_isqrt, nx_th_isqrt
13// all hashed to 5794444719011524842 (FNV-1a 64-bit, normalized).
14//
15// genealogy_id: newton_1669_general_method + heron_alexandria_70AD
16// + bertrand_brent_iqsrt_handbook_1976
17// lineage_id: integer_newton_iteration + fixed_point_iteration
18// axioms: NX_AX_ALG_DISTRIBUTIVITY (Newton step is rearrangement
19// of (x + n/x)/2 = average of x and n/x, which converges
20// monotonically to floor(sqrt(n)) by AM-GM inequality)
21// + NX_AX_ORD_LEAST_UPPER_BOUND (the integer sqrt is the
22// greatest integer y with y*y <= n -- well-defined by LUB
23// on bounded sets of integers).
24
25// nx_safety_envelope:
26// intended_use: AUTO_APPLIED -- primitive-specific tuning queued
27// sil_target: SIL1
28// evidence: [bulk_applied_2026-05-16, see-file-comment-for-detail]
29// verdict: NOT_YET_EVALUATED
30
31import "syscalls.nx"
32import "nx_axioms.nx"
33
34// ===== Integer sqrt (Newton's method) ==================================
35//
36// Returns floor(sqrt(n)) for n >= 0. Returns 0 for n < 0 (conventional
37// rather than abortive -- caller must check sign if invariant matters).
38// Returns 0 for n == 0.
39//
40// Convergence: x_{k+1} = (x_k + n/x_k) / 2. Monotone decreasing toward
41// floor(sqrt(n)) once x_k >= floor(sqrt(n)). Initial x_0 = n converges
42// in O(log n) iterations.
43
44func nx_math_isqrt(n: i64) -> i64 {
45 if n < 0 { return 0 }
46 if n == 0 { return 0 }
47 var x: i64 = n
48 var y: i64 = (x + 1) / 2
49 while y < x {
50 x = y
51 y = (x + n / x) / 2
52 }
53 return x
54}