1use std::cmp::Ordering;
18use std::fmt;
19
20#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
23enum Sign {
24 Neg,
25 Zero,
26 Pos,
27}
28
29#[derive(Clone, PartialEq, Eq, Hash)]
31pub struct BigInt {
32 sign: Sign,
33 mag: Mag,
34}
35
36#[derive(Clone, PartialEq, Eq, Hash)]
44enum Mag {
45 Inline(u64),
46 Heap(Vec<u64>),
47}
48
49impl Mag {
50 fn from_vec(mut v: Vec<u64>) -> Mag {
52 while v.last() == Some(&0) {
53 v.pop();
54 }
55 match v.len() {
56 0 => Mag::Inline(0),
57 1 => Mag::Inline(v[0]),
58 _ => Mag::Heap(v),
59 }
60 }
61
62 fn limbs(&self) -> &[u64] {
64 match self {
65 Mag::Inline(0) => &[],
66 Mag::Inline(x) => std::slice::from_ref(x),
67 Mag::Heap(v) => v,
68 }
69 }
70
71 fn as_single(&self) -> Option<u64> {
74 match self {
75 Mag::Inline(x) => Some(*x),
76 Mag::Heap(_) => None,
77 }
78 }
79}
80
81fn normalize(mut mag: Vec<u64>) -> Vec<u64> {
85 while mag.last() == Some(&0) {
86 mag.pop();
87 }
88 mag
89}
90
91fn mag_cmp(a: &[u64], b: &[u64]) -> Ordering {
93 match a.len().cmp(&b.len()) {
94 Ordering::Equal => {
95 for i in (0..a.len()).rev() {
96 match a[i].cmp(&b[i]) {
97 Ordering::Equal => {}
98 other => return other,
99 }
100 }
101 Ordering::Equal
102 }
103 other => other,
104 }
105}
106
107fn mag_add(a: &[u64], b: &[u64]) -> Vec<u64> {
109 let mut out = Vec::with_capacity(a.len().max(b.len()) + 1);
110 let mut carry = 0u128;
111 for i in 0..a.len().max(b.len()) {
112 let av = *a.get(i).unwrap_or(&0) as u128;
113 let bv = *b.get(i).unwrap_or(&0) as u128;
114 let sum = av + bv + carry;
115 out.push(sum as u64);
116 carry = sum >> 64;
117 }
118 if carry != 0 {
119 out.push(carry as u64);
120 }
121 normalize(out)
122}
123
124fn mag_sub(a: &[u64], b: &[u64]) -> Vec<u64> {
126 debug_assert!(mag_cmp(a, b) != Ordering::Less, "mag_sub underflow");
127 let mut out = Vec::with_capacity(a.len());
128 let mut borrow = 0i128;
129 for i in 0..a.len() {
130 let av = a[i] as i128;
131 let bv = *b.get(i).unwrap_or(&0) as i128;
132 let mut diff = av - bv - borrow;
133 if diff < 0 {
134 diff += 1i128 << 64;
135 borrow = 1;
136 } else {
137 borrow = 0;
138 }
139 out.push(diff as u64);
140 }
141 debug_assert_eq!(borrow, 0, "mag_sub left a borrow");
142 normalize(out)
143}
144
145const KARATSUBA_THRESHOLD: usize = 32;
149
150fn mag_mul(a: &[u64], b: &[u64]) -> Vec<u64> {
152 if a.is_empty() || b.is_empty() {
153 return Vec::new();
154 }
155 if a.len().min(b.len()) < KARATSUBA_THRESHOLD {
156 return mag_mul_schoolbook(a, b);
157 }
158 mag_mul_karatsuba(a, b)
159}
160
161fn mag_mul_schoolbook(a: &[u64], b: &[u64]) -> Vec<u64> {
163 let mut out = vec![0u64; a.len() + b.len()];
164 for (i, &av) in a.iter().enumerate() {
165 let mut carry = 0u128;
166 for (j, &bv) in b.iter().enumerate() {
167 let cur = out[i + j] as u128 + (av as u128) * (bv as u128) + carry;
168 out[i + j] = cur as u64;
169 carry = cur >> 64;
170 }
171 out[i + b.len()] += carry as u64;
172 }
173 normalize(out)
174}
175
176fn mag_shl_limbs(a: &[u64], n: usize) -> Vec<u64> {
178 if a.is_empty() {
179 return Vec::new();
180 }
181 let mut out = Vec::with_capacity(a.len() + n);
182 out.resize(n, 0);
183 out.extend_from_slice(a);
184 out
185}
186
187fn mag_mul_karatsuba(a: &[u64], b: &[u64]) -> Vec<u64> {
194 let m = a.len().min(b.len()) / 2; let (a_lo, a_hi) = a.split_at(m);
196 let (b_lo, b_hi) = b.split_at(m);
197
198 let z0 = mag_mul(a_lo, b_lo);
199 let z2 = mag_mul(a_hi, b_hi);
200 let a_sum = mag_add(a_lo, a_hi);
201 let b_sum = mag_add(b_lo, b_hi);
202 let z1 = mag_sub(&mag_sub(&mag_mul(&a_sum, &b_sum), &z0), &z2);
203
204 let mut out = z0;
205 out = mag_add(&out, &mag_shl_limbs(&z1, m));
206 out = mag_add(&out, &mag_shl_limbs(&z2, 2 * m));
207 normalize(out)
208}
209
210#[cfg(test)]
212fn mag_shl1(a: &[u64], bit: u64) -> Vec<u64> {
213 let mut out = Vec::with_capacity(a.len() + 1);
214 let mut carry = bit & 1;
215 for &limb in a {
216 out.push((limb << 1) | carry);
217 carry = limb >> 63;
218 }
219 if carry != 0 {
220 out.push(carry);
221 }
222 normalize(out)
223}
224
225#[cfg(test)]
227fn mag_divrem_bitwise(a: &[u64], b: &[u64]) -> (Vec<u64>, Vec<u64>) {
228 if mag_cmp(a, b) == Ordering::Less {
229 return (Vec::new(), a.to_vec());
230 }
231 let nbits = a.len() * 64;
232 let mut q = vec![0u64; a.len()];
233 let mut r: Vec<u64> = Vec::new();
234 for i in (0..nbits).rev() {
235 let bit = (a[i / 64] >> (i % 64)) & 1;
236 r = mag_shl1(&r, bit);
237 if mag_cmp(&r, b) != Ordering::Less {
238 r = mag_sub(&r, b);
239 q[i / 64] |= 1u64 << (i % 64);
240 }
241 }
242 (normalize(q), normalize(r))
243}
244
245fn mag_shl_bits(a: &[u64], bits: u64) -> Vec<u64> {
247 if a.is_empty() {
248 return Vec::new();
249 }
250 let (words, sh) = ((bits / 64) as usize, (bits % 64) as u32);
251 let mut out = Vec::with_capacity(a.len() + words + 1);
252 out.resize(words, 0);
253 if sh == 0 {
254 out.extend_from_slice(a);
255 } else {
256 let mut carry = 0u64;
257 for &limb in a {
258 out.push((limb << sh) | carry);
259 carry = limb >> (64 - sh);
260 }
261 if carry != 0 {
262 out.push(carry);
263 }
264 }
265 out
266}
267
268fn scale_by_power_of_two(mut x: f64, mut k: u64) -> f64 {
272 const STEP: u64 = 1000;
273 let power = |e: u64| f64::from_bits((1023 + e) << 52);
274 while k > STEP && x.is_finite() {
275 x *= power(STEP);
276 k -= STEP;
277 }
278 if x.is_finite() {
279 x * power(k)
280 } else {
281 x
282 }
283}
284
285fn mag_shr_bits(a: &[u64], bits: u64) -> Vec<u64> {
287 let words = bits / 64;
288 if words >= a.len() as u64 {
289 return Vec::new();
290 }
291 let a = &a[words as usize..];
292 let sh = (bits % 64) as u32;
293 if sh == 0 {
294 return a.to_vec();
295 }
296 let mut out = Vec::with_capacity(a.len());
297 for i in 0..a.len() {
298 let hi = a.get(i + 1).map_or(0, |h| h << (64 - sh));
299 out.push((a[i] >> sh) | hi);
300 }
301 normalize(out)
302}
303
304fn mag_divrem(a: &[u64], b: &[u64]) -> (Vec<u64>, Vec<u64>) {
309 debug_assert!(!b.is_empty(), "division by zero magnitude");
310 if mag_cmp(a, b) == Ordering::Less {
311 return (Vec::new(), a.to_vec());
312 }
313 if b.len() == 1 {
314 let d = b[0] as u128;
315 let mut q = vec![0u64; a.len()];
316 let mut rem: u128 = 0;
317 for i in (0..a.len()).rev() {
318 let cur = (rem << 64) | a[i] as u128;
319 q[i] = (cur / d) as u64;
320 rem = cur % d;
321 }
322 return (normalize(q), normalize(vec![rem as u64]));
323 }
324 let shift = b[b.len() - 1].leading_zeros() as u64;
325 let v = mag_shl_bits(b, shift);
326 let mut u = mag_shl_bits(a, shift);
327 u.resize(a.len() + 1, 0);
328 let n = v.len();
329 let m = u.len() - n - 1;
330 let mut q = vec![0u64; m + 1];
331 let (vtop, vnext) = (v[n - 1] as u128, v[n - 2] as u128);
332 const B: u128 = 1 << 64;
333 for j in (0..=m).rev() {
334 let num = ((u[j + n] as u128) << 64) | u[j + n - 1] as u128;
335 let mut qhat = num / vtop;
336 let mut rhat = num % vtop;
337 while qhat >= B || qhat * vnext > ((rhat << 64) | u[j + n - 2] as u128) {
338 qhat -= 1;
339 rhat += vtop;
340 if rhat >= B {
341 break;
342 }
343 }
344 let mut borrow: i128 = 0;
345 let mut carry: u128 = 0;
346 for i in 0..n {
347 let p = qhat * v[i] as u128 + carry;
348 carry = p >> 64;
349 let t = u[i + j] as i128 - (p as u64) as i128 + borrow;
350 u[i + j] = t as u64;
351 borrow = t >> 64;
352 }
353 let t = u[j + n] as i128 - carry as i128 + borrow;
354 u[j + n] = t as u64;
355 if t < 0 {
356 qhat -= 1;
357 let mut c: u128 = 0;
358 for i in 0..n {
359 let s = u[i + j] as u128 + v[i] as u128 + c;
360 u[i + j] = s as u64;
361 c = s >> 64;
362 }
363 u[j + n] = u[j + n].wrapping_add(c as u64);
364 }
365 q[j] = qhat as u64;
366 }
367 u.truncate(n);
368 (normalize(q), mag_shr_bits(&normalize(u), shift))
369}
370
371impl BigInt {
372 pub fn zero() -> Self {
374 BigInt {
375 sign: Sign::Zero,
376 mag: Mag::Inline(0),
377 }
378 }
379
380 fn from_sign_mag(neg: bool, mag: Vec<u64>) -> Self {
383 let mag = Mag::from_vec(mag);
384 let sign = if mag.limbs().is_empty() {
385 Sign::Zero
386 } else if neg {
387 Sign::Neg
388 } else {
389 Sign::Pos
390 };
391 BigInt { sign, mag }
392 }
393
394 fn from_sign_mag_u128(neg: bool, m: u128) -> Self {
397 if m == 0 {
398 return Self::zero();
399 }
400 let lo = m as u64;
401 let hi = (m >> 64) as u64;
402 let mag = if hi == 0 {
403 Mag::Inline(lo)
404 } else {
405 Mag::Heap(vec![lo, hi])
406 };
407 BigInt {
408 sign: if neg { Sign::Neg } else { Sign::Pos },
409 mag,
410 }
411 }
412
413 pub fn from_i64(x: i64) -> Self {
415 Self::from_sign_mag_u128(x < 0, (x as i128).unsigned_abs())
416 }
417
418 pub fn from_u64(x: u64) -> Self {
420 Self::from_sign_mag_u128(false, x as u128)
421 }
422
423 pub fn clone_payload_bytes(&self) -> usize {
428 match &self.mag {
429 Mag::Inline(_) => 0,
430 Mag::Heap(limbs) => limbs.len() * std::mem::size_of::<u64>(),
431 }
432 }
433
434 pub fn to_i64(&self) -> Option<i64> {
437 let m = self.mag.as_single()? as i128;
438 let v = if self.sign == Sign::Neg { -m } else { m };
439 if (i64::MIN as i128..=i64::MAX as i128).contains(&v) {
440 Some(v as i64)
441 } else {
442 None
443 }
444 }
445
446 pub fn to_u64(&self) -> Option<u64> {
448 match self.sign {
449 Sign::Neg => None,
450 _ => self.mag.as_single(),
451 }
452 }
453
454 pub fn wrapping_u64(&self) -> u64 {
456 let low = self.mag.limbs().first().copied().unwrap_or(0);
457 if self.sign == Sign::Neg {
458 low.wrapping_neg()
459 } else {
460 low
461 }
462 }
463
464 pub fn bit_len(&self) -> u64 {
466 let l = self.mag.limbs();
467 match l.last() {
468 None => 0,
469 Some(top) => (l.len() as u64 - 1) * 64 + (64 - top.leading_zeros() as u64),
470 }
471 }
472
473 pub fn gcd(&self, other: &Self) -> Self {
475 if let (Some(a), Some(b)) = (self.mag.as_single(), other.mag.as_single()) {
476 let (mut a, mut b) = (a, b);
477 while b != 0 {
478 let t = a % b;
479 a = b;
480 b = t;
481 }
482 return BigInt::from_u64(a);
483 }
484 bigint_gcd(self, other)
485 }
486
487 pub fn shl_bits(&self, bits: u64) -> Self {
489 Self::from_sign_mag(self.sign == Sign::Neg, mag_shl_bits(self.mag.limbs(), bits))
490 }
491
492 pub fn shr_bits(&self, bits: u64) -> Option<Self> {
494 if self.sign == Sign::Neg {
495 return None;
496 }
497 Some(Self::from_sign_mag(
498 false,
499 mag_shr_bits(self.mag.limbs(), bits),
500 ))
501 }
502
503 fn natural_bitwise(&self, other: &Self, op: impl Fn(u64, u64) -> u64) -> Option<Self> {
504 if self.sign == Sign::Neg || other.sign == Sign::Neg {
505 return None;
506 }
507 let (a, b) = (self.mag.limbs(), other.mag.limbs());
508 let out = (0..a.len().max(b.len()))
509 .map(|i| op(*a.get(i).unwrap_or(&0), *b.get(i).unwrap_or(&0)))
510 .collect();
511 Some(Self::from_sign_mag(false, out))
512 }
513
514 pub fn bitand_natural(&self, other: &Self) -> Option<Self> {
516 self.natural_bitwise(other, |x, y| x & y)
517 }
518
519 pub fn bitor_natural(&self, other: &Self) -> Option<Self> {
521 self.natural_bitwise(other, |x, y| x | y)
522 }
523
524 pub fn bitxor_natural(&self, other: &Self) -> Option<Self> {
526 self.natural_bitwise(other, |x, y| x ^ y)
527 }
528
529 pub fn is_zero(&self) -> bool {
530 self.sign == Sign::Zero
531 }
532
533 pub fn is_odd(&self) -> bool {
535 self.mag.limbs().first().is_some_and(|limb| limb & 1 == 1)
536 }
537
538 pub fn to_f64(&self) -> f64 {
547 let limbs = self.mag.limbs();
548 let bits = self.bit_len();
549 let magnitude = if bits <= 64 {
550 limbs.first().copied().unwrap_or(0) as f64
551 } else {
552 let dropped = bits - 64;
553 let (word, shift) = ((dropped / 64) as usize, (dropped % 64) as u32);
554 let top = if shift == 0 {
555 limbs[word]
556 } else {
557 (limbs[word] >> shift) | (limbs[word + 1] << (64 - shift))
558 };
559 let sticky = limbs[..word].iter().any(|&l| l != 0)
560 || (shift != 0 && limbs[word] << (64 - shift) != 0);
561 scale_by_power_of_two((top | sticky as u64) as f64, dropped)
562 };
563 if self.sign == Sign::Neg {
564 -magnitude
565 } else {
566 magnitude
567 }
568 }
569
570 pub fn is_negative(&self) -> bool {
571 self.sign == Sign::Neg
572 }
573
574 pub fn is_positive(&self) -> bool {
575 self.sign == Sign::Pos
576 }
577
578 pub fn abs(&self) -> Self {
580 BigInt {
581 sign: if self.sign == Sign::Zero {
582 Sign::Zero
583 } else {
584 Sign::Pos
585 },
586 mag: self.mag.clone(),
587 }
588 }
589
590 pub fn negated(&self) -> Self {
592 let sign = match self.sign {
593 Sign::Neg => Sign::Pos,
594 Sign::Zero => Sign::Zero,
595 Sign::Pos => Sign::Neg,
596 };
597 BigInt {
598 sign,
599 mag: self.mag.clone(),
600 }
601 }
602
603 pub fn add(&self, other: &Self) -> Self {
605 if let (Some(a), Some(b)) = (self.mag.as_single(), other.mag.as_single()) {
608 let av = if self.sign == Sign::Neg {
609 -(a as i128)
610 } else {
611 a as i128
612 };
613 let bv = if other.sign == Sign::Neg {
614 -(b as i128)
615 } else {
616 b as i128
617 };
618 let sum = av + bv;
619 return Self::from_sign_mag_u128(sum < 0, sum.unsigned_abs());
620 }
621 match (self.sign, other.sign) {
622 (Sign::Zero, _) => other.clone(),
623 (_, Sign::Zero) => self.clone(),
624 (a, b) if a == b => {
626 Self::from_sign_mag(a == Sign::Neg, mag_add(self.mag.limbs(), other.mag.limbs()))
627 }
628 _ => match mag_cmp(self.mag.limbs(), other.mag.limbs()) {
631 Ordering::Equal => Self::zero(),
632 Ordering::Greater => Self::from_sign_mag(
633 self.sign == Sign::Neg,
634 mag_sub(self.mag.limbs(), other.mag.limbs()),
635 ),
636 Ordering::Less => Self::from_sign_mag(
637 other.sign == Sign::Neg,
638 mag_sub(other.mag.limbs(), self.mag.limbs()),
639 ),
640 },
641 }
642 }
643
644 pub fn sub(&self, other: &Self) -> Self {
646 self.add(&other.negated())
647 }
648
649 pub fn mul(&self, other: &Self) -> Self {
651 let neg = (self.sign == Sign::Neg) ^ (other.sign == Sign::Neg);
652 if let (Some(a), Some(b)) = (self.mag.as_single(), other.mag.as_single()) {
654 return Self::from_sign_mag_u128(neg, (a as u128) * (b as u128));
655 }
656 if self.is_zero() || other.is_zero() {
657 return Self::zero();
658 }
659 Self::from_sign_mag(neg, mag_mul(self.mag.limbs(), other.mag.limbs()))
660 }
661
662 pub fn mul_assign_i64(&mut self, rhs: i64) {
670 if rhs == 0 || self.is_zero() {
671 *self = Self::zero();
672 return;
673 }
674 if rhs < 0 {
675 self.sign = match self.sign {
676 Sign::Neg => Sign::Pos,
677 Sign::Pos => Sign::Neg,
678 Sign::Zero => Sign::Zero,
679 };
680 }
681 let m = (rhs as i128).unsigned_abs() as u64;
682 match &mut self.mag {
683 Mag::Inline(x) => {
684 let prod = (*x as u128) * (m as u128);
685 self.mag = if (prod >> 64) == 0 {
686 Mag::Inline(prod as u64)
687 } else {
688 Mag::Heap(vec![prod as u64, (prod >> 64) as u64])
689 };
690 }
691 Mag::Heap(v) => {
692 let mut carry: u64 = 0;
693 for limb in v.iter_mut() {
694 let prod = (*limb as u128) * (m as u128) + (carry as u128);
695 *limb = prod as u64;
696 carry = (prod >> 64) as u64;
697 }
698 if carry != 0 {
699 v.push(carry);
700 }
701 }
702 }
703 }
704
705 pub fn div_rem(&self, other: &Self) -> Option<(Self, Self)> {
710 if other.is_zero() {
711 return None;
712 }
713 let q_neg = (self.sign == Sign::Neg) ^ (other.sign == Sign::Neg);
714 if let (Some(a), Some(b)) = (self.mag.as_single(), other.mag.as_single()) {
717 return Some((
718 Self::from_sign_mag_u128(q_neg, (a / b) as u128),
719 Self::from_sign_mag_u128(self.sign == Sign::Neg, (a % b) as u128),
720 ));
721 }
722 if self.is_zero() {
723 return Some((Self::zero(), Self::zero()));
724 }
725 let (qm, rm) = mag_divrem(self.mag.limbs(), other.mag.limbs());
726 let q = Self::from_sign_mag(q_neg, qm);
727 let r = Self::from_sign_mag(self.sign == Sign::Neg, rm);
729 Some((q, r))
730 }
731
732 pub fn parse_decimal(s: &str) -> Option<Self> {
734 let bytes = s.as_bytes();
735 let (neg, digits) = match bytes.first() {
736 Some(b'-') => (true, &bytes[1..]),
737 Some(b'+') => (false, &bytes[1..]),
738 _ => (false, bytes),
739 };
740 if digits.is_empty() {
741 return None;
742 }
743 let ten = BigInt::from_u64(10);
744 let mut acc = BigInt::zero();
745 for &d in digits {
746 if !d.is_ascii_digit() {
747 return None;
748 }
749 acc = acc.mul(&ten).add(&BigInt::from_u64((d - b'0') as u64));
750 }
751 Some(if neg { acc.negated() } else { acc })
752 }
753
754 pub fn pow(&self, mut exp: u32) -> BigInt {
757 let mut result = BigInt::from_u64(1);
758 let mut base = self.clone();
759 while exp > 0 {
760 if exp & 1 == 1 {
761 result = result.mul(&base);
762 }
763 exp >>= 1;
764 if exp > 0 {
765 base = base.mul(&base);
766 }
767 }
768 result
769 }
770
771 pub fn to_le_bytes(&self) -> (bool, Vec<u8>) {
775 let limbs = self.mag.limbs();
776 let mut bytes = Vec::with_capacity(limbs.len() * 8);
777 for &limb in limbs {
778 bytes.extend_from_slice(&limb.to_le_bytes());
779 }
780 (self.sign == Sign::Neg, bytes)
781 }
782
783 pub fn from_le_bytes(negative: bool, bytes: &[u8]) -> Self {
786 let mut mag = Vec::with_capacity(bytes.len().div_ceil(8));
787 for chunk in bytes.chunks(8) {
788 let mut limb = [0u8; 8];
789 limb[..chunk.len()].copy_from_slice(chunk);
790 mag.push(u64::from_le_bytes(limb));
791 }
792 Self::from_sign_mag(negative, mag)
793 }
794}
795
796impl Ord for BigInt {
797 fn cmp(&self, other: &Self) -> Ordering {
798 let rank = |s: Sign| match s {
800 Sign::Neg => -1i8,
801 Sign::Zero => 0,
802 Sign::Pos => 1,
803 };
804 match rank(self.sign).cmp(&rank(other.sign)) {
805 Ordering::Equal => match self.sign {
806 Sign::Zero => Ordering::Equal,
807 Sign::Pos => mag_cmp(self.mag.limbs(), other.mag.limbs()),
808 Sign::Neg => mag_cmp(other.mag.limbs(), self.mag.limbs()),
809 },
810 other => other,
811 }
812 }
813}
814
815impl PartialOrd for BigInt {
816 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
817 Some(self.cmp(other))
818 }
819}
820
821impl fmt::Display for BigInt {
822 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
823 if self.is_zero() {
824 return write!(f, "0");
825 }
826 const TEN19: u64 = 10_000_000_000_000_000_000;
829 let ten19 = BigInt::from_u64(TEN19);
830 let mut chunks: Vec<u64> = Vec::new();
831 let mut cur = self.abs();
832 while !cur.is_zero() {
833 let (q, r) = cur.div_rem(&ten19).expect("10^19 is nonzero");
834 chunks.push(r.mag.limbs().first().copied().unwrap_or(0));
837 cur = q;
838 }
839 if self.is_negative() {
840 write!(f, "-")?;
841 }
842 write!(f, "{}", chunks.last().unwrap())?;
844 for &chunk in chunks.iter().rev().skip(1) {
845 write!(f, "{chunk:019}")?;
846 }
847 Ok(())
848 }
849}
850
851impl fmt::Debug for BigInt {
852 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
853 write!(f, "BigInt({self})")
854 }
855}
856
857impl From<i64> for BigInt {
858 fn from(x: i64) -> Self {
859 BigInt::from_i64(x)
860 }
861}
862
863fn bigint_gcd(a: &BigInt, b: &BigInt) -> BigInt {
869 let mut a = a.abs();
870 let mut b = b.abs();
871 while !b.is_zero() {
872 let (_q, r) = a.div_rem(&b).expect("b is nonzero inside the loop");
873 a = b;
874 b = r;
875 }
876 a
877}
878
879#[derive(Clone, PartialEq, Eq, Hash)]
889pub struct Rational {
890 num: BigInt,
892 den: BigInt,
896}
897
898impl Rational {
899 pub fn new(num: BigInt, den: BigInt) -> Option<Rational> {
903 if den.is_zero() {
904 return None;
905 }
906 let (mut num, mut den) = (num, den);
907 if den.is_negative() {
908 num = num.negated();
909 den = den.negated();
910 }
911 if num.is_zero() {
912 return Some(Rational {
913 num: BigInt::zero(),
914 den: BigInt::from_i64(1),
915 });
916 }
917 let g = bigint_gcd(&num, &den);
918 let (num, _) = num.div_rem(&g).expect("gcd divides the numerator exactly");
919 let (den, _) = den
920 .div_rem(&g)
921 .expect("gcd divides the denominator exactly");
922 Some(Rational { num, den })
923 }
924
925 pub fn from_bigint(n: BigInt) -> Rational {
927 Rational {
928 num: n,
929 den: BigInt::from_i64(1),
930 }
931 }
932
933 pub fn from_i64(x: i64) -> Rational {
934 Rational::from_bigint(BigInt::from_i64(x))
935 }
936
937 pub fn from_ratio_i64(n: i64, d: i64) -> Option<Rational> {
939 Rational::new(BigInt::from_i64(n), BigInt::from_i64(d))
940 }
941
942 pub fn zero() -> Rational {
943 Rational {
944 num: BigInt::zero(),
945 den: BigInt::from_i64(1),
946 }
947 }
948
949 pub fn one() -> Rational {
950 Rational::from_i64(1)
951 }
952
953 pub fn numerator(&self) -> &BigInt {
954 &self.num
955 }
956
957 pub fn denominator(&self) -> &BigInt {
958 &self.den
959 }
960
961 pub fn is_integer(&self) -> bool {
963 self.den == BigInt::from_i64(1)
964 }
965
966 pub fn is_zero(&self) -> bool {
967 self.num.is_zero()
968 }
969
970 pub fn is_negative(&self) -> bool {
971 self.num.is_negative()
972 }
973
974 pub fn is_positive(&self) -> bool {
975 self.num.is_positive()
976 }
977
978 pub fn to_bigint(&self) -> Option<BigInt> {
981 if self.is_integer() {
982 Some(self.num.clone())
983 } else {
984 None
985 }
986 }
987
988 pub fn to_i64(&self) -> Option<i64> {
990 if self.is_integer() {
991 self.num.to_i64()
992 } else {
993 None
994 }
995 }
996
997 pub fn to_f64(&self) -> f64 {
1000 self.num.to_f64() / self.den.to_f64()
1001 }
1002
1003 pub fn floor(&self) -> BigInt {
1006 let (q, r) = self.num.div_rem(&self.den).expect("denominator is nonzero");
1007 if self.num.is_negative() && !r.is_zero() {
1008 q.sub(&BigInt::from_i64(1))
1009 } else {
1010 q
1011 }
1012 }
1013
1014 pub fn ceil(&self) -> BigInt {
1017 let (q, r) = self.num.div_rem(&self.den).expect("denominator is nonzero");
1018 if !self.num.is_negative() && !r.is_zero() {
1019 q.add(&BigInt::from_i64(1))
1020 } else {
1021 q
1022 }
1023 }
1024
1025 pub fn round(&self) -> BigInt {
1028 let two = BigInt::from_i64(2);
1029 let numerator = self.num.abs().mul(&two).add(&self.den);
1030 let denominator = self.den.mul(&two);
1031 let (mag, _) = numerator
1032 .div_rem(&denominator)
1033 .expect("denominator is nonzero");
1034 if self.num.is_negative() {
1035 mag.negated()
1036 } else {
1037 mag
1038 }
1039 }
1040
1041 pub fn negated(&self) -> Rational {
1042 Rational {
1043 num: self.num.negated(),
1044 den: self.den.clone(),
1045 }
1046 }
1047
1048 pub fn abs(&self) -> Rational {
1049 Rational {
1050 num: self.num.abs(),
1051 den: self.den.clone(),
1052 }
1053 }
1054
1055 pub fn recip(&self) -> Option<Rational> {
1057 Rational::new(self.den.clone(), self.num.clone())
1058 }
1059
1060 pub fn add(&self, other: &Rational) -> Rational {
1061 let num = self.num.mul(&other.den).add(&other.num.mul(&self.den));
1063 let den = self.den.mul(&other.den);
1064 Rational::new(num, den).expect("product of positive denominators is nonzero")
1065 }
1066
1067 pub fn sub(&self, other: &Rational) -> Rational {
1068 let num = self.num.mul(&other.den).sub(&other.num.mul(&self.den));
1069 let den = self.den.mul(&other.den);
1070 Rational::new(num, den).expect("product of positive denominators is nonzero")
1071 }
1072
1073 pub fn mul(&self, other: &Rational) -> Rational {
1074 let num = self.num.mul(&other.num);
1075 let den = self.den.mul(&other.den);
1076 Rational::new(num, den).expect("product of positive denominators is nonzero")
1077 }
1078
1079 pub fn div(&self, other: &Rational) -> Option<Rational> {
1081 let num = self.num.mul(&other.den);
1083 let den = self.den.mul(&other.num);
1084 Rational::new(num, den)
1085 }
1086
1087 pub fn pow(&self, exp: i32) -> Option<Rational> {
1090 if exp >= 0 {
1091 let k = exp as u32;
1092 Some(
1093 Rational::new(self.num.pow(k), self.den.pow(k))
1094 .expect("denominator^k stays positive"),
1095 )
1096 } else {
1097 if self.num.is_zero() {
1098 return None;
1099 }
1100 let k = exp.unsigned_abs();
1101 Rational::new(self.den.pow(k), self.num.pow(k))
1103 }
1104 }
1105
1106 pub fn parse(s: &str) -> Option<Rational> {
1109 let s = s.trim();
1110 if let Some((n, d)) = s.split_once('/') {
1111 let num = BigInt::parse_decimal(n.trim())?;
1112 let den = BigInt::parse_decimal(d.trim())?;
1113 Rational::new(num, den)
1114 } else {
1115 Some(Rational::from_bigint(BigInt::parse_decimal(s)?))
1116 }
1117 }
1118}
1119
1120impl Ord for Rational {
1121 fn cmp(&self, other: &Self) -> Ordering {
1122 self.num.mul(&other.den).cmp(&other.num.mul(&self.den))
1124 }
1125}
1126
1127impl PartialOrd for Rational {
1128 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1129 Some(self.cmp(other))
1130 }
1131}
1132
1133impl fmt::Display for Rational {
1134 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1135 if self.is_integer() {
1136 write!(f, "{}", self.num)
1137 } else {
1138 write!(f, "{}/{}", self.num, self.den)
1139 }
1140 }
1141}
1142
1143impl fmt::Debug for Rational {
1144 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1145 write!(f, "Rational({}/{})", self.num, self.den)
1146 }
1147}
1148
1149impl From<i64> for Rational {
1150 fn from(x: i64) -> Self {
1151 Rational::from_i64(x)
1152 }
1153}
1154
1155impl From<BigInt> for Rational {
1156 fn from(x: BigInt) -> Self {
1157 Rational::from_bigint(x)
1158 }
1159}
1160
1161#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
1169pub enum RoundingMode {
1170 Down,
1172 Up,
1174 Floor,
1176 Ceiling,
1178 HalfUp,
1180 HalfDown,
1182 HalfEven,
1184}
1185
1186fn ten_pow(k: u32) -> BigInt {
1188 BigInt::from_u64(10).pow(k)
1189}
1190
1191fn round_rational_to_bigint(x: &Rational, mode: RoundingMode) -> BigInt {
1195 let num = x.numerator();
1196 let den = x.denominator(); let (q, r) = num.div_rem(den).expect("rational denominator is nonzero");
1198 if r.is_zero() {
1199 return q; }
1201 let neg = num.is_negative();
1202 let twice = r.abs().mul(&BigInt::from_i64(2));
1204 let half = twice.cmp(den);
1205 let away = match mode {
1206 RoundingMode::Down => false,
1207 RoundingMode::Up => true,
1208 RoundingMode::Floor => neg,
1209 RoundingMode::Ceiling => !neg,
1210 RoundingMode::HalfUp => half != Ordering::Less,
1211 RoundingMode::HalfDown => half == Ordering::Greater,
1212 RoundingMode::HalfEven => {
1213 half == Ordering::Greater || (half == Ordering::Equal && q.is_odd())
1214 }
1215 };
1216 if away {
1217 if neg {
1219 q.sub(&BigInt::from_i64(1))
1220 } else {
1221 q.add(&BigInt::from_i64(1))
1222 }
1223 } else {
1224 q
1225 }
1226}
1227
1228#[derive(Clone)]
1239pub struct Decimal {
1240 coeff: BigInt,
1241 scale: u32,
1243}
1244
1245impl Decimal {
1246 pub fn from_bigint(coeff: BigInt) -> Decimal {
1248 Decimal { coeff, scale: 0 }
1249 }
1250
1251 pub fn from_i64(x: i64) -> Decimal {
1252 Decimal::from_bigint(BigInt::from_i64(x))
1253 }
1254
1255 pub fn from_coeff_scale(coeff: BigInt, scale: u32) -> Decimal {
1257 Decimal { coeff, scale }
1258 }
1259
1260 pub fn zero() -> Decimal {
1261 Decimal::from_i64(0)
1262 }
1263
1264 pub fn one() -> Decimal {
1265 Decimal::from_i64(1)
1266 }
1267
1268 pub fn scale(&self) -> u32 {
1269 self.scale
1270 }
1271
1272 pub fn coefficient(&self) -> &BigInt {
1273 &self.coeff
1274 }
1275
1276 pub fn is_zero(&self) -> bool {
1277 self.coeff.is_zero()
1278 }
1279
1280 pub fn is_negative(&self) -> bool {
1281 self.coeff.is_negative()
1282 }
1283
1284 pub fn negated(&self) -> Decimal {
1285 Decimal {
1286 coeff: self.coeff.negated(),
1287 scale: self.scale,
1288 }
1289 }
1290
1291 pub fn abs(&self) -> Decimal {
1292 Decimal {
1293 coeff: self.coeff.abs(),
1294 scale: self.scale,
1295 }
1296 }
1297
1298 pub fn to_rational(&self) -> Rational {
1301 Rational::new(self.coeff.clone(), ten_pow(self.scale)).expect("10^scale is nonzero")
1302 }
1303
1304 pub fn from_rational(value: &Rational, scale: u32, mode: RoundingMode) -> Decimal {
1306 let scaled = value.mul(&Rational::from_bigint(ten_pow(scale)));
1307 Decimal {
1308 coeff: round_rational_to_bigint(&scaled, mode),
1309 scale,
1310 }
1311 }
1312
1313 pub fn rescale(&self, scale: u32, mode: RoundingMode) -> Decimal {
1316 if scale >= self.scale {
1317 Decimal {
1318 coeff: self.coeff.mul(&ten_pow(scale - self.scale)),
1319 scale,
1320 }
1321 } else {
1322 Decimal::from_rational(&self.to_rational(), scale, mode)
1323 }
1324 }
1325
1326 fn aligned(&self, other: &Decimal) -> (BigInt, BigInt, u32) {
1328 let s = self.scale.max(other.scale);
1329 let a = self.coeff.mul(&ten_pow(s - self.scale));
1330 let b = other.coeff.mul(&ten_pow(s - other.scale));
1331 (a, b, s)
1332 }
1333
1334 pub fn add(&self, other: &Decimal) -> Decimal {
1335 let (a, b, s) = self.aligned(other);
1336 Decimal {
1337 coeff: a.add(&b),
1338 scale: s,
1339 }
1340 }
1341
1342 pub fn sub(&self, other: &Decimal) -> Decimal {
1343 let (a, b, s) = self.aligned(other);
1344 Decimal {
1345 coeff: a.sub(&b),
1346 scale: s,
1347 }
1348 }
1349
1350 pub fn mul(&self, other: &Decimal) -> Decimal {
1352 Decimal {
1353 coeff: self.coeff.mul(&other.coeff),
1354 scale: self.scale + other.scale,
1355 }
1356 }
1357
1358 pub fn div(&self, other: &Decimal, scale: u32, mode: RoundingMode) -> Option<Decimal> {
1361 let q = self.to_rational().div(&other.to_rational())?;
1362 Some(Decimal::from_rational(&q, scale, mode))
1363 }
1364
1365 fn normalized(&self) -> (BigInt, u32) {
1368 if self.coeff.is_zero() {
1369 return (BigInt::zero(), 0);
1370 }
1371 let ten = BigInt::from_u64(10);
1372 let mut c = self.coeff.clone();
1373 let mut s = self.scale;
1374 while s > 0 {
1375 let (q, r) = c.div_rem(&ten).expect("ten is nonzero");
1376 if !r.is_zero() {
1377 break;
1378 }
1379 c = q;
1380 s -= 1;
1381 }
1382 (c, s)
1383 }
1384
1385 pub fn to_le_bytes(&self) -> (bool, Vec<u8>, u32) {
1388 let (neg, bytes) = self.coeff.to_le_bytes();
1389 (neg, bytes, self.scale)
1390 }
1391
1392 pub fn from_le_bytes(negative: bool, bytes: &[u8], scale: u32) -> Decimal {
1393 Decimal {
1394 coeff: BigInt::from_le_bytes(negative, bytes),
1395 scale,
1396 }
1397 }
1398
1399 pub fn parse(s: &str) -> Option<Decimal> {
1403 let s = s.trim();
1404 let (neg, body) = match s.as_bytes().first() {
1405 Some(b'-') => (true, &s[1..]),
1406 Some(b'+') => (false, &s[1..]),
1407 _ => (false, s),
1408 };
1409 if body.is_empty() {
1410 return None;
1411 }
1412 let (int_part, frac_part) = match body.split_once('.') {
1413 Some((i, f)) => (i, f),
1414 None => (body, ""),
1415 };
1416 if int_part.is_empty() && frac_part.is_empty() {
1417 return None; }
1419 if !int_part.bytes().all(|c| c.is_ascii_digit())
1420 || !frac_part.bytes().all(|c| c.is_ascii_digit())
1421 {
1422 return None;
1423 }
1424 let digits = format!("{int_part}{frac_part}");
1425 let mag = if digits.is_empty() {
1426 BigInt::zero()
1427 } else {
1428 BigInt::parse_decimal(&digits)?
1429 };
1430 let coeff = if neg { mag.negated() } else { mag };
1431 Some(Decimal {
1432 coeff,
1433 scale: frac_part.len() as u32,
1434 })
1435 }
1436}
1437
1438impl PartialEq for Decimal {
1439 fn eq(&self, other: &Self) -> bool {
1440 self.normalized() == other.normalized()
1441 }
1442}
1443
1444impl Eq for Decimal {}
1445
1446impl std::hash::Hash for Decimal {
1447 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1448 self.normalized().hash(state);
1449 }
1450}
1451
1452impl Ord for Decimal {
1453 fn cmp(&self, other: &Self) -> Ordering {
1454 self.to_rational().cmp(&other.to_rational())
1456 }
1457}
1458
1459impl PartialOrd for Decimal {
1460 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1461 Some(self.cmp(other))
1462 }
1463}
1464
1465impl fmt::Display for Decimal {
1466 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1467 if self.scale == 0 {
1468 return write!(f, "{}", self.coeff);
1469 }
1470 let neg = self.coeff.is_negative();
1471 let mut digits = self.coeff.abs().to_string();
1472 let scale = self.scale as usize;
1473 if digits.len() <= scale {
1474 digits = format!("{}{}", "0".repeat(scale + 1 - digits.len()), digits);
1476 }
1477 let point = digits.len() - scale;
1478 if neg {
1479 write!(f, "-")?;
1480 }
1481 write!(f, "{}.{}", &digits[..point], &digits[point..])
1482 }
1483}
1484
1485impl fmt::Debug for Decimal {
1486 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1487 write!(f, "Decimal({self})")
1488 }
1489}
1490
1491impl From<i64> for Decimal {
1492 fn from(x: i64) -> Self {
1493 Decimal::from_i64(x)
1494 }
1495}
1496
1497impl From<BigInt> for Decimal {
1498 fn from(x: BigInt) -> Self {
1499 Decimal::from_bigint(x)
1500 }
1501}
1502
1503#[derive(Clone, PartialEq, Eq, Hash)]
1515pub struct Complex {
1516 re: Rational,
1517 im: Rational,
1518}
1519
1520impl Complex {
1521 pub fn new(re: Rational, im: Rational) -> Complex {
1522 Complex { re, im }
1523 }
1524
1525 pub fn from_rational(re: Rational) -> Complex {
1527 Complex {
1528 re,
1529 im: Rational::zero(),
1530 }
1531 }
1532
1533 pub fn from_i64(x: i64) -> Complex {
1534 Complex::from_rational(Rational::from_i64(x))
1535 }
1536
1537 pub fn zero() -> Complex {
1538 Complex {
1539 re: Rational::zero(),
1540 im: Rational::zero(),
1541 }
1542 }
1543
1544 pub fn one() -> Complex {
1545 Complex::from_i64(1)
1546 }
1547
1548 pub fn i() -> Complex {
1550 Complex {
1551 re: Rational::zero(),
1552 im: Rational::one(),
1553 }
1554 }
1555
1556 pub fn re(&self) -> &Rational {
1557 &self.re
1558 }
1559
1560 pub fn im(&self) -> &Rational {
1561 &self.im
1562 }
1563
1564 pub fn is_zero(&self) -> bool {
1565 self.re.is_zero() && self.im.is_zero()
1566 }
1567
1568 pub fn is_real(&self) -> bool {
1570 self.im.is_zero()
1571 }
1572
1573 pub fn conjugate(&self) -> Complex {
1575 Complex {
1576 re: self.re.clone(),
1577 im: self.im.negated(),
1578 }
1579 }
1580
1581 pub fn norm_sqr(&self) -> Rational {
1583 self.re.mul(&self.re).add(&self.im.mul(&self.im))
1584 }
1585
1586 pub fn abs_f64(&self) -> f64 {
1589 self.norm_sqr().to_f64().sqrt()
1590 }
1591
1592 pub fn negated(&self) -> Complex {
1593 Complex {
1594 re: self.re.negated(),
1595 im: self.im.negated(),
1596 }
1597 }
1598
1599 pub fn add(&self, other: &Complex) -> Complex {
1600 Complex {
1601 re: self.re.add(&other.re),
1602 im: self.im.add(&other.im),
1603 }
1604 }
1605
1606 pub fn sub(&self, other: &Complex) -> Complex {
1607 Complex {
1608 re: self.re.sub(&other.re),
1609 im: self.im.sub(&other.im),
1610 }
1611 }
1612
1613 pub fn mul(&self, other: &Complex) -> Complex {
1615 let (a, b, c, d) = (&self.re, &self.im, &other.re, &other.im);
1616 Complex {
1617 re: a.mul(c).sub(&b.mul(d)),
1618 im: a.mul(d).add(&b.mul(c)),
1619 }
1620 }
1621
1622 pub fn recip(&self) -> Option<Complex> {
1624 let n = self.norm_sqr();
1625 if n.is_zero() {
1626 return None;
1627 }
1628 let inv = n.recip().expect("norm is nonzero here");
1629 Some(Complex {
1630 re: self.re.mul(&inv),
1631 im: self.im.negated().mul(&inv),
1632 })
1633 }
1634
1635 pub fn div(&self, other: &Complex) -> Option<Complex> {
1637 Some(self.mul(&other.recip()?))
1638 }
1639
1640 pub fn pow(&self, exp: i32) -> Option<Complex> {
1643 if exp < 0 {
1644 return self.recip()?.pow(-exp);
1645 }
1646 let mut result = Complex::one();
1647 let mut base = self.clone();
1648 let mut e = exp as u32;
1649 while e > 0 {
1650 if e & 1 == 1 {
1651 result = result.mul(&base);
1652 }
1653 e >>= 1;
1654 if e > 0 {
1655 base = base.mul(&base);
1656 }
1657 }
1658 Some(result)
1659 }
1660
1661 pub fn parse(s: &str) -> Option<Complex> {
1664 let s = s.trim();
1665 if s.is_empty() {
1666 return None;
1667 }
1668 let bytes = s.as_bytes();
1669 if bytes[bytes.len() - 1] != b'i' {
1670 return Some(Complex::from_rational(Rational::parse(s)?));
1672 }
1673 let body = &s[..s.len() - 1]; let split = body
1676 .bytes()
1677 .enumerate()
1678 .rev()
1679 .find(|&(i, c)| i > 0 && (c == b'+' || c == b'-'))
1680 .map(|(i, _)| i);
1681 let (real_str, imag_str) = match split {
1682 Some(i) => (&body[..i], &body[i..]),
1683 None => ("", body),
1684 };
1685 let re = if real_str.is_empty() {
1686 Rational::zero()
1687 } else {
1688 Rational::parse(real_str)?
1689 };
1690 let im = match imag_str {
1691 "" | "+" => Rational::one(),
1692 "-" => Rational::from_i64(-1),
1693 other => Rational::parse(other)?,
1694 };
1695 Some(Complex { re, im })
1696 }
1697}
1698
1699impl fmt::Display for Complex {
1700 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1701 if self.im.is_zero() {
1702 return write!(f, "{}", self.re);
1703 }
1704 let mag = self.im.abs();
1705 let unit = mag == Rational::one(); if self.re.is_zero() {
1707 return if self.im.is_negative() {
1709 if unit {
1710 write!(f, "-i")
1711 } else {
1712 write!(f, "-{mag}i")
1713 }
1714 } else if unit {
1715 write!(f, "i")
1716 } else {
1717 write!(f, "{mag}i")
1718 };
1719 }
1720 let sign = if self.im.is_negative() { "-" } else { "+" };
1721 if unit {
1722 write!(f, "{}{}i", self.re, sign)
1723 } else {
1724 write!(f, "{}{}{}i", self.re, sign, mag)
1725 }
1726 }
1727}
1728
1729#[derive(Clone, Copy, PartialEq, Debug)]
1742pub struct ComplexF {
1743 re: f64,
1744 im: f64,
1745}
1746
1747impl ComplexF {
1748 pub fn new(re: f64, im: f64) -> ComplexF {
1749 ComplexF { re, im }
1750 }
1751 pub fn from_f64(re: f64) -> ComplexF {
1753 ComplexF { re, im: 0.0 }
1754 }
1755 pub fn re(&self) -> f64 {
1756 self.re
1757 }
1758 pub fn im(&self) -> f64 {
1759 self.im
1760 }
1761 pub fn is_zero(&self) -> bool {
1762 self.re == 0.0 && self.im == 0.0
1763 }
1764 pub fn is_real(&self) -> bool {
1766 self.im == 0.0
1767 }
1768 pub fn conjugate(&self) -> ComplexF {
1770 ComplexF {
1771 re: self.re,
1772 im: -self.im,
1773 }
1774 }
1775 pub fn norm_sqr(&self) -> f64 {
1777 self.re * self.re + self.im * self.im
1778 }
1779 pub fn abs(&self) -> f64 {
1781 self.norm_sqr().sqrt()
1782 }
1783 pub fn negated(&self) -> ComplexF {
1784 ComplexF {
1785 re: -self.re,
1786 im: -self.im,
1787 }
1788 }
1789 pub fn add(&self, other: &ComplexF) -> ComplexF {
1790 ComplexF {
1791 re: self.re + other.re,
1792 im: self.im + other.im,
1793 }
1794 }
1795 pub fn sub(&self, other: &ComplexF) -> ComplexF {
1796 ComplexF {
1797 re: self.re - other.re,
1798 im: self.im - other.im,
1799 }
1800 }
1801 pub fn mul(&self, other: &ComplexF) -> ComplexF {
1803 let (a, b, c, d) = (self.re, self.im, other.re, other.im);
1804 ComplexF {
1805 re: a * c - b * d,
1806 im: a * d + b * c,
1807 }
1808 }
1809 pub fn recip(&self) -> Option<ComplexF> {
1811 let n = self.norm_sqr();
1812 if n == 0.0 {
1813 return None;
1814 }
1815 Some(ComplexF {
1816 re: self.re / n,
1817 im: -self.im / n,
1818 })
1819 }
1820 pub fn div(&self, other: &ComplexF) -> Option<ComplexF> {
1822 Some(self.mul(&other.recip()?))
1823 }
1824 pub fn sqrt(&self) -> ComplexF {
1828 let m = self.abs();
1829 if m == 0.0 {
1830 return ComplexF { re: 0.0, im: 0.0 };
1831 }
1832 let re = ((m + self.re) * 0.5).max(0.0).sqrt();
1833 let im0 = ((m - self.re) * 0.5).max(0.0).sqrt();
1834 ComplexF {
1835 re,
1836 im: if self.im < 0.0 { -im0 } else { im0 },
1837 }
1838 }
1839 pub fn pow(&self, exp: i32) -> Option<ComplexF> {
1842 if exp < 0 {
1843 return self.recip()?.pow(-exp);
1844 }
1845 let mut result = ComplexF::from_f64(1.0);
1846 let mut base = *self;
1847 let mut e = exp as u32;
1848 while e > 0 {
1849 if e & 1 == 1 {
1850 result = result.mul(&base);
1851 }
1852 e >>= 1;
1853 if e > 0 {
1854 base = base.mul(&base);
1855 }
1856 }
1857 Some(result)
1858 }
1859}
1860
1861impl fmt::Display for ComplexF {
1862 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1863 if self.im == 0.0 {
1866 return write!(f, "{}", self.re);
1867 }
1868 let sign = if self.im < 0.0 { "-" } else { "+" };
1869 write!(f, "{}{}{}i", self.re, sign, self.im.abs())
1870 }
1871}
1872
1873impl fmt::Debug for Complex {
1874 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1875 write!(f, "Complex({self})")
1876 }
1877}
1878
1879impl From<i64> for Complex {
1880 fn from(x: i64) -> Self {
1881 Complex::from_i64(x)
1882 }
1883}
1884
1885impl From<Rational> for Complex {
1886 fn from(x: Rational) -> Self {
1887 Complex::from_rational(x)
1888 }
1889}
1890
1891fn bigint_egcd(a: &BigInt, b: &BigInt) -> (BigInt, BigInt, BigInt) {
1898 let (mut old_r, mut r) = (a.clone(), b.clone());
1899 let (mut old_s, mut s) = (BigInt::from_i64(1), BigInt::zero());
1900 let (mut old_t, mut t) = (BigInt::zero(), BigInt::from_i64(1));
1901 while !r.is_zero() {
1902 let (q, _) = old_r.div_rem(&r).expect("r is nonzero inside the loop");
1903 let nr = old_r.sub(&q.mul(&r));
1904 old_r = std::mem::replace(&mut r, nr);
1905 let ns = old_s.sub(&q.mul(&s));
1906 old_s = std::mem::replace(&mut s, ns);
1907 let nt = old_t.sub(&q.mul(&t));
1908 old_t = std::mem::replace(&mut t, nt);
1909 }
1910 (old_r, old_s, old_t)
1911}
1912
1913#[derive(Clone, PartialEq, Eq, Hash)]
1923pub struct Modular {
1924 value: BigInt,
1925 modulus: BigInt,
1926}
1927
1928fn mod_reduce(value: BigInt, modulus: &BigInt) -> BigInt {
1930 let (_, r) = value.div_rem(modulus).expect("modulus is nonzero");
1931 if r.is_negative() {
1932 r.add(modulus)
1933 } else {
1934 r
1935 }
1936}
1937
1938impl Modular {
1939 pub fn new(value: BigInt, modulus: BigInt) -> Option<Modular> {
1941 if modulus.is_zero() || modulus.is_negative() {
1942 return None;
1943 }
1944 let value = mod_reduce(value, &modulus);
1945 Some(Modular { value, modulus })
1946 }
1947
1948 pub fn from_i64(value: i64, modulus: i64) -> Option<Modular> {
1950 Modular::new(BigInt::from_i64(value), BigInt::from_i64(modulus))
1951 }
1952
1953 pub fn value(&self) -> &BigInt {
1955 &self.value
1956 }
1957
1958 pub fn modulus(&self) -> &BigInt {
1959 &self.modulus
1960 }
1961
1962 pub fn is_zero(&self) -> bool {
1963 self.value.is_zero()
1964 }
1965
1966 pub fn add(&self, other: &Modular) -> Option<Modular> {
1968 if self.modulus != other.modulus {
1969 return None;
1970 }
1971 Modular::new(self.value.add(&other.value), self.modulus.clone())
1972 }
1973
1974 pub fn sub(&self, other: &Modular) -> Option<Modular> {
1975 if self.modulus != other.modulus {
1976 return None;
1977 }
1978 Modular::new(self.value.sub(&other.value), self.modulus.clone())
1979 }
1980
1981 pub fn mul(&self, other: &Modular) -> Option<Modular> {
1982 if self.modulus != other.modulus {
1983 return None;
1984 }
1985 Modular::new(self.value.mul(&other.value), self.modulus.clone())
1986 }
1987
1988 pub fn negated(&self) -> Modular {
1990 Modular::new(self.value.negated(), self.modulus.clone()).expect("modulus stays valid")
1991 }
1992
1993 pub fn pow(&self, mut exp: u64) -> Modular {
1995 let one = Modular::new(BigInt::from_i64(1), self.modulus.clone()).expect("modulus valid");
1996 let mut result = one;
1997 let mut base = self.clone();
1998 while exp > 0 {
1999 if exp & 1 == 1 {
2000 result = result.mul(&base).expect("same modulus");
2001 }
2002 exp >>= 1;
2003 if exp > 0 {
2004 base = base.mul(&base).expect("same modulus");
2005 }
2006 }
2007 result
2008 }
2009
2010 pub fn inverse(&self) -> Option<Modular> {
2013 let (g, x, _) = bigint_egcd(&self.value, &self.modulus);
2014 if g != BigInt::from_i64(1) {
2015 return None;
2016 }
2017 Modular::new(x, self.modulus.clone())
2018 }
2019
2020 pub fn div(&self, other: &Modular) -> Option<Modular> {
2022 if self.modulus != other.modulus {
2023 return None;
2024 }
2025 self.mul(&other.inverse()?)
2026 }
2027}
2028
2029impl fmt::Display for Modular {
2030 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2031 write!(f, "{} (mod {})", self.value, self.modulus)
2032 }
2033}
2034
2035impl fmt::Debug for Modular {
2036 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2037 write!(f, "Modular({} mod {})", self.value, self.modulus)
2038 }
2039}
2040
2041pub const NUMERIC_HASH_P: u64 = (1u64 << 61) - 1;
2054
2055fn decompose_f64(f: f64) -> Option<(bool, u64, i32)> {
2058 if !f.is_finite() {
2059 return None;
2060 }
2061 let bits = f.to_bits();
2062 let neg = bits >> 63 == 1;
2063 let biased = ((bits >> 52) & 0x7ff) as i32;
2064 let frac = bits & ((1u64 << 52) - 1);
2065 let (m, e) = if biased == 0 {
2066 (frac, -1074) } else {
2068 (frac | (1u64 << 52), biased - 1075)
2069 };
2070 Some((neg, m, e))
2071}
2072
2073pub fn rational_from_f64_exact(f: f64) -> Option<Rational> {
2075 let (neg, m, e) = decompose_f64(f)?;
2076 let mag = BigInt::from_u64(m);
2077 let two = BigInt::from_u64(2);
2078 let (num, den) = if e >= 0 {
2079 (mag.mul(&two.pow(e as u32)), BigInt::from_i64(1))
2080 } else {
2081 (mag, two.pow((-e) as u32))
2082 };
2083 let num = if neg { num.negated() } else { num };
2084 Rational::new(num, den)
2085}
2086
2087pub fn rational_to_f64_nearest(r: &Rational) -> f64 {
2093 if r.is_zero() {
2094 return 0.0;
2095 }
2096 let neg = r.is_negative();
2097 let n = r.numerator().abs();
2098 let d = r.denominator().clone();
2099 let e0 = n.bit_len() as i64 - d.bit_len() as i64;
2100 let at_least = if e0 >= 0 {
2101 n >= d.shl_bits(e0 as u64)
2102 } else {
2103 n.shl_bits((-e0) as u64) >= d
2104 };
2105 let e = if at_least { e0 } else { e0 - 1 };
2106 if e > 1023 {
2107 return if neg { f64::NEG_INFINITY } else { f64::INFINITY };
2108 }
2109 let shift = if e >= -1022 { 52 - e } else { 1074 };
2110 let (num, den) = if shift >= 0 {
2111 (n.shl_bits(shift as u64), d)
2112 } else {
2113 (n, d.shl_bits((-shift) as u64))
2114 };
2115 let (mut q, rem) = num.div_rem(&den).expect("the denominator is nonzero");
2116 let round_up = match rem.add(&rem).cmp(&den) {
2117 Ordering::Greater => true,
2118 Ordering::Less => false,
2119 Ordering::Equal => q.is_odd(),
2120 };
2121 if round_up {
2122 q = q.add(&BigInt::from_i64(1));
2123 }
2124 let significand = q.to_u64().expect("at most 2^53 after rounding") as f64;
2125 let magnitude = scale_by_pow2(significand, -shift);
2126 if neg {
2127 -magnitude
2128 } else {
2129 magnitude
2130 }
2131}
2132
2133fn pow2_normal(j: i64) -> f64 {
2135 f64::from_bits(((j + 1023) as u64) << 52)
2136}
2137
2138fn scale_by_pow2(x: f64, k: i64) -> f64 {
2141 if k < -1022 {
2142 x * pow2_normal(-1022) * pow2_normal(k + 1022)
2143 } else if k > 1023 {
2144 x * pow2_normal(1023) * pow2_normal(k - 1023)
2145 } else {
2146 x * pow2_normal(k)
2147 }
2148}
2149
2150pub fn cmp_i64_f64_exact(i: i64, f: f64) -> Option<Ordering> {
2152 if f.is_nan() {
2153 return None;
2154 }
2155 if f == f64::INFINITY {
2156 return Some(Ordering::Less);
2157 }
2158 if f == f64::NEG_INFINITY {
2159 return Some(Ordering::Greater);
2160 }
2161 if i.unsigned_abs() <= (1u64 << 53) {
2164 return (i as f64).partial_cmp(&f);
2165 }
2166 let fr = rational_from_f64_exact(f).expect("finite f64 is an exact rational");
2167 Some(Rational::from_i64(i).cmp(&fr))
2168}
2169
2170pub fn cmp_bigint_f64_exact(b: &BigInt, f: f64) -> Option<Ordering> {
2172 if f.is_nan() {
2173 return None;
2174 }
2175 if f == f64::INFINITY {
2176 return Some(Ordering::Less);
2177 }
2178 if f == f64::NEG_INFINITY {
2179 return Some(Ordering::Greater);
2180 }
2181 let fr = rational_from_f64_exact(f).expect("finite f64 is an exact rational");
2182 Some(Rational::from_bigint(b.clone()).cmp(&fr))
2183}
2184
2185pub fn cmp_rational_f64_exact(r: &Rational, f: f64) -> Option<Ordering> {
2187 if f.is_nan() {
2188 return None;
2189 }
2190 if f == f64::INFINITY {
2191 return Some(Ordering::Less);
2192 }
2193 if f == f64::NEG_INFINITY {
2194 return Some(Ordering::Greater);
2195 }
2196 let fr = rational_from_f64_exact(f).expect("finite f64 is an exact rational");
2197 Some(r.cmp(&fr))
2198}
2199
2200fn mod_p(x: u64) -> u64 {
2202 let r = (x & NUMERIC_HASH_P) + (x >> 61);
2203 if r >= NUMERIC_HASH_P {
2204 r - NUMERIC_HASH_P
2205 } else {
2206 r
2207 }
2208}
2209
2210fn mul_mod_p(a: u64, b: u64) -> u64 {
2211 ((a as u128 * b as u128) % (NUMERIC_HASH_P as u128)) as u64
2212}
2213
2214fn pow_mod_p(mut base: u64, mut exp: u64) -> u64 {
2215 let mut acc = 1u64;
2216 base %= NUMERIC_HASH_P;
2217 while exp > 0 {
2218 if exp & 1 == 1 {
2219 acc = mul_mod_p(acc, base);
2220 }
2221 base = mul_mod_p(base, base);
2222 exp >>= 1;
2223 }
2224 acc
2225}
2226
2227fn signed_hash(neg: bool, h: u64) -> u64 {
2230 if neg && h != 0 {
2231 NUMERIC_HASH_P - h
2232 } else {
2233 h
2234 }
2235}
2236
2237pub fn numeric_hash_i64(n: i64) -> u64 {
2239 signed_hash(n < 0, mod_p(n.unsigned_abs()))
2240}
2241
2242pub fn numeric_hash_bigint(b: &BigInt) -> u64 {
2245 let mut acc: u64 = 0;
2246 for &limb in b.mag.limbs().iter().rev() {
2247 let t = (acc as u128) * 8 + (mod_p(limb) as u128);
2248 acc = (t % (NUMERIC_HASH_P as u128)) as u64;
2249 }
2250 signed_hash(b.is_negative(), acc)
2251}
2252
2253pub fn numeric_hash_f64(f: f64) -> u64 {
2257 if f.is_nan() {
2258 return 0x6e616e; }
2260 if f == f64::INFINITY {
2261 return 314159;
2262 }
2263 if f == f64::NEG_INFINITY {
2264 return NUMERIC_HASH_P - 314159;
2265 }
2266 let (neg, m, e) = decompose_f64(f).expect("finite");
2267 let h = mul_mod_p(mod_p(m), pow_mod_p(2, e.rem_euclid(61) as u64));
2268 signed_hash(neg, h)
2269}
2270
2271pub fn numeric_hash_rational(r: &Rational) -> u64 {
2275 let num = numeric_hash_bigint(&r.numerator().abs());
2276 let den = numeric_hash_bigint(&r.denominator().abs());
2277 let inv = pow_mod_p(den, NUMERIC_HASH_P - 2);
2278 signed_hash(r.is_negative(), mul_mod_p(num, inv))
2279}
2280
2281pub fn float_min(a: f64, b: f64) -> f64 {
2285 if a.is_nan() {
2286 b
2287 } else if b.is_nan() || a < b || (a == b && a.is_sign_negative()) {
2288 a
2289 } else {
2290 b
2291 }
2292}
2293
2294pub fn float_max(a: f64, b: f64) -> f64 {
2297 if a.is_nan() {
2298 b
2299 } else if b.is_nan() || a > b || (a == b && a.is_sign_positive()) {
2300 a
2301 } else {
2302 b
2303 }
2304}
2305
2306#[cfg(test)]
2307#[path = "../../logicaffeine_tests/unit/logicaffeine_base/numeric/tests.rs"]
2308mod tests;