1use logicaffeine_base::numeric::{BigInt, Rational};
19
20const MR_BASES: &[u64] = &[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37];
23
24fn one() -> BigInt {
25 BigInt::from_i64(1)
26}
27
28fn two() -> BigInt {
29 BigInt::from_i64(2)
30}
31
32fn rem(a: &BigInt, m: &BigInt) -> BigInt {
34 a.div_rem(m).expect("modulus is nonzero").1
35}
36
37pub fn gcd(a: &BigInt, b: &BigInt) -> BigInt {
39 let (mut a, mut b) = (a.abs(), b.abs());
40 while !b.is_zero() {
41 let r = rem(&a, &b);
42 a = b;
43 b = r;
44 }
45 a
46}
47
48pub fn mod_inverse(a: &BigInt, m: &BigInt) -> Option<BigInt> {
50 let (mut old_r, mut r) = (rem(a, m), m.clone());
51 let (mut old_s, mut s) = (one(), BigInt::zero());
52 while !r.is_zero() {
53 let (q, rr) = old_r.div_rem(&r).expect("nonzero");
54 old_r = r;
55 r = rr;
56 let ns = old_s.sub(&q.mul(&s));
57 old_s = s;
58 s = ns;
59 }
60 if old_r != one() {
61 return None;
62 }
63 let mut res = rem(&old_s, m);
64 if res.is_negative() {
65 res = res.add(m);
66 }
67 Some(res)
68}
69
70pub fn modpow(base: &BigInt, exp: &BigInt, m: &BigInt) -> BigInt {
73 if *m == one() {
74 return BigInt::zero();
75 }
76 let two = two();
77 let mut result = one();
78 let mut b = rem(base, m);
79 let mut e = exp.clone();
80 while !e.is_zero() {
81 let (q, bit) = e.div_rem(&two).expect("nonzero");
82 if !bit.is_zero() {
83 result = rem(&result.mul(&b), m);
84 }
85 b = rem(&b.mul(&b), m);
86 e = q;
87 }
88 result
89}
90
91pub fn isqrt(n: &BigInt) -> BigInt {
95 if n.is_zero() || n.is_negative() {
96 return BigInt::zero();
97 }
98 let two = two();
99 let approx = n.to_f64().sqrt();
100 let mut x = if approx.is_finite() && approx >= 1.0 {
101 BigInt::parse_decimal(&format!("{approx:.0}")).unwrap_or_else(one)
102 } else {
103 one()
104 };
105 if x.is_zero() {
106 x = one();
107 }
108 while x.mul(&x) < *n {
109 x = x.mul(&two); }
111 loop {
112 let (q, _) = n.div_rem(&x).expect("nonzero");
113 let y = x.add(&q).div_rem(&two).expect("nonzero").0;
114 if y >= x {
115 return x;
116 }
117 x = y;
118 }
119}
120
121pub fn is_probable_prime(n: &BigInt) -> bool {
123 let (one, two) = (one(), two());
124 if *n < two {
125 return false;
126 }
127 if *n == two {
128 return true;
129 }
130 if !n.is_odd() {
131 return false;
132 }
133 let n1 = n.sub(&one);
135 let mut d = n1.clone();
136 let mut s = 0u32;
137 while !d.is_odd() {
138 d = d.div_rem(&two).expect("nonzero").0;
139 s += 1;
140 }
141 'base: for &a in MR_BASES {
142 let a = BigInt::from_u64(a);
143 if rem(&a, n).is_zero() {
144 continue; }
146 let mut x = modpow(&a, &d, n);
147 if x == one || x == n1 {
148 continue;
149 }
150 for _ in 0..s.saturating_sub(1) {
151 x = rem(&x.mul(&x), n);
152 if x == n1 {
153 continue 'base;
154 }
155 }
156 return false;
157 }
158 true
159}
160
161pub fn next_prime(start: &BigInt) -> BigInt {
163 let (one, two) = (one(), two());
164 if *start <= two {
165 return two;
166 }
167 let mut c = if start.is_odd() {
168 start.clone()
169 } else {
170 start.add(&one)
171 };
172 loop {
173 if is_probable_prime(&c) {
174 return c;
175 }
176 c = c.add(&two);
177 }
178}
179
180pub fn verify_factorization(n: &BigInt, p: &BigInt, q: &BigInt) -> bool {
182 let one = one();
183 p.mul(q) == *n && *p > one && *q > one && *p < *n && *q < *n
184}
185
186fn split(n: &BigInt, d: &BigInt) -> Option<(BigInt, BigInt)> {
187 let one = one();
188 if *d > one && *d < *n {
189 let (q, r) = n.div_rem(d).expect("nonzero");
190 if r.is_zero() {
191 return Some((d.clone(), q));
192 }
193 }
194 None
195}
196
197pub fn trial_division(n: &BigInt, limit: u64) -> Option<(BigInt, BigInt)> {
199 let mut d = 2u64;
200 while d <= limit {
201 let bd = BigInt::from_u64(d);
202 if bd.mul(&bd) > *n {
203 break;
204 }
205 if let Some(f) = split(n, &bd) {
206 return Some(f);
207 }
208 d += if d == 2 { 1 } else { 2 };
209 }
210 None
211}
212
213pub fn fermat(n: &BigInt, max_iters: u64) -> Option<(BigInt, BigInt)> {
217 if !n.is_odd() {
218 return split(n, &two());
219 }
220 let one = one();
221 let mut a = isqrt(n);
222 if a.mul(&a) < *n {
223 a = a.add(&one);
224 }
225 for _ in 0..max_iters {
226 let b2 = a.mul(&a).sub(n);
227 let b = isqrt(&b2);
228 if b.mul(&b) == b2 {
229 let p = a.sub(&b);
230 let q = a.add(&b);
231 if verify_factorization(n, &p, &q) {
232 return Some((p, q));
233 }
234 }
235 a = a.add(&one);
236 }
237 None
238}
239
240pub fn pollard_rho(n: &BigInt, max_iters: u64) -> Option<(BigInt, BigInt)> {
243 let (one, two) = (one(), two());
244 if !n.is_odd() {
245 return split(n, &two);
246 }
247 let f = |x: &BigInt| rem(&x.mul(x).add(&one), n);
248 let (mut x, mut y, mut d) = (two.clone(), two.clone(), one.clone());
249 let mut iters = 0u64;
250 while d == one && iters < max_iters {
251 x = f(&x);
252 y = f(&f(&y));
253 d = gcd(&x.sub(&y).abs(), n);
254 iters += 1;
255 }
256 split(n, &d)
257}
258
259pub fn pollard_p_minus_1(n: &BigInt, bound: u64) -> Option<(BigInt, BigInt)> {
263 let one = one();
264 let mut a = two();
265 for k in 2..=bound {
266 a = modpow(&a, &BigInt::from_u64(k), n);
267 if k % 16 == 0 || k == bound {
268 if let Some(f) = split(n, &gcd(&a.sub(&one), n)) {
269 return Some(f);
270 }
271 }
272 }
273 split(n, &gcd(&a.sub(&one), n))
274}
275
276pub fn wiener(e: &BigInt, n: &BigInt) -> Option<(BigInt, BigInt)> {
281 let (one, two, four) = (one(), two(), BigInt::from_i64(4));
282 let (mut num, mut den) = (e.clone(), n.clone());
283 let (mut h2, mut h1) = (BigInt::zero(), one.clone());
285 let (mut k2, mut k1) = (one.clone(), BigInt::zero());
286 for _ in 0..2000 {
287 if den.is_zero() {
288 break;
289 }
290 let (a, r) = num.div_rem(&den).expect("nonzero");
291 let h = a.mul(&h1).add(&h2); let k = a.mul(&k1).add(&k2); if !h.is_zero() {
294 let (phi, prem) = e.mul(&k).sub(&one).div_rem(&h).expect("nonzero");
295 if prem.is_zero() {
296 let s = n.sub(&phi).add(&one); let disc = s.mul(&s).sub(&four.mul(n));
299 if !disc.is_negative() {
300 let sq = isqrt(&disc);
301 if sq.mul(&sq) == disc {
302 let p = s.sub(&sq).div_rem(&two).expect("nonzero").0;
303 let q = s.add(&sq).div_rem(&two).expect("nonzero").0;
304 if verify_factorization(n, &p, &q) {
305 return Some((p, q));
306 }
307 }
308 }
309 }
310 }
311 num = den;
312 den = r;
313 (h2, h1) = (h1, h);
314 (k2, k1) = (k1, k);
315 }
316 None
317}
318
319fn pos_rem(a: &BigInt, m: &BigInt) -> BigInt {
329 let r = rem(a, m);
330 if r.is_negative() {
331 r.add(m)
332 } else {
333 r
334 }
335}
336
337pub fn crt(residues: &[BigInt], moduli: &[BigInt]) -> Option<BigInt> {
340 if residues.is_empty() || residues.len() != moduli.len() {
341 return None;
342 }
343 let mut x = pos_rem(&residues[0], &moduli[0]);
344 let mut m = moduli[0].clone();
345 for i in 1..moduli.len() {
346 let mi = &moduli[i];
347 let inv = mod_inverse(&pos_rem(&m, mi), mi)?;
348 let diff = pos_rem(&residues[i].sub(&x), mi);
349 let t = pos_rem(&diff.mul(&inv), mi);
350 x = x.add(&m.mul(&t));
351 m = m.mul(mi);
352 x = pos_rem(&x, &m);
353 }
354 Some(x)
355}
356
357pub fn integer_nth_root(x: &BigInt, n: u32) -> BigInt {
360 if n == 0 || x.is_negative() {
361 return BigInt::zero();
362 }
363 if n == 1 || x.is_zero() {
364 return x.clone();
365 }
366 let (one, two) = (one(), two());
367 let nn = BigInt::from_u64(n as u64);
368 let nm1 = BigInt::from_u64((n - 1) as u64);
369 let approx = x.to_f64().powf(1.0 / n as f64);
370 let mut r = if approx.is_finite() && approx >= 1.0 {
371 BigInt::parse_decimal(&format!("{approx:.0}")).unwrap_or_else(|| one.clone())
372 } else {
373 one.clone()
374 };
375 if r.is_zero() {
376 r = one.clone();
377 }
378 while r.pow(n) < *x {
379 r = r.mul(&two); }
381 loop {
382 let (q, _) = x.div_rem(&r.pow(n - 1)).expect("nonzero");
383 let next = nm1.mul(&r).add(&q).div_rem(&nn).expect("nonzero").0;
384 if next >= r {
385 break;
386 }
387 r = next;
388 }
389 while r.pow(n) > *x {
390 r = r.sub(&one);
391 }
392 while r.add(&one).pow(n) <= *x {
393 r = r.add(&one);
394 }
395 r
396}
397
398pub fn hastad_broadcast_attack(
403 e: u32,
404 ciphertexts: &[BigInt],
405 moduli: &[BigInt],
406) -> Option<BigInt> {
407 if (ciphertexts.len() as u32) < e {
408 return None;
409 }
410 let c = crt(ciphertexts, moduli)?;
411 let m = integer_nth_root(&c, e);
412 (m.pow(e) == c).then_some(m)
413}
414
415fn ext_gcd(a: &BigInt, b: &BigInt) -> (BigInt, BigInt, BigInt) {
419 let (mut old_r, mut r) = (a.clone(), b.clone());
420 let (mut old_s, mut s) = (one(), BigInt::zero());
421 let (mut old_t, mut t) = (BigInt::zero(), one());
422 while !r.is_zero() {
423 let (q, _) = old_r.div_rem(&r).expect("nonzero");
424 let nr = old_r.sub(&q.mul(&r));
425 old_r = r;
426 r = nr;
427 let ns = old_s.sub(&q.mul(&s));
428 old_s = s;
429 s = ns;
430 let nt = old_t.sub(&q.mul(&t));
431 old_t = t;
432 t = nt;
433 }
434 (old_r, old_s, old_t)
435}
436
437pub fn common_modulus_attack(
441 e1: &BigInt,
442 e2: &BigInt,
443 c1: &BigInt,
444 c2: &BigInt,
445 n: &BigInt,
446) -> Option<BigInt> {
447 let (g, a, b) = ext_gcd(e1, e2);
448 if g != one() {
449 return None;
450 }
451 let t1 = if a.is_negative() {
452 modpow(&mod_inverse(c1, n)?, &a.negated(), n)
453 } else {
454 modpow(c1, &a, n)
455 };
456 let t2 = if b.is_negative() {
457 modpow(&mod_inverse(c2, n)?, &b.negated(), n)
458 } else {
459 modpow(c2, &b, n)
460 };
461 Some(rem(&t1.mul(&t2), n))
462}
463
464pub fn low_exponent_message(c: &BigInt, e: u32) -> Option<BigInt> {
467 let m = integer_nth_root(c, e);
468 (m.pow(e) == *c).then_some(m)
469}
470
471fn poly_norm_mod(p: &[BigInt], n: &BigInt) -> Vec<BigInt> {
472 let mut v: Vec<BigInt> = p.iter().map(|c| pos_rem(c, n)).collect();
473 while v.len() > 1 && v.last().is_some_and(|c| c.is_zero()) {
474 v.pop();
475 }
476 if v.is_empty() {
477 v.push(BigInt::zero());
478 }
479 v
480}
481
482fn poly_mul_mod(a: &[BigInt], b: &[BigInt], n: &BigInt) -> Vec<BigInt> {
483 let mut out = vec![BigInt::zero(); a.len() + b.len() - 1];
484 for (i, ai) in a.iter().enumerate() {
485 for (j, bj) in b.iter().enumerate() {
486 out[i + j] = pos_rem(&out[i + j].add(&ai.mul(bj)), n);
487 }
488 }
489 poly_norm_mod(&out, n)
490}
491
492fn poly_rem_mod(a: &[BigInt], b: &[BigInt], n: &BigInt) -> Option<Vec<BigInt>> {
495 let b = poly_norm_mod(b, n);
496 let db = b.len() - 1;
497 if b.iter().all(|c| c.is_zero()) {
498 return None;
499 }
500 let lead_inv = mod_inverse(&b[db], n)?;
501 let mut r = poly_norm_mod(a, n);
502 while r.len() > db {
503 let dr = r.len() - 1;
504 let factor = pos_rem(&r[dr].mul(&lead_inv), n);
505 let shift = dr - db;
506 for i in 0..b.len() {
507 r[shift + i] = pos_rem(&r[shift + i].sub(&factor.mul(&b[i])), n);
508 }
509 r = poly_norm_mod(&r, n);
510 }
511 Some(r)
512}
513
514fn poly_gcd_mod(a: &[BigInt], b: &[BigInt], n: &BigInt) -> Option<Vec<BigInt>> {
516 let mut a = poly_norm_mod(a, n);
517 let mut b = poly_norm_mod(b, n);
518 while !(b.len() == 1 && b[0].is_zero()) {
519 let r = poly_rem_mod(&a, &b, n)?;
520 a = b;
521 b = r;
522 }
523 Some(a)
524}
525
526pub fn franklin_reiter_attack(
532 e: u32,
533 r: &BigInt,
534 c1: &BigInt,
535 c2: &BigInt,
536 n: &BigInt,
537) -> Option<BigInt> {
538 let mut g1 = vec![BigInt::zero(); (e + 1) as usize];
539 g1[0] = pos_rem(&c1.negated(), n);
540 g1[e as usize] = one();
541
542 let xr = vec![pos_rem(r, n), one()];
543 let mut g2 = vec![one()];
544 for _ in 0..e {
545 g2 = poly_mul_mod(&g2, &xr, n);
546 }
547 g2[0] = pos_rem(&g2[0].sub(c2), n);
548
549 let g = poly_gcd_mod(&g1, &g2, n)?;
550 if g.len() == 2 {
551 let m = pos_rem(&g[0].negated().mul(&mod_inverse(&g[1], n)?), n);
552 if modpow(&m, &BigInt::from_u64(e as u64), n) == pos_rem(c1, n) {
553 return Some(m);
554 }
555 }
556 None
557}
558
559fn poly_mul(a: &[BigInt], b: &[BigInt]) -> Vec<BigInt> {
564 if a.is_empty() || b.is_empty() {
565 return Vec::new();
566 }
567 let mut out = vec![BigInt::zero(); a.len() + b.len() - 1];
568 for (i, ai) in a.iter().enumerate() {
569 for (j, bj) in b.iter().enumerate() {
570 out[i + j] = out[i + j].add(&ai.mul(bj));
571 }
572 }
573 out
574}
575
576fn poly_pow(base: &[BigInt], e: usize) -> Vec<BigInt> {
577 let mut acc = vec![one()];
578 for _ in 0..e {
579 acc = poly_mul(&acc, base);
580 }
581 acc
582}
583
584fn poly_eval(coeffs: &[BigInt], x: &BigInt) -> BigInt {
585 coeffs
586 .iter()
587 .rev()
588 .fold(BigInt::zero(), |acc, c| acc.mul(x).add(c))
589}
590
591fn poly_integer_root(coeffs: &[BigInt], bound: &BigInt) -> Option<BigInt> {
596 let maxc = coeffs.iter().map(|c| c.abs()).max()?;
597 if maxc.is_zero() {
598 return None;
599 }
600 if bound.to_f64() <= 4_200_000.0 {
604 let mut x = BigInt::zero();
605 let one = one();
606 while x <= *bound {
607 if poly_eval(coeffs, &x).is_zero() {
608 return Some(x);
609 }
610 x = x.add(&one);
611 }
612 return None;
613 }
614 let cf: Vec<f64> = coeffs
615 .iter()
616 .map(|c| {
617 Rational::new(c.clone(), maxc.clone())
618 .map(|r| r.to_f64())
619 .unwrap_or(0.0)
620 })
621 .collect();
622 let eval = |x: f64| cf.iter().rev().fold(0.0, |acc, &c| acc * x + c);
623 let deriv = |x: f64| {
624 (1..cf.len())
625 .rev()
626 .fold(0.0, |acc, k| acc * x + cf[k] * k as f64)
627 };
628 let bound_f = bound.to_f64();
629
630 let mut seeds: Vec<f64> = Vec::new();
631 let mut p = 1.0;
632 while p <= bound_f {
633 seeds.push(p);
634 p *= 1.5;
635 }
636 for i in 0..=64 {
637 seeds.push(bound_f * i as f64 / 64.0);
638 }
639
640 let mut seen: Vec<BigInt> = Vec::new();
641 for &s in &seeds {
642 let mut x = s;
643 for _ in 0..200 {
644 let d = deriv(x);
645 if d.abs() < 1e-15 {
646 break;
647 }
648 let nx = x - eval(x) / d;
649 if !nx.is_finite() {
650 break;
651 }
652 if (nx - x).abs() < 0.4 {
653 x = nx;
654 break;
655 }
656 x = nx;
657 }
658 if x.is_finite() && x >= -1.0 && x <= bound_f + 1.0 {
659 if let Some(cand) = BigInt::parse_decimal(&format!("{:.0}", x.max(0.0))) {
660 if !seen.contains(&cand) {
661 if cand <= *bound && poly_eval(coeffs, &cand).is_zero() {
662 return Some(cand);
663 }
664 seen.push(cand);
665 }
666 }
667 }
668 }
669 None
670}
671
672fn poly_derivative(p: &[BigInt]) -> Vec<BigInt> {
673 (1..p.len())
674 .map(|k| p[k].mul(&BigInt::from_i64(k as i64)))
675 .collect()
676}
677
678fn round_div_factor(a: &BigInt, b: &BigInt) -> BigInt {
680 let (q, r) = a.div_rem(b).expect("nonzero");
681 if r.is_zero() {
682 return q;
683 }
684 if BigInt::from_i64(2).mul(&r.abs()) > b.abs() {
685 if a.is_negative() ^ b.is_negative() {
686 q.sub(&one())
687 } else {
688 q.add(&one())
689 }
690 } else {
691 q
692 }
693}
694
695fn integer_roots_of(res: &[BigInt], bound: &BigInt) -> Vec<BigInt> {
700 let deriv = poly_derivative(res);
701 let mut out: Vec<BigInt> = Vec::new();
702 for seed in real_root_candidates(res, bound) {
703 let mut x = seed;
704 for _ in 0..80 {
705 let fx = poly_eval(res, &x);
706 if fx.is_zero() {
707 break;
708 }
709 let dfx = poly_eval(&deriv, &x);
710 if dfx.is_zero() {
711 break;
712 }
713 let step = round_div_factor(&fx, &dfx);
714 if step.is_zero() {
715 break;
716 }
717 x = x.sub(&step);
718 }
719 if poly_eval(res, &x).is_zero() && x.abs() <= *bound && !out.contains(&x) {
720 out.push(x);
721 }
722 }
723 out
724}
725
726pub fn coppersmith_factor_high_bits(
733 n: &BigInt,
734 p_high: &BigInt,
735 unknown_bits: u32,
736) -> Option<(BigInt, BigInt)> {
737 let two = two();
738 let mut x_bound = one();
739 for _ in 0..unknown_bits {
740 x_bound = x_bound.mul(&two);
741 }
742 let (m, t) = (4usize, 4usize);
745 let deg = m + t;
746 let f = vec![p_high.clone(), one()]; let mut polys: Vec<Vec<BigInt>> = Vec::new();
750 for i in 0..=m {
751 let scale = n.pow((m - i) as u32);
752 polys.push(poly_pow(&f, i).iter().map(|c| c.mul(&scale)).collect());
753 }
754 let fm = poly_pow(&f, m);
755 for j in 1..=t {
756 let mut p = vec![BigInt::zero(); j];
757 p.extend_from_slice(&fm);
758 polys.push(p);
759 }
760
761 let mut xpow = vec![one()];
763 for k in 1..=deg {
764 xpow.push(xpow[k - 1].mul(&x_bound));
765 }
766 let rows: Vec<Vec<BigInt>> = polys
767 .iter()
768 .map(|p| {
769 (0..=deg)
770 .map(|k| p.get(k).cloned().unwrap_or_else(BigInt::zero).mul(&xpow[k]))
771 .collect()
772 })
773 .collect();
774
775 let reduced = crate::lattice::lll_reduce_bigint_fp(&rows);
776 for row in &reduced {
777 let mut h = Vec::with_capacity(deg + 1);
779 let mut ok = true;
780 for k in 0..=deg {
781 let (q, r) = row[k].div_rem(&xpow[k]).expect("nonzero");
782 if !r.is_zero() {
783 ok = false;
784 break;
785 }
786 h.push(q);
787 }
788 if !ok || h.iter().all(|c| c.is_zero()) {
789 continue;
790 }
791 if let Some(x0) = poly_integer_root(&h, &x_bound) {
792 if let Some(f) = split(n, &p_high.add(&x0)) {
793 return Some(f);
794 }
795 }
796 }
797 None
798}
799
800pub fn rsa_private_exponent(e: &BigInt, p: &BigInt, q: &BigInt) -> Option<BigInt> {
804 let one = one();
805 mod_inverse(e, &p.sub(&one).mul(&q.sub(&one)))
806}
807
808pub fn factor_via_private_exponent(n: &BigInt, e: &BigInt, d: &BigInt) -> Option<(BigInt, BigInt)> {
815 let (one, two) = (one(), two());
816 let n1 = n.sub(&one);
817 let k = e.mul(d).sub(&one);
818 if k.is_zero() || k.is_negative() {
819 return None;
820 }
821 let mut t = k;
823 let mut s = 0u32;
824 while !t.is_odd() {
825 t = t.div_rem(&two).expect("nonzero").0;
826 s += 1;
827 }
828 for &gb in MR_BASES {
829 let g = BigInt::from_u64(gb);
830 let shared = gcd(&g, n);
831 if shared != one {
832 if let Some(f) = split(n, &shared) {
833 return Some(f);
834 }
835 continue;
836 }
837 let mut x = modpow(&g, &t, n);
838 if x == one || x == n1 {
839 continue;
840 }
841 for _ in 0..s {
842 let y = modpow(&x, &two, n);
843 if y == one {
844 if let Some(f) = split(n, &gcd(&x.sub(&one), n)) {
846 return Some(f);
847 }
848 break;
849 }
850 if y == n1 {
851 break; }
853 x = y;
854 }
855 }
856 None
857}
858
859pub fn batch_gcd(moduli: &[BigInt]) -> Vec<(usize, usize, BigInt)> {
862 let one = one();
863 let mut hits = Vec::new();
864 for i in 0..moduli.len() {
865 for j in (i + 1)..moduli.len() {
866 let g = gcd(&moduli[i], &moduli[j]);
867 if g > one {
868 hits.push((i, j, g));
869 }
870 }
871 }
872 hits
873}
874
875fn gf2_dependencies(rows: &[Vec<bool>], ncols: usize) -> Vec<Vec<usize>> {
890 let m = rows.len();
891 let mut mat: Vec<(Vec<bool>, Vec<bool>)> = rows
892 .iter()
893 .enumerate()
894 .map(|(i, r)| {
895 let mut tag = vec![false; m];
896 tag[i] = true;
897 (r.clone(), tag)
898 })
899 .collect();
900 let mut pivot = 0;
901 for col in 0..ncols {
902 let Some(pr) = (pivot..m).find(|&i| mat[i].0[col]) else {
903 continue;
904 };
905 mat.swap(pivot, pr);
906 let (prow, ptag) = (mat[pivot].0.clone(), mat[pivot].1.clone());
907 for i in 0..m {
908 if i != pivot && mat[i].0[col] {
909 for c in 0..ncols {
910 mat[i].0[c] ^= prow[c];
911 }
912 for c in 0..m {
913 mat[i].1[c] ^= ptag[c];
914 }
915 }
916 }
917 pivot += 1;
918 }
919 mat.iter()
920 .filter(|(prim, _)| prim.iter().all(|&b| !b))
921 .map(|(_, tag)| (0..m).filter(|&i| tag[i]).collect())
922 .filter(|s: &Vec<usize>| !s.is_empty())
923 .collect()
924}
925
926pub fn dixon_factor(n: &BigInt, base: &[u64], tries: usize) -> Option<(BigInt, BigInt)> {
932 let one = one();
933 let need = base.len() + 5;
934 let mut rels: Vec<(BigInt, Vec<u64>)> = Vec::new();
935 let mut r = isqrt(n).add(&one);
936 let mut steps = 0;
937 while rels.len() < need && steps < tries {
938 let mut s = rem(&r.mul(&r), n);
939 let mut exps = vec![0u64; base.len()];
940 for (bi, &b) in base.iter().enumerate() {
941 let bb = BigInt::from_u64(b);
942 while let Some((q, rr)) = s.div_rem(&bb) {
943 if rr.is_zero() {
944 s = q;
945 exps[bi] += 1;
946 } else {
947 break;
948 }
949 }
950 }
951 if s == one {
952 rels.push((r.clone(), exps));
953 }
954 r = r.add(&one);
955 steps += 1;
956 }
957 if rels.len() < 2 {
958 return None;
959 }
960 let rows: Vec<Vec<bool>> = rels
961 .iter()
962 .map(|(_, e)| e.iter().map(|&x| x & 1 == 1).collect())
963 .collect();
964 for dep in gf2_dependencies(&rows, base.len()) {
965 let mut x = one.clone();
966 let mut total = vec![0u64; base.len()];
967 for &i in &dep {
968 x = rem(&x.mul(&rels[i].0), n);
969 for (k, &e) in rels[i].1.iter().enumerate() {
970 total[k] += e;
971 }
972 }
973 let mut y = one.clone();
974 for (k, &e) in total.iter().enumerate() {
975 y = rem(
976 &y.mul(&modpow(
977 &BigInt::from_u64(base[k]),
978 &BigInt::from_u64(e / 2),
979 n,
980 )),
981 n,
982 );
983 }
984 let diff = if x >= y { x.sub(&y) } else { x.add(n).sub(&y) };
985 for cand in [gcd(&diff, n), gcd(&x.add(&y), n)] {
986 if let Some(f) = split(n, &cand) {
987 return Some(f);
988 }
989 }
990 }
991 None
992}
993
994fn is_small_prime(p: u64) -> bool {
1004 if p < 2 {
1005 return false;
1006 }
1007 let mut d = 2u64;
1008 while d * d <= p {
1009 if p % d == 0 {
1010 return false;
1011 }
1012 d += 1;
1013 }
1014 true
1015}
1016
1017fn bigint_mod_u64(n: &BigInt, p: u64) -> u64 {
1018 n.div_rem(&BigInt::from_u64(p))
1019 .expect("nonzero")
1020 .1
1021 .to_i64()
1022 .unwrap_or(0) as u64
1023}
1024
1025fn modular_sqrt_u64(a: u64, p: u64) -> Option<u64> {
1028 let a = a % p;
1029 (0..p).find(|&r| (r as u128 * r as u128 % p as u128) as u64 == a)
1030}
1031
1032pub fn quadratic_sieve(n: &BigInt, b: u64, m_interval: usize) -> Option<(BigInt, BigInt)> {
1036 let one = one();
1037 let a = isqrt(n).add(&one);
1038
1039 let mut base: Vec<u64> = Vec::new();
1041 let mut roots: Vec<(u64, u64)> = Vec::new();
1042 for p in 2..=b {
1043 if !is_small_prime(p) {
1044 continue;
1045 }
1046 let np = bigint_mod_u64(n, p);
1047 if p == 2 {
1048 base.push(2);
1049 roots.push((np % 2, np % 2));
1050 } else if let Some(r) = modular_sqrt_u64(np, p) {
1051 base.push(p);
1052 roots.push((r, p - r));
1053 }
1054 }
1055 if base.len() < 3 {
1056 return None;
1057 }
1058
1059 let mut sieve = vec![0f64; m_interval];
1061 for (bi, &p) in base.iter().enumerate() {
1062 let am = bigint_mod_u64(&a, p) as i64;
1063 let (r1, r2) = roots[bi];
1064 let both = [r1, r2];
1065 let candidates: &[u64] = if p == 2 { &both[..1] } else { &both[..] };
1066 for &root in candidates {
1067 let mut x = ((root as i64 - am).rem_euclid(p as i64)) as usize;
1068 while x < m_interval {
1069 sieve[x] += (p as f64).ln();
1070 x += p as usize;
1071 }
1072 }
1073 }
1074
1075 let mut rels: Vec<(BigInt, Vec<u64>)> = Vec::new();
1077 for x in 0..m_interval {
1078 let ax = a.add(&BigInt::from_u64(x as u64));
1079 let q = ax.mul(&ax).sub(n);
1080 if q.is_zero() {
1081 continue;
1082 }
1083 if sieve[x] < 0.5 * q.to_f64().ln() {
1086 continue;
1087 }
1088 let mut qq = q;
1089 let mut exps = vec![0u64; base.len()];
1090 for (bi, &p) in base.iter().enumerate() {
1091 let bp = BigInt::from_u64(p);
1092 while let Some((quo, rr)) = qq.div_rem(&bp) {
1093 if rr.is_zero() {
1094 qq = quo;
1095 exps[bi] += 1;
1096 } else {
1097 break;
1098 }
1099 }
1100 }
1101 if qq == one {
1102 rels.push((ax, exps));
1103 if rels.len() > base.len() + 5 {
1104 break;
1105 }
1106 }
1107 }
1108 if rels.len() < 2 {
1109 return None;
1110 }
1111
1112 let rows: Vec<Vec<bool>> = rels
1113 .iter()
1114 .map(|(_, e)| e.iter().map(|&x| x & 1 == 1).collect())
1115 .collect();
1116 for dep in gf2_dependencies(&rows, base.len()) {
1117 let mut x = one.clone();
1118 let mut total = vec![0u64; base.len()];
1119 for &i in &dep {
1120 x = rem(&x.mul(&rels[i].0), n);
1121 for (k, &e) in rels[i].1.iter().enumerate() {
1122 total[k] += e;
1123 }
1124 }
1125 let mut y = one.clone();
1126 for (k, &e) in total.iter().enumerate() {
1127 y = rem(
1128 &y.mul(&modpow(
1129 &BigInt::from_u64(base[k]),
1130 &BigInt::from_u64(e / 2),
1131 n,
1132 )),
1133 n,
1134 );
1135 }
1136 let diff = if x >= y { x.sub(&y) } else { x.add(n).sub(&y) };
1137 for cand in [gcd(&diff, n), gcd(&x.add(&y), n)] {
1138 if let Some(f) = split(n, &cand) {
1139 return Some(f);
1140 }
1141 }
1142 }
1143 None
1144}
1145
1146type BPoly = std::collections::BTreeMap<(u32, u32), BigInt>;
1150
1151fn poly_deg(p: &[BigInt]) -> usize {
1153 let mut d = p.len();
1154 while d > 0 && p[d - 1].is_zero() {
1155 d -= 1;
1156 }
1157 d.saturating_sub(1)
1158}
1159
1160fn det_bareiss(mut a: Vec<Vec<BigInt>>) -> BigInt {
1162 let n = a.len();
1163 if n == 0 {
1164 return one();
1165 }
1166 let mut prev = one();
1167 let mut neg = false;
1168 for k in 0..n - 1 {
1169 if a[k][k].is_zero() {
1170 match (k + 1..n).find(|&i| !a[i][k].is_zero()) {
1171 Some(p) => {
1172 a.swap(k, p);
1173 neg = !neg;
1174 }
1175 None => return BigInt::zero(),
1176 }
1177 }
1178 for i in k + 1..n {
1179 for j in k + 1..n {
1180 let num = a[i][j].mul(&a[k][k]).sub(&a[i][k].mul(&a[k][j]));
1181 a[i][j] = num.div_rem(&prev).expect("Bareiss division is exact").0;
1182 }
1183 }
1184 prev = a[k][k].clone();
1185 }
1186 if neg {
1187 a[n - 1][n - 1].negated()
1188 } else {
1189 a[n - 1][n - 1].clone()
1190 }
1191}
1192
1193fn univariate_resultant(a: &[BigInt], b: &[BigInt]) -> BigInt {
1195 let (da, db) = (poly_deg(a), poly_deg(b));
1196 if a.iter().all(|c| c.is_zero()) || b.iter().all(|c| c.is_zero()) {
1197 return BigInt::zero();
1198 }
1199 if da == 0 {
1200 return a[0].pow(db as u32);
1201 }
1202 if db == 0 {
1203 return b[0].pow(da as u32);
1204 }
1205 let n = da + db;
1206 let mut syl = vec![vec![BigInt::zero(); n]; n];
1207 for r in 0..db {
1208 for c in 0..=da {
1209 syl[r][r + c] = a[da - c].clone();
1210 }
1211 }
1212 for r in 0..da {
1213 for c in 0..=db {
1214 syl[db + r][r + c] = b[db - c].clone();
1215 }
1216 }
1217 det_bareiss(syl)
1218}
1219
1220fn eval_bivar_at_y(g: &BPoly, t: &BigInt) -> Vec<BigInt> {
1222 let max_i = g.keys().map(|&(i, _)| i).max().unwrap_or(0) as usize;
1223 let mut uni = vec![BigInt::zero(); max_i + 1];
1224 for (&(i, j), c) in g {
1225 uni[i as usize] = uni[i as usize].add(&c.mul(&t.pow(j)));
1226 }
1227 uni
1228}
1229
1230fn lagrange_interpolate(points: &[(BigInt, BigInt)]) -> Vec<BigInt> {
1232 let n = points.len();
1233 let mut acc = vec![Rational::zero(); n];
1234 for (i, (xi, yi)) in points.iter().enumerate() {
1235 let mut basis = vec![Rational::zero(); n];
1237 basis[0] = Rational::from_bigint(yi.clone());
1238 let mut denom = Rational::from_i64(1);
1239 let mut deg = 0;
1240 for (m, (xm, _)) in points.iter().enumerate() {
1241 if m == i {
1242 continue;
1243 }
1244 for d in (0..=deg).rev() {
1246 let shifted = basis[d].clone();
1247 basis[d + 1] = basis[d + 1].add(&shifted);
1248 basis[d] = basis[d].mul(&Rational::from_bigint(xm.negated()));
1249 }
1250 deg += 1;
1251 denom = denom.mul(&Rational::from_bigint(xi.sub(xm)));
1252 }
1253 let inv = denom.recip().expect("distinct nodes");
1254 for d in 0..n {
1255 acc[d] = acc[d].add(&basis[d].mul(&inv));
1256 }
1257 }
1258 acc.iter().map(|r| r.round()).collect()
1259}
1260
1261fn bivariate_resultant_x(g1: &BPoly, g2: &BPoly) -> Vec<BigInt> {
1265 let dx = |g: &BPoly| g.keys().map(|&(i, _)| i).max().unwrap_or(0) as usize;
1266 let dy = |g: &BPoly| g.keys().map(|&(_, j)| j).max().unwrap_or(0) as usize;
1267 let degree = dx(g1) * dy(g2) + dx(g2) * dy(g1);
1268 let points: Vec<(BigInt, BigInt)> = (0..=degree as i64)
1269 .map(|t| {
1270 let ty = BigInt::from_i64(t);
1271 let r = univariate_resultant(&eval_bivar_at_y(g1, &ty), &eval_bivar_at_y(g2, &ty));
1272 (ty, r)
1273 })
1274 .collect();
1275 lagrange_interpolate(&points)
1276}
1277
1278fn bpoly_mul(a: &BPoly, b: &BPoly) -> BPoly {
1279 let mut out = BPoly::new();
1280 for (&(i1, j1), c1) in a {
1281 for (&(i2, j2), c2) in b {
1282 let e = out.entry((i1 + i2, j1 + j2)).or_insert_with(BigInt::zero);
1283 *e = e.add(&c1.mul(c2));
1284 }
1285 }
1286 out.retain(|_, c| !c.is_zero());
1287 out
1288}
1289
1290fn bpoly_pow(base: &BPoly, e: u32) -> BPoly {
1291 let mut acc = BPoly::new();
1292 acc.insert((0, 0), one());
1293 for _ in 0..e {
1294 acc = bpoly_mul(&acc, base);
1295 }
1296 acc
1297}
1298
1299fn bpoly_eval(g: &BPoly, x: &BigInt, y: &BigInt) -> BigInt {
1300 g.iter().fold(BigInt::zero(), |acc, (&(i, j), c)| {
1301 acc.add(&c.mul(&x.pow(i)).mul(&y.pow(j)))
1302 })
1303}
1304
1305fn bpoly_subst_x(g: &BPoly, xv: &BigInt) -> Vec<BigInt> {
1308 let max_j = g.keys().map(|&(_, j)| j).max().unwrap_or(0) as usize;
1309 let mut uni = vec![BigInt::zero(); max_j + 1];
1310 for (&(i, j), c) in g {
1311 uni[j as usize] = uni[j as usize].add(&c.mul(&xv.pow(i)));
1312 }
1313 uni
1314}
1315
1316fn bd_reduced_polys(
1319 n: &BigInt,
1320 e: &BigInt,
1321 m: usize,
1322 t: usize,
1323 x_bound: &BigInt,
1324) -> (Vec<BPoly>, BigInt) {
1325 let one = one();
1326 let y_bound = isqrt(n).mul(&BigInt::from_i64(3));
1327
1328 let mut f = BPoly::new();
1329 f.insert((1, 1), one.clone());
1330 f.insert((1, 0), n.add(&one));
1331 f.insert((0, 0), one.clone());
1332
1333 let mut shifts: Vec<BPoly> = Vec::new();
1334 for k in 0..=m {
1335 let fke: BPoly = {
1336 let scale = e.pow((m - k) as u32);
1337 bpoly_pow(&f, k as u32)
1338 .into_iter()
1339 .map(|(key, c)| (key, c.mul(&scale)))
1340 .collect()
1341 };
1342 for i in 0..=(m - k) {
1343 shifts.push(
1344 fke.iter()
1345 .map(|(&(a, b), c)| ((a + i as u32, b), c.clone()))
1346 .collect(),
1347 );
1348 }
1349 for j in 1..=t {
1350 shifts.push(
1351 fke.iter()
1352 .map(|(&(a, b), c)| ((a, b + j as u32), c.clone()))
1353 .collect(),
1354 );
1355 }
1356 }
1357
1358 let mut monos: std::collections::BTreeSet<(u32, u32)> = std::collections::BTreeSet::new();
1359 for s in &shifts {
1360 monos.extend(s.keys());
1361 }
1362 let monos: Vec<(u32, u32)> = monos.into_iter().collect();
1363 let scale_of: Vec<BigInt> = monos
1364 .iter()
1365 .map(|&(i, j)| x_bound.pow(i).mul(&y_bound.pow(j)))
1366 .collect();
1367 let col: std::collections::HashMap<(u32, u32), usize> =
1368 monos.iter().enumerate().map(|(i, &k)| (k, i)).collect();
1369 let rows: Vec<Vec<BigInt>> = shifts
1370 .iter()
1371 .map(|s| {
1372 let mut row = vec![BigInt::zero(); monos.len()];
1373 for (&key, c) in s {
1374 let ci = col[&key];
1375 row[ci] = c.mul(&scale_of[ci]);
1376 }
1377 row
1378 })
1379 .collect();
1380
1381 let reduced = crate::lattice::lll_reduce_bigint_fp(&rows);
1382 let polys: Vec<BPoly> = reduced
1383 .iter()
1384 .map(|row| {
1385 let mut g = BPoly::new();
1386 for (ci, &key) in monos.iter().enumerate() {
1387 if !row[ci].is_zero() {
1388 let (q, r) = row[ci].div_rem(&scale_of[ci]).expect("nonzero");
1389 if r.is_zero() {
1390 g.insert(key, q);
1391 }
1392 }
1393 }
1394 g
1395 })
1396 .filter(|g| !g.is_empty())
1397 .collect();
1398 (polys, y_bound)
1399}
1400
1401fn real_root_candidates(res: &[BigInt], bound: &BigInt) -> Vec<BigInt> {
1404 let maxc = res.iter().map(|c| c.abs()).max().filter(|c| !c.is_zero());
1405 let Some(maxc) = maxc else {
1406 return Vec::new();
1407 };
1408 let cf: Vec<f64> = res
1409 .iter()
1410 .map(|c| {
1411 Rational::new(c.clone(), maxc.clone())
1412 .map(|r| r.to_f64())
1413 .unwrap_or(0.0)
1414 })
1415 .collect();
1416 let eval = |x: f64| cf.iter().rev().fold(0.0, |acc, &c| acc * x + c);
1417 let deriv = |x: f64| {
1418 (1..cf.len())
1419 .rev()
1420 .fold(0.0, |acc, k| acc * x + cf[k] * k as f64)
1421 };
1422 let bf = bound.to_f64();
1423 let mut seeds: Vec<f64> = Vec::new();
1424 let mut p = 1.0;
1425 while p <= bf {
1426 seeds.push(p);
1427 seeds.push(-p);
1428 p *= 1.3;
1429 }
1430 let mut out: Vec<BigInt> = Vec::new();
1431 for &s in &seeds {
1432 let mut x = s;
1433 for _ in 0..200 {
1434 let d = deriv(x);
1435 if d.abs() < 1e-18 || !x.is_finite() {
1436 break;
1437 }
1438 let nx = x - eval(x) / d;
1439 if !nx.is_finite() {
1440 break;
1441 }
1442 if (nx - x).abs() < 0.4 {
1443 x = nx;
1444 break;
1445 }
1446 x = nx;
1447 }
1448 if x.is_finite() && x.abs() <= bf * 1.01 {
1449 if let Some(c) = BigInt::parse_decimal(&format!("{:.0}", x.abs())) {
1450 let cand = if x < 0.0 { c.negated() } else { c };
1451 if !out.contains(&cand) {
1452 out.push(cand);
1453 }
1454 }
1455 }
1456 }
1457 out
1458}
1459
1460pub fn boneh_durfee(
1467 n: &BigInt,
1468 e: &BigInt,
1469 m: usize,
1470 t: usize,
1471 x_bound: &BigInt,
1472) -> Option<(BigInt, BigInt)> {
1473 let (polys, y_bound) = bd_reduced_polys(n, e, m, t, x_bound);
1474
1475 let x_lim = x_bound.to_i64().unwrap_or(0).max(0);
1479 let four_n = BigInt::from_i64(4).mul(n);
1480 let two = two();
1481 for g in polys.iter().take(6) {
1482 for ki in 1..=x_lim {
1483 let k = BigInt::from_i64(ki);
1484 let gy = bpoly_subst_x(g, &k);
1485 if gy.iter().all(|c| c.is_zero()) {
1486 continue;
1487 }
1488 for y0 in integer_roots_of(&gy, &y_bound) {
1489 let s = y0.negated();
1490 if s.is_negative() || s.is_zero() {
1491 continue;
1492 }
1493 let disc = s.mul(&s).sub(&four_n);
1494 if disc.is_negative() {
1495 continue;
1496 }
1497 let sq = isqrt(&disc);
1498 if sq.mul(&sq) == disc {
1499 let p = s.sub(&sq).div_rem(&two).expect("nonzero").0;
1500 let q = s.add(&sq).div_rem(&two).expect("nonzero").0;
1501 if verify_factorization(n, &p, &q) {
1502 return Some((p, q));
1503 }
1504 }
1505 }
1506 }
1507 }
1508 None
1509}
1510
1511#[derive(Clone, Copy, Debug)]
1514pub struct StructuralBudget {
1515 pub trial_limit: u64,
1516 pub fermat_iters: u64,
1517 pub pminus1_bound: u64,
1518 pub rho_iters: u64,
1519}
1520
1521impl Default for StructuralBudget {
1522 fn default() -> Self {
1527 Self {
1528 trial_limit: 1_000,
1529 fermat_iters: 3_000,
1530 pminus1_bound: 500,
1531 rho_iters: 5_000,
1532 }
1533 }
1534}
1535
1536#[derive(Clone, Debug, PartialEq, Eq)]
1538pub struct StructuralWitness {
1539 pub p: BigInt,
1540 pub q: BigInt,
1541 pub method: &'static str,
1542}
1543
1544pub fn structural_factor(n: &BigInt, budget: StructuralBudget) -> Option<StructuralWitness> {
1548 let mk = |(p, q): (BigInt, BigInt), method: &'static str| StructuralWitness { p, q, method };
1549 if let Some(f) = trial_division(n, budget.trial_limit) {
1550 return Some(mk(f, "trial division (small factor)"));
1551 }
1552 if let Some(f) = fermat(n, budget.fermat_iters) {
1553 return Some(mk(f, "Fermat (close primes)"));
1554 }
1555 if let Some(f) = pollard_p_minus_1(n, budget.pminus1_bound) {
1556 return Some(mk(f, "Pollard p−1 (smooth p−1)"));
1557 }
1558 if let Some(f) = pollard_rho(n, budget.rho_iters) {
1559 return Some(mk(f, "Pollard rho"));
1560 }
1561 None
1562}
1563
1564#[cfg(test)]
1565#[path = "../../logicaffeine_tests/unit/logicaffeine_proof/factor/tests.rs"]
1566mod tests;