interplane.Get Omega
Read in your language

omega-mv

Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance.

Brought by drakestapleton

branch main Branches Tags History

omega-mv / research / atemporal / at1 / evaluator / src / big.rs

471 lines · 14410 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Arbitrary-precision signed integers (std only). Little-endian u32 limbs,
17//! normalised (no high zero limbs; zero is an empty vector with neg = false).
18//! Division is Knuth algorithm D (Hacker's Delight divmnu form).
19
20use std::cmp::Ordering;
21
22#[derive(Clone, Debug, PartialEq, Eq)]
23pub struct Int {
24 neg: bool,
25 mag: Vec<u32>,
26}
27
28fn trim(v: &mut Vec<u32>) {
29 while let Some(&0) = v.last() {
30 v.pop();
31 }
32}
33
34fn mag_cmp(a: &[u32], b: &[u32]) -> Ordering {
35 if a.len() != b.len() {
36 return a.len().cmp(&b.len());
37 }
38 for i in (0..a.len()).rev() {
39 if a[i] != b[i] {
40 return a[i].cmp(&b[i]);
41 }
42 }
43 Ordering::Equal
44}
45
46fn mag_add(a: &[u32], b: &[u32]) -> Vec<u32> {
47 let (a, b) = if a.len() >= b.len() { (a, b) } else { (b, a) };
48 let mut r = Vec::with_capacity(a.len() + 1);
49 let mut carry = 0u64;
50 for i in 0..a.len() {
51 let s = a[i] as u64 + if i < b.len() { b[i] as u64 } else { 0 } + carry;
52 r.push(s as u32);
53 carry = s >> 32;
54 }
55 if carry != 0 {
56 r.push(carry as u32);
57 }
58 r
59}
60
61/// a - b, requires a >= b.
62fn mag_sub(a: &[u32], b: &[u32]) -> Vec<u32> {
63 let mut r = Vec::with_capacity(a.len());
64 let mut borrow = 0i64;
65 for i in 0..a.len() {
66 let mut d = a[i] as i64 - borrow - if i < b.len() { b[i] as i64 } else { 0 };
67 if d < 0 {
68 d += 1 << 32;
69 borrow = 1;
70 } else {
71 borrow = 0;
72 }
73 r.push(d as u32);
74 }
75 assert!(borrow == 0, "mag_sub underflow");
76 trim(&mut r);
77 r
78}
79
80fn mag_mul(a: &[u32], b: &[u32]) -> Vec<u32> {
81 if a.is_empty() || b.is_empty() {
82 return Vec::new();
83 }
84 let mut r = vec![0u32; a.len() + b.len()];
85 for i in 0..a.len() {
86 let mut carry = 0u64;
87 let ai = a[i] as u64;
88 if ai == 0 {
89 continue;
90 }
91 for j in 0..b.len() {
92 let t = ai * b[j] as u64 + r[i + j] as u64 + carry;
93 r[i + j] = t as u32;
94 carry = t >> 32;
95 }
96 let mut k = i + b.len();
97 while carry != 0 {
98 let t = r[k] as u64 + carry;
99 r[k] = t as u32;
100 carry = t >> 32;
101 k += 1;
102 }
103 }
104 trim(&mut r);
105 r
106}
107
108fn mag_divrem_small(a: &[u32], d: u32) -> (Vec<u32>, u32) {
109 let mut q = vec![0u32; a.len()];
110 let mut rem = 0u64;
111 for i in (0..a.len()).rev() {
112 let cur = (rem << 32) | a[i] as u64;
113 q[i] = (cur / d as u64) as u32;
114 rem = cur % d as u64;
115 }
116 trim(&mut q);
117 (q, rem as u32)
118}
119
120/// Knuth D. Requires v nonzero.
121fn mag_divrem(u: &[u32], v: &[u32]) -> (Vec<u32>, Vec<u32>) {
122 assert!(!v.is_empty(), "division by zero");
123 if mag_cmp(u, v) == Ordering::Less {
124 return (Vec::new(), u.to_vec());
125 }
126 if v.len() == 1 {
127 let (q, r) = mag_divrem_small(u, v[0]);
128 let mut rv = vec![r];
129 trim(&mut rv);
130 return (q, rv);
131 }
132 let n = v.len();
133 let m = u.len() - n;
134 let s = v[n - 1].leading_zeros();
135 let mut vn = vec![0u32; n];
136 let mut un = vec![0u32; u.len() + 1];
137 if s > 0 {
138 for i in (1..n).rev() {
139 vn[i] = (v[i] << s) | (v[i - 1] >> (32 - s));
140 }
141 vn[0] = v[0] << s;
142 un[u.len()] = u[u.len() - 1] >> (32 - s);
143 for i in (1..u.len()).rev() {
144 un[i] = (u[i] << s) | (u[i - 1] >> (32 - s));
145 }
146 un[0] = u[0] << s;
147 } else {
148 vn.copy_from_slice(v);
149 un[..u.len()].copy_from_slice(u);
150 un[u.len()] = 0;
151 }
152 let b: u128 = 1u128 << 32;
153 let mut q = vec![0u32; m + 1];
154 for j in (0..=m).rev() {
155 let num: u128 = ((un[j + n] as u128) << 32) | un[j + n - 1] as u128;
156 let mut qhat = num / vn[n - 1] as u128;
157 let mut rhat = num % vn[n - 1] as u128;
158 loop {
159 if qhat >= b || qhat * vn[n - 2] as u128 > ((rhat << 32) | un[j + n - 2] as u128) {
160 qhat -= 1;
161 rhat += vn[n - 1] as u128;
162 if rhat < b {
163 continue;
164 }
165 }
166 break;
167 }
168 let mut k: i128 = 0;
169 let mut t: i128;
170 for i in 0..n {
171 let p: u128 = qhat * vn[i] as u128;
172 t = un[i + j] as i128 - k - (p & 0xffff_ffff) as i128;
173 un[i + j] = t as u32;
174 k = (p >> 32) as i128 - (t >> 32);
175 }
176 t = un[j + n] as i128 - k;
177 un[j + n] = t as u32;
178 q[j] = qhat as u32;
179 if t < 0 {
180 q[j] = q[j].wrapping_sub(1);
181 let mut c: u64 = 0;
182 for i in 0..n {
183 let s2 = un[i + j] as u64 + vn[i] as u64 + c;
184 un[i + j] = s2 as u32;
185 c = s2 >> 32;
186 }
187 un[j + n] = un[j + n].wrapping_add(c as u32);
188 }
189 }
190 let mut r = vec![0u32; n];
191 if s > 0 {
192 for i in 0..n {
193 r[i] = (un[i] >> s) | (((un[i + 1] as u64) << (32 - s)) as u32);
194 }
195 } else {
196 r.copy_from_slice(&un[..n]);
197 }
198 trim(&mut q);
199 trim(&mut r);
200 (q, r)
201}
202
203impl Int {
204 pub fn zero() -> Int {
205 Int { neg: false, mag: Vec::new() }
206 }
207 pub fn from_u64(v: u64) -> Int {
208 let mut mag = vec![v as u32, (v >> 32) as u32];
209 trim(&mut mag);
210 Int { neg: false, mag }
211 }
212 pub fn from_i64(v: i64) -> Int {
213 let mut r = Int::from_u64(v.unsigned_abs());
214 r.neg = v < 0 && !r.mag.is_empty();
215 r
216 }
217 fn from_parts(neg: bool, mut mag: Vec<u32>) -> Int {
218 trim(&mut mag);
219 let neg = neg && !mag.is_empty();
220 Int { neg, mag }
221 }
222 /// Parses a string of ASCII decimal digits (no sign). None if empty or not digits.
223 pub fn from_dec_digits(s: &str) -> Option<Int> {
224 if s.is_empty() || !s.bytes().all(|c| c.is_ascii_digit()) {
225 return None;
226 }
227 let mut mag: Vec<u32> = Vec::new();
228 for chunk in s.as_bytes().chunks(9) {
229 let mut mul: u64 = 1;
230 let mut add: u64 = 0;
231 for &c in chunk {
232 mul *= 10;
233 add = add * 10 + (c - b'0') as u64;
234 }
235 let mut carry = add;
236 for limb in mag.iter_mut() {
237 let t = *limb as u64 * mul + carry;
238 *limb = t as u32;
239 carry = t >> 32;
240 }
241 while carry != 0 {
242 mag.push(carry as u32);
243 carry >>= 32;
244 }
245 }
246 Some(Int::from_parts(false, mag))
247 }
248 pub fn to_dec(&self) -> String {
249 if self.mag.is_empty() {
250 return "0".to_string();
251 }
252 let mut parts = Vec::new();
253 let mut cur = self.mag.clone();
254 while !cur.is_empty() {
255 let (q, r) = mag_divrem_small(&cur, 1_000_000_000);
256 parts.push(r);
257 cur = q;
258 }
259 let mut s = String::new();
260 if self.neg {
261 s.push('-');
262 }
263 s.push_str(&parts.last().unwrap().to_string());
264 for p in parts.iter().rev().skip(1) {
265 s.push_str(&format!("{:09}", p));
266 }
267 s
268 }
269 pub fn is_zero(&self) -> bool {
270 self.mag.is_empty()
271 }
272 pub fn is_neg(&self) -> bool {
273 self.neg
274 }
275 pub fn signum(&self) -> i32 {
276 if self.mag.is_empty() {
277 0
278 } else if self.neg {
279 -1
280 } else {
281 1
282 }
283 }
284 pub fn neg(&self) -> Int {
285 Int::from_parts(!self.neg, self.mag.clone())
286 }
287 pub fn abs(&self) -> Int {
288 Int::from_parts(false, self.mag.clone())
289 }
290 pub fn add(&self, o: &Int) -> Int {
291 if self.neg == o.neg {
292 return Int::from_parts(self.neg, mag_add(&self.mag, &o.mag));
293 }
294 match mag_cmp(&self.mag, &o.mag) {
295 Ordering::Equal => Int::zero(),
296 Ordering::Greater => Int::from_parts(self.neg, mag_sub(&self.mag, &o.mag)),
297 Ordering::Less => Int::from_parts(o.neg, mag_sub(&o.mag, &self.mag)),
298 }
299 }
300 pub fn sub(&self, o: &Int) -> Int {
301 self.add(&o.neg())
302 }
303 pub fn mul(&self, o: &Int) -> Int {
304 Int::from_parts(self.neg != o.neg, mag_mul(&self.mag, &o.mag))
305 }
306 /// Truncated division (quotient rounds toward zero; remainder has the sign of self).
307 pub fn divrem(&self, o: &Int) -> (Int, Int) {
308 let (q, r) = mag_divrem(&self.mag, &o.mag);
309 (Int::from_parts(self.neg != o.neg, q), Int::from_parts(self.neg, r))
310 }
311 /// Floor division and the matching non-negative remainder for a positive divisor.
312 pub fn div_floor(&self, o: &Int) -> (Int, Int) {
313 assert!(o.signum() > 0);
314 let (q, r) = self.divrem(o);
315 if r.is_neg() {
316 (q.sub(&Int::from_u64(1)), r.add(o))
317 } else {
318 (q, r)
319 }
320 }
321 pub fn cmp(&self, o: &Int) -> Ordering {
322 match (self.neg, o.neg) {
323 (false, true) => Ordering::Greater,
324 (true, false) => Ordering::Less,
325 (false, false) => mag_cmp(&self.mag, &o.mag),
326 (true, true) => mag_cmp(&o.mag, &self.mag),
327 }
328 }
329 pub fn gcd(a: &Int, b: &Int) -> Int {
330 let mut x = a.abs();
331 let mut y = b.abs();
332 while !y.is_zero() {
333 let (_, r) = x.divrem(&y);
334 x = y;
335 y = r;
336 }
337 x
338 }
339 pub fn shl(&self, bits: u32) -> Int {
340 if self.mag.is_empty() {
341 return self.clone();
342 }
343 let limbs = (bits / 32) as usize;
344 let s = bits % 32;
345 let mut r = vec![0u32; limbs];
346 if s == 0 {
347 r.extend_from_slice(&self.mag);
348 } else {
349 let mut carry = 0u32;
350 for &l in &self.mag {
351 r.push((l << s) | carry);
352 carry = l >> (32 - s);
353 }
354 if carry != 0 {
355 r.push(carry);
356 }
357 }
358 Int::from_parts(self.neg, r)
359 }
360 pub fn bits(&self) -> u32 {
361 match self.mag.last() {
362 None => 0,
363 Some(&top) => (self.mag.len() as u32 - 1) * 32 + (32 - top.leading_zeros()),
364 }
365 }
366 pub fn pow10(k: u32) -> Int {
367 let mut r = Int::from_u64(1);
368 let ten = Int::from_u64(10);
369 for _ in 0..k {
370 r = r.mul(&ten);
371 }
372 r
373 }
374 pub fn pow2(k: u32) -> Int {
375 Int::from_u64(1).shl(k)
376 }
377 /// floor(sqrt(self)) for self >= 0.
378 pub fn isqrt(&self) -> Int {
379 assert!(!self.neg);
380 if self.is_zero() {
381 return Int::zero();
382 }
383 let mut x = Int::pow2(self.bits() / 2 + 1);
384 loop {
385 let (q, _) = self.divrem(&x);
386 let y = x.add(&q).shr1();
387 if y.cmp(&x) != Ordering::Less {
388 return x;
389 }
390 x = y;
391 }
392 }
393 fn shr1(&self) -> Int {
394 let mut r = self.mag.clone();
395 let mut carry = 0u32;
396 for i in (0..r.len()).rev() {
397 let l = r[i];
398 r[i] = (l >> 1) | (carry << 31);
399 carry = l & 1;
400 }
401 Int::from_parts(self.neg, r)
402 }
403 pub fn is_even(&self) -> bool {
404 self.mag.first().map_or(true, |l| l & 1 == 0)
405 }
406 /// The low 64 bits of the magnitude.
407 pub fn low_u64(&self) -> u64 {
408 let a = *self.mag.first().unwrap_or(&0) as u64;
409 let b = *self.mag.get(1).unwrap_or(&0) as u64;
410 a | (b << 32)
411 }
412 /// Top 64 bits of the magnitude, and the shift such that |self| ~ top * 2^shift (exact when shift <= 0).
413 pub fn top_bits(&self, want: u32) -> (u64, i32) {
414 let b = self.bits();
415 if b <= want {
416 return (self.low_u64(), 0);
417 }
418 let shift = b - want;
419 let (q, _) = mag_divrem(&self.mag, &Int::pow2(shift).mag);
420 let qi = Int::from_parts(false, q);
421 (qi.low_u64(), shift as i32)
422 }
423}
424
425#[cfg(test)]
426mod tests {
427 use super::*;
428 #[test]
429 fn dec_roundtrip_and_division() {
430 let a = Int::from_dec_digits("340282366920938463463374607431768211457").unwrap();
431 assert_eq!(a.to_dec(), "340282366920938463463374607431768211457");
432 let b = Int::from_dec_digits("18446744073709551629").unwrap();
433 let (q, r) = a.divrem(&b);
434 assert_eq!(q.mul(&b).add(&r), a);
435 assert!(r.cmp(&b) == Ordering::Less);
436 let c = a.mul(&a).add(&Int::from_u64(12345));
437 assert_eq!(c.isqrt(), a);
438 assert_eq!(Int::gcd(&Int::from_i64(-12), &Int::from_u64(18)), Int::from_u64(6));
439 let (fq, fr) = Int::from_i64(-7).div_floor(&Int::from_u64(4));
440 assert_eq!((fq, fr), (Int::from_i64(-2), Int::from_u64(1)));
441 }
442 #[test]
443 fn knuth_d_random_like() {
444 // deterministic pseudo-random operands exercising the add-back branch
445 let mut x: u64 = 0x9e3779b97f4a7c15;
446 for _ in 0..300 {
447 let mut gen = |n: usize| {
448 let mut v = Vec::new();
449 for _ in 0..n {
450 x ^= x << 13;
451 x ^= x >> 7;
452 x ^= x << 17;
453 v.push(x as u32);
454 }
455 Int::from_parts(false, v)
456 };
457 let a = gen(9);
458 let b = gen(4);
459 if b.is_zero() {
460 continue;
461 }
462 let (q, r) = a.divrem(&b);
463 assert_eq!(q.mul(&b).add(&r), a);
464 assert!(r.cmp(&b) == Ordering::Less);
465 }
466 let a = Int::from_parts(false, vec![0, 0, 0x8000_0000, 0x7fff_ffff]);
467 let b = Int::from_parts(false, vec![1, 0, 0x8000_0000]);
468 let (q, r) = a.divrem(&b);
469 assert_eq!(q.mul(&b).add(&r), a);
470 }
471}