alkahest-cas 3.9.0

High-performance computer algebra kernel: symbolic expressions, polynomials, Gröbner bases, JIT, and Arb ball arithmetic.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
//! Exact arithmetic in `Q(n)` and `Q(n)(k)`.
//!
//! Creative telescoping needs a *field* of coefficients for the linear algebra
//! (the unknowns `a_i(n)` and the certificate coefficients live in `Q(n)`) and a
//! ring of polynomials over it (the `k`-side of the Gosper equation).  This
//! module supplies both, on top of [`RatUniPoly`] (dense `Q[x]`) and
//! [`RatFunc`] (reduced `Q(x)`), which already exist for Gosper summation.
//!
//! Nothing here is approximate: every operation is exact rational arithmetic,
//! which is what makes the final certificate check in
//! [`super::zeilberger::zeilberger()`] a proof rather than a spot check.

use crate::matrix::normal_form::RatUniPoly;
use crate::sum::RatFunc;
use rug::{Integer, Rational};

/// An element of `Q(n)` — a reduced rational function in the outer variable.
pub type Rn = RatFunc;

pub fn rn_zero() -> Rn {
    RatFunc::zero()
}

pub fn rn_one() -> Rn {
    RatFunc::one()
}

pub fn rn_int(i: i64) -> Rn {
    RatFunc::scalar(Rational::from(i))
}

pub fn rn_rat(q: Rational) -> Rn {
    RatFunc::scalar(q)
}

/// The generator `n` itself.
pub fn rn_var() -> Rn {
    RatFunc::from_poly(RatUniPoly::x())
}

pub fn rn_poly(p: RatUniPoly) -> Rn {
    RatFunc::from_poly(p).normalize()
}

pub fn rn_is_zero(a: &Rn) -> bool {
    a.num.is_zero()
}

/// `a + b`.
///
/// Both operands are assumed to be in `RatFunc`'s canonical form (coprime
/// `num`/`den`, monic `den`) — every constructor in this module produces it.
/// Given that, the only cancellation possible is against `gcd(a.den, b.den)`,
/// which is what makes the two small gcds below enough: the generic
/// `RatFunc + RatFunc` instead reduces the full cross-multiplied product, whose
/// degree is the *sum* of the two denominators'.
pub fn rn_add(a: &Rn, b: &Rn) -> Rn {
    if rn_is_zero(a) {
        return b.clone();
    }
    if rn_is_zero(b) {
        return a.clone();
    }
    let g = if a.den.degree() <= 0 || b.den.degree() <= 0 {
        RatUniPoly::one()
    } else {
        q_gcd(&a.den, &b.den)
    };
    if g.degree() <= 0 {
        // Coprime denominators: the sum is already in lowest terms.
        let num = &(&a.num * &b.den) + &(&b.num * &a.den);
        let den = &a.den * &b.den;
        return rn_from_coprime(num, den);
    }
    let (Some(b1), Some(d1)) = (q_exact_div(&a.den, &g), q_exact_div(&b.den, &g)) else {
        return a.clone() + b.clone();
    };
    // `num/den = (a.num·d1 + b.num·b1) / (a.den·d1)` over the lcm of the two
    // denominators; whatever is left to cancel must divide `g`.
    let num = &(&a.num * &d1) + &(&b.num * &b1);
    if num.is_zero() {
        return rn_zero();
    }
    let den = &a.den * &d1;
    let h = q_gcd(&num, &g);
    if h.degree() > 0 {
        if let (Some(nn), Some(dd)) = (q_exact_div(&num, &h), q_exact_div(&den, &h)) {
            return rn_from_coprime(nn, dd);
        }
    }
    rn_from_coprime(num, den)
}

pub fn rn_neg(a: &Rn) -> Rn {
    -a.clone()
}

pub fn rn_sub(a: &Rn, b: &Rn) -> Rn {
    rn_add(a, &rn_neg(b))
}

/// `a · b`.
///
/// Same canonical-form assumption as [`rn_add`]: with both operands reduced,
/// `gcd(a.num·b.num, a.den·b.den) = gcd(a.num, b.den)·gcd(b.num, a.den)`, so
/// cancelling crosswise *before* multiplying is both cheaper and complete.
pub fn rn_mul(a: &Rn, b: &Rn) -> Rn {
    if rn_is_zero(a) || rn_is_zero(b) {
        return rn_zero();
    }
    let (an, bd) = cross_cancel(&a.num, &b.den);
    let (bn, ad) = cross_cancel(&b.num, &a.den);
    rn_from_coprime(&an * &bn, &ad * &bd)
}

pub fn rn_inv(a: &Rn) -> Option<Rn> {
    if rn_is_zero(a) {
        return None;
    }
    // `a` is reduced, so the reciprocal is too — only the monic normalisation
    // of the new denominator is left to do.
    Some(rn_from_coprime(a.den.clone(), a.num.clone()))
}

/// Divide `gcd(x, y)` out of both, leaving them untouched when it is a unit.
fn cross_cancel(x: &RatUniPoly, y: &RatUniPoly) -> (RatUniPoly, RatUniPoly) {
    if x.degree() <= 0 || y.degree() <= 0 {
        return (x.clone(), y.clone());
    }
    let g = q_gcd(x, y);
    if g.degree() <= 0 {
        return (x.clone(), y.clone());
    }
    match (q_exact_div(x, &g), q_exact_div(y, &g)) {
        (Some(xx), Some(yy)) => (xx, yy),
        _ => (x.clone(), y.clone()),
    }
}

/// Build an `Rn` from an already-coprime pair, normalizing `den` to monic.
fn rn_from_coprime(num: RatUniPoly, den: RatUniPoly) -> Rn {
    let num = num.trim();
    if num.is_zero() {
        return rn_zero();
    }
    let den = den.trim();
    let lc = den.leading_coeff();
    if lc == 1 || den.is_zero() {
        return RatFunc { num, den };
    }
    let inv = Rational::from(1) / lc;
    RatFunc {
        num: scale_ratuni(&num, &inv),
        den: scale_ratuni(&den, &inv),
    }
}

fn scale_ratuni(p: &RatUniPoly, z: &Rational) -> RatUniPoly {
    if p.is_zero() || *z == 1 {
        return p.clone();
    }
    RatUniPoly {
        coeffs: p.coeffs.iter().map(|c| c.clone() * z.clone()).collect(),
    }
    .trim()
}

fn q_exact_div(a: &RatUniPoly, b: &RatUniPoly) -> Option<RatUniPoly> {
    if b.is_zero() {
        return None;
    }
    let (q, r) = RatUniPoly::div_rem(a, b);
    if r.is_zero() {
        Some(q)
    } else {
        None
    }
}

/// Monic gcd in `Q[n]`, computed by the `Z[n]` subresultant PRS.
///
/// `RatUniPoly::gcd` is the naive Euclidean sequence over `Q`, which swells the
/// rational coefficients of every remainder; clearing denominators once and
/// running the subresultant PRS in `Z[n]` keeps the whole computation in
/// integers. The result is the same monic polynomial.
fn q_gcd(a: &RatUniPoly, b: &RatUniPoly) -> RatUniPoly {
    if a.is_zero() {
        return make_monic(b.clone());
    }
    if b.is_zero() {
        return make_monic(a.clone());
    }
    if a.degree() <= 0 || b.degree() <= 0 {
        return RatUniPoly::one();
    }
    let g = IPoly::gcd(&ratuni_to_zpoly(a), &ratuni_to_zpoly(b));
    make_monic(ipoly_to_ratuni(&g))
}

fn make_monic(p: RatUniPoly) -> RatUniPoly {
    let p = p.trim();
    if p.is_zero() {
        return p;
    }
    let lc = p.leading_coeff();
    if lc == 1 {
        return p;
    }
    scale_ratuni(&p, &(Rational::from(1) / lc))
}

/// Clear the rational denominators of a `Q[n]` polynomial, giving a `Z[n]` one
/// that is a rational multiple of it (enough for gcd purposes).
fn ratuni_to_zpoly(p: &RatUniPoly) -> IPoly {
    let mut l = Integer::from(1);
    for c in &p.coeffs {
        l = l.lcm(&c.clone().denom().clone());
    }
    let scaled = scale_ratuni(p, &Rational::from(l));
    IPoly {
        c: scaled
            .coeffs
            .iter()
            .map(|c| c.numer().clone())
            .collect::<Vec<_>>(),
    }
    .trim()
}

pub fn rn_div(a: &Rn, b: &Rn) -> Option<Rn> {
    Some(rn_mul(a, &rn_inv(b)?))
}

pub fn rn_eq(a: &Rn, b: &Rn) -> bool {
    rn_is_zero(&rn_sub(a, b))
}

/// `a(n + i)`.
pub fn rn_shift(a: &Rn, i: i64) -> Rn {
    if i == 0 {
        return a.clone();
    }
    a.compose_affine_arg(&Rational::from(1), &Rational::from(i))
}

fn poly_deriv(p: &RatUniPoly) -> RatUniPoly {
    if p.coeffs.len() <= 1 {
        return RatUniPoly::zero();
    }
    let coeffs: Vec<Rational> = p
        .coeffs
        .iter()
        .enumerate()
        .skip(1)
        .map(|(i, c)| c.clone() * Rational::from(i as i64))
        .collect();
    RatUniPoly { coeffs }.trim()
}

/// `d/dn` of a rational function.
pub fn rn_deriv(a: &Rn) -> Rn {
    let nu = poly_deriv(&a.num);
    let dv = poly_deriv(&a.den);
    let num = &(&nu * &a.den) - &(&a.num * &dv);
    let den = &a.den * &a.den;
    RatFunc { num, den }.normalize()
}

/// `d/dk` of a `Q(n)[k]` polynomial.
///
/// The coefficient field `Q(n)` is *constant* with respect to `k`, so this is
/// the plain power rule with no chain-rule term — which is exactly what makes
/// `Q(n)(k)` a differential field over `Q(n)` and lets the continuous
/// creative-telescoping engine ([`super::azeil`]) reuse this tower unchanged.
pub fn polyk_deriv_k(p: &PolyK) -> PolyK {
    if p.coeffs.len() <= 1 {
        return PolyK::zero();
    }
    let coeffs: Vec<Rn> = p
        .coeffs
        .iter()
        .enumerate()
        .skip(1)
        .map(|(i, c)| rn_mul(c, &rn_int(i as i64)))
        .collect();
    PolyK::from_coeffs(coeffs)
}

/// `d/dk` of a `Q(n)(k)` rational function, by the quotient rule.
pub fn ratk_deriv_k(r: &RatK) -> RatK {
    let nu = polyk_deriv_k(&r.num);
    let dv = polyk_deriv_k(&r.den);
    RatK {
        num: nu.mul(&r.den).sub(&r.num.mul(&dv)),
        den: r.den.mul(&r.den),
    }
    .normalize()
}

fn poly_eval(p: &RatUniPoly, x: &Rational) -> Rational {
    let mut acc = Rational::from(0);
    for c in p.coeffs.iter().rev() {
        acc *= x.clone();
        acc += c.clone();
    }
    acc
}

/// Evaluate at a rational point; `None` at a pole.
pub fn rn_eval(a: &Rn, x: &Rational) -> Option<Rational> {
    let d = poly_eval(&a.den, x);
    if d == 0 {
        return None;
    }
    Some(poly_eval(&a.num, x) / d)
}

/// Clear denominators across a slice of `Q(n)` elements, returning integer
/// primitive polynomials in `n` that are proportional to the input.
///
/// The scaling is common to all entries, so a linear relation with these
/// coefficients holds exactly when it held for the input.
pub fn clear_denominators(items: &[Rn]) -> Vec<RatUniPoly> {
    // Common denominator: product of denominators reduced by pairwise gcd.
    let mut common = RatUniPoly::one();
    for it in items {
        if it.den.is_zero() {
            continue;
        }
        let g = common.gcd(&it.den);
        let (q, _) = RatUniPoly::div_rem(&it.den, &g);
        common = &common * &q;
    }
    let mut out: Vec<RatUniPoly> = Vec::with_capacity(items.len());
    for it in items {
        let (mult, _) = RatUniPoly::div_rem(&common, &it.den);
        out.push((&it.num * &mult).trim());
    }
    make_primitive(&mut out);
    out
}

/// Scale a family of rational polynomials by one common rational so that all
/// coefficients are integers with overall content 1 and a positive leading
/// coefficient on the last non-zero entry.
pub fn make_primitive(polys: &mut [RatUniPoly]) {
    let mut den_lcm = Integer::from(1);
    for p in polys.iter() {
        for c in &p.coeffs {
            den_lcm = den_lcm.lcm(&c.clone().denom().clone());
        }
    }
    let scale = Rational::from(den_lcm);
    for p in polys.iter_mut() {
        for c in p.coeffs.iter_mut() {
            *c *= scale.clone();
        }
    }
    let mut content = Integer::from(0);
    for p in polys.iter() {
        for c in &p.coeffs {
            content = content.gcd(&c.clone().numer().clone());
        }
    }
    if content != 0 && content != 1 {
        let inv = Rational::from((Integer::from(1), content));
        for p in polys.iter_mut() {
            for c in p.coeffs.iter_mut() {
                *c *= inv.clone();
            }
        }
    }
    let sign_ref = polys
        .iter()
        .rev()
        .find(|p| !p.is_zero())
        .map(|p| p.leading_coeff());
    if let Some(lc) = sign_ref {
        if lc < 0 {
            for p in polys.iter_mut() {
                for c in p.coeffs.iter_mut() {
                    *c *= Rational::from(-1);
                }
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Z[n] and Z[n][k] — the integral-domain view that gcd actually runs in
// ---------------------------------------------------------------------------
//
// `Q(n)[k]` is a Euclidean domain, so a gcd *can* be computed by the textbook
// remainder sequence over the field `Q(n)` — and that is what this module used
// to do. It is also the textbook example of intermediate expression swell: each
// `div_rem` step divides by the leading coefficient, so every remainder
// coefficient is a fresh quotient of rational functions in `n` whose numerator
// and denominator degrees add, and nothing ever removes the common content that
// makes them cancel again. On Franel (`Σ_k C(n,k)³`) one such gcd ran for
// eleven seconds.
//
// The classical fix is to leave the field and work in the UFD `Z[n][k]`, where
// the coefficients stay polynomials and the swell is controlled by *dividing
// out the subresultant* at every step (Brown's subresultant PRS: Collins 1967,
// Brown 1971; Knuth, TAOCP vol. 2 § 4.6.1, algorithm C). The gcd over `Q(n)[k]`
// is the gcd over `Z[n][k]` up to a unit of `Q(n)`, which the monic
// normalisation at the end absorbs, so this is the same mathematical object,
// only reachable in milliseconds instead of seconds.

/// Dense univariate polynomial over `Z` in the outer variable `n`, ascending.
#[derive(Clone, Debug, PartialEq, Eq)]
struct IPoly {
    c: Vec<Integer>,
}

impl IPoly {
    fn zero() -> Self {
        IPoly { c: vec![] }
    }

    fn one() -> Self {
        IPoly {
            c: vec![Integer::from(1)],
        }
    }

    fn from_int(i: Integer) -> Self {
        if i == 0 {
            IPoly::zero()
        } else {
            IPoly { c: vec![i] }
        }
    }

    fn is_zero(&self) -> bool {
        self.c.is_empty()
    }

    fn is_one(&self) -> bool {
        self.c.len() == 1 && self.c[0] == 1
    }

    /// Degree, or `-1` for the zero polynomial.
    fn degree(&self) -> i32 {
        self.c.len() as i32 - 1
    }

    fn trim(mut self) -> Self {
        while self.c.last().map(|v| *v == 0).unwrap_or(false) {
            self.c.pop();
        }
        self
    }

    fn lc(&self) -> Integer {
        self.c.last().cloned().unwrap_or_else(|| Integer::from(0))
    }

    fn sub(&self, other: &Self) -> Self {
        let n = self.c.len().max(other.c.len());
        let mut out = Vec::with_capacity(n);
        for i in 0..n {
            let a = self.c.get(i).cloned().unwrap_or_else(|| Integer::from(0));
            let b = other.c.get(i).cloned().unwrap_or_else(|| Integer::from(0));
            out.push(a - b);
        }
        IPoly { c: out }.trim()
    }

    fn mul(&self, other: &Self) -> Self {
        if self.is_zero() || other.is_zero() {
            return IPoly::zero();
        }
        let mut out = vec![Integer::from(0); self.c.len() + other.c.len() - 1];
        for (i, a) in self.c.iter().enumerate() {
            if *a == 0 {
                continue;
            }
            for (j, b) in other.c.iter().enumerate() {
                if *b == 0 {
                    continue;
                }
                out[i + j] += Integer::from(a * b);
            }
        }
        IPoly { c: out }.trim()
    }

    fn scale_int(&self, z: &Integer) -> Self {
        if *z == 0 {
            return IPoly::zero();
        }
        IPoly {
            c: self.c.iter().map(|v| Integer::from(v * z)).collect(),
        }
        .trim()
    }

    fn pow_usize(&self, e: usize) -> Self {
        let mut acc = IPoly::one();
        for _ in 0..e {
            acc = acc.mul(self);
        }
        acc
    }

    /// `x^shift · self`.
    fn shift_pow(&self, shift: usize) -> Self {
        if self.is_zero() || shift == 0 {
            return self.clone();
        }
        let mut c = vec![Integer::from(0); shift];
        c.extend(self.c.iter().cloned());
        IPoly { c }
    }

    /// Non-negative gcd of the coefficients (`0` for the zero polynomial).
    fn content(&self) -> Integer {
        let mut g = Integer::from(0);
        for v in &self.c {
            g = g.gcd(v);
            if g == 1 {
                break;
            }
        }
        g.abs()
    }

    fn div_int_exact(&self, z: &Integer) -> Option<Self> {
        if *z == 0 {
            return None;
        }
        let mut out = Vec::with_capacity(self.c.len());
        for v in &self.c {
            if !v.is_divisible(z) {
                return None;
            }
            out.push(Integer::from(v / z));
        }
        Some(IPoly { c: out }.trim())
    }

    /// Primitive part, normalized to a positive leading coefficient.
    fn primitive_part(&self) -> Self {
        if self.is_zero() {
            return IPoly::zero();
        }
        let mut cont = self.content();
        if self.lc() < 0 {
            cont = -cont;
        }
        self.div_int_exact(&cont).unwrap_or_else(|| self.clone())
    }

    /// Exact division in `Z[n]`; `None` when the quotient is not in `Z[n]`.
    fn exact_div(&self, d: &Self) -> Option<Self> {
        if d.is_zero() {
            return None;
        }
        if self.is_zero() {
            return Some(IPoly::zero());
        }
        let dd = d.degree();
        if self.degree() < dd {
            return None;
        }
        let ld = d.lc();
        let mut rem = self.c.clone();
        let mut q = vec![Integer::from(0); (self.degree() - dd + 1) as usize];
        let mut i = self.degree();
        while i >= dd {
            let lr = rem[i as usize].clone();
            if lr != 0 {
                if !lr.is_divisible(&ld) {
                    return None;
                }
                let t = Integer::from(&lr / &ld);
                let shift = (i - dd) as usize;
                q[shift] = t.clone();
                for (j, dc) in d.c.iter().enumerate() {
                    rem[shift + j] -= Integer::from(&t * dc);
                }
            }
            i -= 1;
        }
        if rem[..dd as usize].iter().any(|v| *v != 0) {
            return None;
        }
        Some(IPoly { c: q }.trim())
    }

    /// Pseudo-remainder: the remainder of `lc(b)^(deg a − deg b + 1)·a` by `b`.
    fn pseudo_rem(a: &Self, b: &Self) -> Self {
        let db = b.degree();
        let mut r = a.clone().trim();
        if r.degree() < db || r.is_zero() {
            return r;
        }
        let lb = b.lc();
        let mut e = (r.degree() - db + 1) as usize;
        while !r.is_zero() && r.degree() >= db {
            let shift = (r.degree() - db) as usize;
            let lr = r.lc();
            r = r.scale_int(&lb).sub(&b.shift_pow(shift).scale_int(&lr));
            e -= 1;
        }
        for _ in 0..e {
            r = r.scale_int(&lb);
        }
        r
    }

    /// gcd in `Z[n]` by subresultant PRS, normalized to a positive leading
    /// coefficient (`0` only when both inputs are `0`).
    fn gcd(a: &Self, b: &Self) -> Self {
        let mut x = a.clone().trim();
        let mut y = b.clone().trim();
        if x.is_zero() {
            return y.primitive_part().scale_int(&y.content());
        }
        if y.is_zero() {
            return x.primitive_part().scale_int(&x.content());
        }
        if x.degree() < y.degree() {
            std::mem::swap(&mut x, &mut y);
        }
        let cx = x.content();
        let cy = y.content();
        let d = Integer::from(cx.gcd_ref(&cy));
        x = x.div_int_exact(&cx).unwrap_or(x);
        y = y.div_int_exact(&cy).unwrap_or(y);
        if y.degree() == 0 {
            return IPoly::from_int(d);
        }
        let mut g = Integer::from(1);
        let mut h = Integer::from(1);
        loop {
            let delta = (x.degree() - y.degree()) as usize;
            let r = IPoly::pseudo_rem(&x, &y);
            if r.is_zero() {
                break;
            }
            if r.degree() == 0 {
                y = IPoly::one();
                break;
            }
            x = y;
            let mut divisor = g.clone();
            for _ in 0..delta {
                divisor *= h.clone();
            }
            y = match r.div_int_exact(&divisor) {
                Some(q) => q,
                // Never expected (the subresultant divides exactly); falling
                // back to the primitive PRS keeps the sequence valid.
                None => r.primitive_part(),
            };
            g = x.lc();
            if delta > 0 {
                let mut gd = Integer::from(1);
                for _ in 0..delta {
                    gd *= g.clone();
                }
                let mut hd = Integer::from(1);
                for _ in 0..(delta - 1) {
                    hd *= h.clone();
                }
                h = if hd != 0 && gd.is_divisible(&hd) {
                    Integer::from(&gd / &hd)
                } else {
                    gd
                };
            }
        }
        y.primitive_part().scale_int(&d)
    }
}

/// Dense polynomial in `k` with `Z[n]` coefficients, ascending in `k`.
#[derive(Clone, Debug)]
struct BiPoly {
    c: Vec<IPoly>,
}

impl BiPoly {
    fn one() -> Self {
        BiPoly {
            c: vec![IPoly::one()],
        }
    }

    fn is_zero(&self) -> bool {
        self.c.iter().all(IPoly::is_zero)
    }

    fn degree(&self) -> i32 {
        let mut d = self.c.len() as i32 - 1;
        while d >= 0 && self.c[d as usize].is_zero() {
            d -= 1;
        }
        d
    }

    fn trim(mut self) -> Self {
        while self.c.last().map(IPoly::is_zero).unwrap_or(false) {
            self.c.pop();
        }
        self
    }

    fn lc(&self) -> IPoly {
        let d = self.degree();
        if d < 0 {
            IPoly::zero()
        } else {
            self.c[d as usize].clone()
        }
    }

    fn scale(&self, z: &IPoly) -> Self {
        if z.is_zero() {
            return BiPoly { c: vec![] };
        }
        BiPoly {
            c: self.c.iter().map(|a| a.mul(z)).collect(),
        }
        .trim()
    }

    fn sub(&self, other: &Self) -> Self {
        let n = self.c.len().max(other.c.len());
        let mut out = Vec::with_capacity(n);
        let zero = IPoly::zero();
        for i in 0..n {
            let a = self.c.get(i).unwrap_or(&zero);
            let b = other.c.get(i).unwrap_or(&zero);
            out.push(a.sub(b));
        }
        BiPoly { c: out }.trim()
    }

    /// `k^shift · self`.
    fn shift_pow(&self, shift: usize) -> Self {
        if shift == 0 || self.is_zero() {
            return self.clone();
        }
        let mut c = vec![IPoly::zero(); shift];
        c.extend(self.c.iter().cloned());
        BiPoly { c }
    }

    /// The `Z[n]`-content: gcd of the coefficients.
    fn content(&self) -> IPoly {
        let mut g = IPoly::zero();
        for a in &self.c {
            g = IPoly::gcd(&g, a);
            if g.is_one() {
                break;
            }
        }
        g
    }

    fn div_coeff_exact(&self, z: &IPoly) -> Option<Self> {
        let mut out = Vec::with_capacity(self.c.len());
        for a in &self.c {
            out.push(a.exact_div(z)?);
        }
        Some(BiPoly { c: out }.trim())
    }

    fn primitive_part(&self) -> Self {
        let cont = self.content();
        if cont.is_zero() || cont.is_one() {
            return self.clone().trim();
        }
        self.div_coeff_exact(&cont)
            .unwrap_or_else(|| self.clone().trim())
    }

    /// Exact division in `Z[n][k]`; `None` when the quotient does not live there.
    fn exact_div(&self, d: &Self) -> Option<Self> {
        if d.is_zero() {
            return None;
        }
        if self.is_zero() {
            return Some(BiPoly { c: vec![] });
        }
        let dd = d.degree();
        let da = self.degree();
        if da < dd {
            return None;
        }
        let ld = d.lc();
        let mut rem: Vec<IPoly> = self.c.clone();
        rem.resize(((da + 1) as usize).max(rem.len()), IPoly::zero());
        let mut q = vec![IPoly::zero(); (da - dd + 1) as usize];
        let mut i = da;
        while i >= dd {
            let lr = rem[i as usize].clone();
            if !lr.is_zero() {
                let t = lr.exact_div(&ld)?;
                let shift = (i - dd) as usize;
                q[shift] = t.clone();
                for (j, dc) in d.c.iter().enumerate() {
                    if dc.is_zero() {
                        continue;
                    }
                    rem[shift + j] = rem[shift + j].sub(&t.mul(dc));
                }
            }
            i -= 1;
        }
        if rem[..dd as usize].iter().any(|v| !v.is_zero()) {
            return None;
        }
        Some(BiPoly { c: q }.trim())
    }

    fn pseudo_rem(a: &Self, b: &Self) -> Self {
        let db = b.degree();
        let mut r = a.clone().trim();
        if r.is_zero() || r.degree() < db {
            return r;
        }
        let lb = b.lc();
        let mut e = (r.degree() - db + 1) as usize;
        while !r.is_zero() && r.degree() >= db {
            let shift = (r.degree() - db) as usize;
            let lr = r.lc();
            r = r.scale(&lb).sub(&b.shift_pow(shift).scale(&lr));
            e -= 1;
        }
        for _ in 0..e {
            r = r.scale(&lb);
        }
        r
    }

    /// gcd in `Z[n][k]` by Brown's subresultant PRS (content handled
    /// separately, as the algorithm requires primitive inputs).
    fn gcd(a: &Self, b: &Self) -> Self {
        let mut x = a.clone().trim();
        let mut y = b.clone().trim();
        if x.is_zero() {
            return y;
        }
        if y.is_zero() {
            return x;
        }
        if x.degree() < y.degree() {
            std::mem::swap(&mut x, &mut y);
        }
        let cx = x.content();
        let cy = y.content();
        let d = IPoly::gcd(&cx, &cy);
        x = x.div_coeff_exact(&cx).unwrap_or(x);
        y = y.div_coeff_exact(&cy).unwrap_or(y);
        if y.degree() == 0 {
            return BiPoly { c: vec![d] };
        }
        let mut g = IPoly::one();
        let mut h = IPoly::one();
        loop {
            let delta = (x.degree() - y.degree()) as usize;
            let r = BiPoly::pseudo_rem(&x, &y);
            if r.is_zero() {
                break;
            }
            if r.degree() == 0 {
                y = BiPoly::one();
                break;
            }
            x = y;
            let divisor = g.mul(&h.pow_usize(delta));
            y = match r.div_coeff_exact(&divisor) {
                Some(q) => q,
                // The subresultant divides exactly in exact arithmetic; the
                // primitive PRS is the safe fallback and stays correct.
                None => r.primitive_part(),
            };
            g = x.lc();
            if delta > 0 {
                let gd = g.pow_usize(delta);
                let hd = h.pow_usize(delta - 1);
                h = gd.exact_div(&hd).unwrap_or(gd);
            }
        }
        y.primitive_part().scale(&d)
    }
}

/// `p` rewritten as `(α / dn(n)) · B(n, k)` with `B ∈ Z[n][k]` and `α ∈ Q`.
///
/// Leaving `Q(n)` for `Z[n][k]` is what makes the gcd below cheap; the scalar
/// `α / dn` is `k`-independent, so it is a unit of `Q(n)` and cannot affect a
/// gcd or a reduced quotient — it is carried along and folded back in at the end.
struct BiForm {
    b: BiPoly,
    alpha: Rational,
    dn: RatUniPoly,
}

fn ratuni_to_ipoly(p: &RatUniPoly) -> Option<IPoly> {
    let mut c = Vec::with_capacity(p.coeffs.len());
    for q in &p.coeffs {
        if *q.clone().denom() != 1 {
            return None;
        }
        c.push(q.numer().clone());
    }
    Some(IPoly { c }.trim())
}

fn ipoly_to_ratuni(p: &IPoly) -> RatUniPoly {
    RatUniPoly {
        coeffs: p.c.iter().map(|v| Rational::from(v.clone())).collect(),
    }
    .trim()
}

fn ipoly_to_rn(p: &IPoly) -> Rn {
    RatFunc::from_poly(ipoly_to_ratuni(p))
}

/// Convert a `Q(n)[k]` polynomial into the integral-domain view.
fn to_biform(p: &PolyK) -> BiForm {
    // Common denominator in `n` across the `k`-coefficients.
    let den_of = |c: &Rn| -> RatUniPoly {
        if c.den.is_zero() {
            RatUniPoly::one()
        } else {
            c.den.clone()
        }
    };
    let mut dn = RatUniPoly::one();
    for c in &p.coeffs {
        if c.num.is_zero() {
            continue;
        }
        let den = den_of(c);
        if den.degree() <= 0 {
            continue;
        }
        let g = dn.gcd(&den);
        let (q, _) = RatUniPoly::div_rem(&den, &g);
        dn = &dn * &q;
    }
    // Numerators over that common denominator: polynomials in `n` over `Q`.
    let mut num_polys: Vec<RatUniPoly> = Vec::with_capacity(p.coeffs.len());
    for c in &p.coeffs {
        if c.num.is_zero() {
            num_polys.push(RatUniPoly::zero());
            continue;
        }
        let (mult, _) = RatUniPoly::div_rem(&dn, &den_of(c));
        num_polys.push((&c.num * &mult).trim());
    }
    // Clear the rational denominators and the integer content, so `B` has
    // integer coefficients: `Σ num_polys[i]·k^i = (cont / lcm)·B`.
    let mut den_lcm = Integer::from(1);
    for q in &num_polys {
        for c in &q.coeffs {
            den_lcm = den_lcm.lcm(&c.clone().denom().clone());
        }
    }
    let mut ints: Vec<IPoly> = Vec::with_capacity(num_polys.len());
    for q in &num_polys {
        let scaled = RatUniPoly {
            coeffs: q
                .coeffs
                .iter()
                .map(|c| c.clone() * Rational::from(den_lcm.clone()))
                .collect(),
        }
        .trim();
        // Exact by construction of `den_lcm`.
        ints.push(ratuni_to_ipoly(&scaled).unwrap_or_else(IPoly::zero));
    }
    let b = BiPoly { c: ints }.trim();
    // Integer content only — the `Z[n]` content is left in place for
    // `BiPoly::gcd`, which has to compute it anyway.
    let mut cont = Integer::from(0);
    for a in &b.c {
        cont = cont.gcd(&a.content());
        if cont == 1 {
            break;
        }
    }
    if cont == 0 {
        cont = Integer::from(1);
    }
    let b = if cont == 1 {
        b
    } else {
        let scaled: Vec<IPoly> =
            b.c.iter()
                .map(|a| a.div_int_exact(&cont).unwrap_or_else(|| a.clone()))
                .collect();
        BiPoly { c: scaled }.trim()
    };
    BiForm {
        b,
        alpha: Rational::from((cont, den_lcm)),
        dn,
    }
}

fn bipoly_to_polyk(b: &BiPoly) -> PolyK {
    PolyK {
        coeffs: b.c.iter().map(ipoly_to_rn).collect(),
    }
    .trim()
}

// ---------------------------------------------------------------------------
// Q(n)[k]
// ---------------------------------------------------------------------------

/// A polynomial in `k` with coefficients in `Q(n)` (ascending order).
#[derive(Clone, Debug)]
pub struct PolyK {
    pub coeffs: Vec<Rn>,
}

impl PolyK {
    pub fn zero() -> Self {
        PolyK { coeffs: vec![] }
    }

    pub fn one() -> Self {
        PolyK {
            coeffs: vec![rn_one()],
        }
    }

    pub fn constant(c: Rn) -> Self {
        PolyK { coeffs: vec![c] }.trim()
    }

    /// The polynomial `k`.
    pub fn k() -> Self {
        PolyK {
            coeffs: vec![rn_zero(), rn_one()],
        }
    }

    pub fn from_coeffs(coeffs: Vec<Rn>) -> Self {
        PolyK { coeffs }.trim()
    }

    pub fn trim(mut self) -> Self {
        while self.coeffs.last().map(rn_is_zero).unwrap_or(false) {
            self.coeffs.pop();
        }
        self
    }

    pub fn is_zero(&self) -> bool {
        self.coeffs.iter().all(rn_is_zero)
    }

    /// Degree, or `-1` for the zero polynomial.
    pub fn degree(&self) -> i32 {
        let mut d = self.coeffs.len() as i32 - 1;
        while d >= 0 && rn_is_zero(&self.coeffs[d as usize]) {
            d -= 1;
        }
        d
    }

    pub fn coeff(&self, i: usize) -> Rn {
        self.coeffs.get(i).cloned().unwrap_or_else(rn_zero)
    }

    pub fn leading_coeff(&self) -> Rn {
        let d = self.degree();
        if d < 0 {
            rn_zero()
        } else {
            self.coeff(d as usize)
        }
    }

    pub fn add(&self, other: &PolyK) -> PolyK {
        let n = self.coeffs.len().max(other.coeffs.len());
        let mut out = Vec::with_capacity(n);
        for i in 0..n {
            out.push(rn_add(&self.coeff(i), &other.coeff(i)));
        }
        PolyK { coeffs: out }.trim()
    }

    pub fn neg(&self) -> PolyK {
        PolyK {
            coeffs: self.coeffs.iter().map(rn_neg).collect(),
        }
    }

    pub fn sub(&self, other: &PolyK) -> PolyK {
        self.add(&other.neg())
    }

    pub fn mul(&self, other: &PolyK) -> PolyK {
        if self.is_zero() || other.is_zero() {
            return PolyK::zero();
        }
        let mut out = vec![rn_zero(); self.coeffs.len() + other.coeffs.len() - 1];
        for (i, a) in self.coeffs.iter().enumerate() {
            if rn_is_zero(a) {
                continue;
            }
            for (j, b) in other.coeffs.iter().enumerate() {
                if rn_is_zero(b) {
                    continue;
                }
                out[i + j] = rn_add(&out[i + j], &rn_mul(a, b));
            }
        }
        PolyK { coeffs: out }.trim()
    }

    pub fn scale(&self, c: &Rn) -> PolyK {
        if rn_is_zero(c) {
            return PolyK::zero();
        }
        PolyK {
            coeffs: self.coeffs.iter().map(|a| rn_mul(a, c)).collect(),
        }
        .trim()
    }

    /// Euclidean division over the field `Q(n)`.
    pub fn div_rem(a: &PolyK, b: &PolyK) -> Option<(PolyK, PolyK)> {
        if b.is_zero() {
            return None;
        }
        let db = b.degree();
        let lb = b.leading_coeff();
        let lb_inv = rn_inv(&lb)?;
        let mut rem = a.clone().trim();
        let mut quot = vec![rn_zero(); ((a.degree() - db).max(-1) + 1).max(0) as usize];
        while rem.degree() >= db && !rem.is_zero() {
            let shift = (rem.degree() - db) as usize;
            let t = rn_mul(&rem.leading_coeff(), &lb_inv);
            if shift >= quot.len() {
                quot.resize(shift + 1, rn_zero());
            }
            quot[shift] = rn_add(&quot[shift], &t);
            let mut sub_coeffs = vec![rn_zero(); shift];
            sub_coeffs.extend(b.coeffs.iter().map(|c| rn_mul(c, &t)));
            let sub = PolyK { coeffs: sub_coeffs };
            rem = rem.sub(&sub);
        }
        Some((PolyK { coeffs: quot }.trim(), rem.trim()))
    }

    pub fn exact_div(a: &PolyK, b: &PolyK) -> Option<PolyK> {
        let (q, r) = PolyK::div_rem(a, b)?;
        if r.is_zero() {
            Some(q)
        } else {
            None
        }
    }

    /// Monic gcd over `Q(n)`.
    pub fn gcd(a: &PolyK, b: &PolyK) -> PolyK {
        let x = a.clone().trim();
        let y = b.clone().trim();
        // Cheap decisions first: they are the majority of the calls made by
        // `RatK::normalize` and by the Gosper normal form's shifted-gcd loop.
        if x.is_zero() && y.is_zero() {
            return PolyK::zero();
        }
        if y.is_zero() {
            return x.monic();
        }
        if x.is_zero() {
            return y.monic();
        }
        if x.degree() == 0 || y.degree() == 0 {
            // A non-zero constant is a unit of `Q(n)[k]`.
            return PolyK::one();
        }
        // Otherwise: subresultant PRS in `Z[n][k]` (see the module section
        // above). The `k`-independent scalars dropped by `to_biform` are units
        // of `Q(n)`, so they cannot change a monic gcd.
        let bx = to_biform(&x);
        let by = to_biform(&y);
        let g = BiPoly::gcd(&bx.b, &by.b);
        if g.degree() <= 0 {
            return PolyK::one();
        }
        bipoly_to_polyk(&g).monic()
    }

    pub fn monic(&self) -> PolyK {
        let lc = self.leading_coeff();
        match rn_inv(&lc) {
            Some(inv) => self.scale(&inv),
            None => self.clone(),
        }
    }

    /// `p(k + j)`.
    pub fn shift_k(&self, j: i64) -> PolyK {
        if j == 0 || self.is_zero() {
            return self.clone().trim();
        }
        let kj = PolyK {
            coeffs: vec![rn_int(j), rn_one()],
        };
        let mut acc = PolyK::zero();
        let mut pow = PolyK::one();
        for c in &self.coeffs {
            acc = acc.add(&pow.scale(c));
            pow = pow.mul(&kj);
        }
        acc.trim()
    }

    /// `p` with `n ↦ n + i` applied to every coefficient.
    pub fn shift_n(&self, i: i64) -> PolyK {
        if i == 0 {
            return self.clone();
        }
        PolyK {
            coeffs: self.coeffs.iter().map(|c| rn_shift(c, i)).collect(),
        }
        .trim()
    }

    pub fn eq_poly(&self, other: &PolyK) -> bool {
        self.sub(other).is_zero()
    }

    /// `lcm` via `a·b/gcd`.
    pub fn lcm(a: &PolyK, b: &PolyK) -> PolyK {
        if a.is_zero() || b.is_zero() {
            return PolyK::zero();
        }
        let g = PolyK::gcd(a, b);
        let prod = a.mul(b);
        PolyK::exact_div(&prod, &g).unwrap_or(prod)
    }
}

// ---------------------------------------------------------------------------
// Q(n)(k)
// ---------------------------------------------------------------------------

/// A rational function in `k` over `Q(n)` — i.e. an element of `Q(n, k)`.
#[derive(Clone, Debug)]
pub struct RatK {
    pub num: PolyK,
    pub den: PolyK,
}

impl RatK {
    pub fn zero() -> Self {
        RatK {
            num: PolyK::zero(),
            den: PolyK::one(),
        }
    }

    pub fn one() -> Self {
        RatK {
            num: PolyK::one(),
            den: PolyK::one(),
        }
    }

    pub fn from_poly(p: PolyK) -> Self {
        RatK {
            num: p,
            den: PolyK::one(),
        }
        .normalize()
    }

    pub fn from_rn(c: Rn) -> Self {
        RatK::from_poly(PolyK::constant(c))
    }

    pub fn k() -> Self {
        RatK::from_poly(PolyK::k())
    }

    pub fn is_zero(&self) -> bool {
        self.num.is_zero()
    }

    pub fn normalize(mut self) -> Self {
        if self.num.is_zero() {
            return RatK::zero();
        }
        if self.den.is_zero() {
            return self;
        }
        // A `k`-constant on either side is a unit of `Q(n)[k]`: there is
        // nothing to cancel, so the gcd is skipped entirely. This is the common
        // case for the small `RatK`s the search manipulates.
        if self.num.degree() > 0 && self.den.degree() > 0 {
            if let Some(reduced) = self.reduce_by_z_gcd() {
                self = reduced;
            }
        }
        // Make the denominator monic in k with a `Q(n)` leading coefficient of 1.
        let lc = self.den.leading_coeff();
        if let Some(inv) = rn_inv(&lc) {
            self.num = self.num.scale(&inv);
            self.den = self.den.scale(&inv);
        }
        self
    }

    /// Cancel `gcd(num, den)` without ever leaving the integral domain.
    ///
    /// The whole reduction — gcd *and* both cofactors — happens in `Z[n][k]`,
    /// so no step ever forms a quotient of rational functions in `n`. `None`
    /// means "nothing to cancel" (the gcd is a unit), which leaves the caller's
    /// representation untouched.
    fn reduce_by_z_gcd(&self) -> Option<RatK> {
        let bn = to_biform(&self.num);
        let bd = to_biform(&self.den);
        let g = BiPoly::gcd(&bn.b, &bd.b);
        if g.degree() <= 0 {
            return None;
        }
        match (bn.b.exact_div(&g), bd.b.exact_div(&g)) {
            (Some(u), Some(v)) => {
                // `num/den = (α_n/dn_n)·U / ((α_d/dn_d)·V) = s·U/V`, with the
                // `k`-independent `s = (α_n·dn_d)/(α_d·dn_n) ∈ Q(n)`.
                let s = rn_mul(
                    &rn_rat(bn.alpha / bd.alpha),
                    &RatFunc {
                        num: bd.dn,
                        den: bn.dn,
                    }
                    .normalize(),
                );
                Some(RatK {
                    num: bipoly_to_polyk(&u).scale(&s),
                    den: bipoly_to_polyk(&v),
                })
            }
            // Not expected (Gauss's lemma puts both cofactors in `Z[n][k]`);
            // dividing in `Q(n)[k]` instead is always exact here.
            _ => {
                let gk = bipoly_to_polyk(&g);
                let u = PolyK::exact_div(&self.num, &gk)?;
                let v = PolyK::exact_div(&self.den, &gk)?;
                Some(RatK { num: u, den: v })
            }
        }
    }

    pub fn add(&self, other: &RatK) -> RatK {
        RatK {
            num: self.num.mul(&other.den).add(&other.num.mul(&self.den)),
            den: self.den.mul(&other.den),
        }
        .normalize()
    }

    pub fn neg(&self) -> RatK {
        RatK {
            num: self.num.neg(),
            den: self.den.clone(),
        }
    }

    pub fn sub(&self, other: &RatK) -> RatK {
        self.add(&other.neg())
    }

    pub fn mul(&self, other: &RatK) -> RatK {
        RatK {
            num: self.num.mul(&other.num),
            den: self.den.mul(&other.den),
        }
        .normalize()
    }

    pub fn inv(&self) -> Option<RatK> {
        if self.num.is_zero() {
            return None;
        }
        Some(
            RatK {
                num: self.den.clone(),
                den: self.num.clone(),
            }
            .normalize(),
        )
    }

    pub fn div(&self, other: &RatK) -> Option<RatK> {
        Some(self.mul(&other.inv()?))
    }

    pub fn pow_i32(&self, e: i32) -> Option<RatK> {
        if e == 0 {
            return Some(RatK::one());
        }
        let base = if e < 0 { self.inv()? } else { self.clone() };
        let mut acc = RatK::one();
        for _ in 0..e.unsigned_abs() {
            acc = acc.mul(&base);
        }
        Some(acc)
    }

    pub fn shift_k(&self, j: i64) -> RatK {
        RatK {
            num: self.num.shift_k(j),
            den: self.den.shift_k(j),
        }
        .normalize()
    }

    pub fn shift_n(&self, i: i64) -> RatK {
        RatK {
            num: self.num.shift_n(i),
            den: self.den.shift_n(i),
        }
        .normalize()
    }

    pub fn eq_ratk(&self, other: &RatK) -> bool {
        self.sub(other).is_zero()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn rn_of(coeffs: &[i64]) -> Rn {
        rn_poly(
            RatUniPoly {
                coeffs: coeffs.iter().map(|c| Rational::from(*c)).collect(),
            }
            .trim(),
        )
    }

    #[test]
    fn rn_basic_field_ops() {
        let n = rn_var();
        let one = rn_one();
        let a = rn_add(&n, &one); // n + 1
        let b = rn_sub(&n, &one); // n - 1
        let prod = rn_mul(&a, &b); // n^2 - 1
        assert!(rn_eq(&prod, &rn_of(&[-1, 0, 1])));
        let q = rn_div(&prod, &a).expect("nonzero divisor");
        assert!(rn_eq(&q, &b));
        assert!(rn_eq(&rn_shift(&n, 2), &rn_of(&[2, 1])));
    }

    #[test]
    fn rn_derivative_and_eval() {
        // d/dn (1/n) = -1/n^2
        let n = rn_var();
        let inv = rn_inv(&n).expect("n != 0");
        let d = rn_deriv(&inv);
        let expected = rn_neg(&rn_inv(&rn_mul(&n, &n)).unwrap());
        assert!(rn_eq(&d, &expected));
        assert_eq!(
            rn_eval(&inv, &Rational::from(4)).unwrap(),
            Rational::from((1, 4))
        );
        assert!(rn_eval(&inv, &Rational::from(0)).is_none());
    }

    #[test]
    fn polyk_div_rem_and_gcd() {
        // (k^2 - 1) = (k - 1)(k + 1)
        let k = PolyK::k();
        let one = PolyK::one();
        let a = k.sub(&one);
        let b = k.add(&one);
        let p = a.mul(&b);
        let (q, r) = PolyK::div_rem(&p, &a).expect("divide");
        assert!(r.is_zero());
        assert!(q.eq_poly(&b));
        let g = PolyK::gcd(&p, &b);
        assert!(g.eq_poly(&b.monic()));
    }

    #[test]
    fn polyk_shift_in_both_variables() {
        // p = k + n  ⇒  p(k+1) = k + n + 1, p with n↦n+1 = k + n + 1
        let p = PolyK::from_coeffs(vec![rn_var(), rn_one()]);
        let want = PolyK::from_coeffs(vec![rn_add(&rn_var(), &rn_one()), rn_one()]);
        assert!(p.shift_k(1).eq_poly(&want));
        assert!(p.shift_n(1).eq_poly(&want));
    }

    #[test]
    fn ratk_arithmetic_is_exact() {
        // 1/(k+n) + 1/(k-n) = 2k/(k^2 - n^2)
        let n = rn_var();
        let kp = PolyK::from_coeffs(vec![n.clone(), rn_one()]);
        let km = PolyK::from_coeffs(vec![rn_neg(&n), rn_one()]);
        let a = RatK::from_poly(kp.clone()).inv().unwrap();
        let b = RatK::from_poly(km.clone()).inv().unwrap();
        let s = a.add(&b);
        let want = RatK {
            num: PolyK::k().scale(&rn_int(2)),
            den: kp.mul(&km),
        }
        .normalize();
        assert!(s.eq_ratk(&want));
    }

    // -----------------------------------------------------------------
    // The `Z[n][k]` gcd against the definition it replaced
    // -----------------------------------------------------------------

    /// The Euclidean remainder sequence over the field `Q(n)` — the textbook
    /// definition of the gcd, and what [`PolyK::gcd`] used to be. Kept here as
    /// the oracle the fast subresultant version is checked against: the two
    /// must agree on the nose, since a monic gcd is unique.
    fn gcd_by_field_euclid(a: &PolyK, b: &PolyK) -> PolyK {
        let mut x = a.clone().trim();
        let mut y = b.clone().trim();
        if x.degree() < y.degree() {
            std::mem::swap(&mut x, &mut y);
        }
        while !y.is_zero() {
            let Some((_, r)) = PolyK::div_rem(&x, &y) else {
                return PolyK::one();
            };
            x = y;
            y = r;
        }
        if x.is_zero() {
            PolyK::zero()
        } else {
            x.monic()
        }
    }

    /// A cheap deterministic stream, so the cases below are reproducible.
    struct Lcg(u64);

    impl Lcg {
        fn next(&mut self) -> u64 {
            self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1);
            self.0 >> 33
        }

        /// A small integer in `[-3, 3]`.
        fn small(&mut self) -> i64 {
            (self.next() % 7) as i64 - 3
        }

        /// A `Q(n)`-coefficient polynomial in `k` of degree `< deg`, with
        /// coefficients that are genuine rational functions of `n`.
        fn poly(&mut self, deg: usize) -> PolyK {
            let mut coeffs = Vec::with_capacity(deg);
            for _ in 0..deg {
                let num = rn_of(&[self.small(), self.small(), self.small()]);
                let den = rn_of(&[self.small(), self.small()]);
                coeffs.push(if rn_is_zero(&den) {
                    num
                } else {
                    rn_div(&num, &den).unwrap()
                });
            }
            PolyK::from_coeffs(coeffs)
        }
    }

    #[test]
    fn gcd_agrees_with_the_field_euclidean_sequence() {
        let mut rng = Lcg(0x5eed_1234);
        for _ in 0..40 {
            let a = rng.poly(3);
            let b = rng.poly(3);
            // Random pairs (usually coprime) *and* pairs with a planted factor,
            // so both the "nothing cancels" and the "something cancels" branch
            // are exercised.
            let g = rng.poly(2);
            for (x, y) in [(a.clone(), b.clone()), (a.mul(&g), b.mul(&g))] {
                let fast = PolyK::gcd(&x, &y);
                let slow = gcd_by_field_euclid(&x, &y);
                assert!(
                    fast.eq_poly(&slow),
                    "gcd mismatch:\n  x = {x:?}\n  y = {y:?}\n  fast = {fast:?}\n  slow = {slow:?}"
                );
            }
        }
    }

    #[test]
    fn gcd_edge_cases_match_the_old_contract() {
        let z = PolyK::zero();
        let one = PolyK::one();
        let p = PolyK::from_coeffs(vec![rn_var(), rn_one()]); // k + n
        assert!(PolyK::gcd(&z, &z).is_zero());
        assert!(PolyK::gcd(&p, &z).eq_poly(&p.monic()));
        assert!(PolyK::gcd(&z, &p).eq_poly(&p.monic()));
        assert!(PolyK::gcd(&p, &one).eq_poly(&one));
        assert!(PolyK::gcd(&p, &p).eq_poly(&p.monic()));
    }

    #[test]
    fn normalize_cancels_a_planted_common_factor_exactly() {
        let mut rng = Lcg(0xfeed_beef);
        for _ in 0..20 {
            let u = rng.poly(3);
            let v = rng.poly(3);
            let g = rng.poly(3);
            if u.is_zero() || v.is_zero() || g.is_zero() {
                continue;
            }
            let r = RatK {
                num: u.mul(&g),
                den: v.mul(&g),
            }
            .normalize();
            // Reduced: nothing left to cancel …
            assert_eq!(
                PolyK::gcd(&r.num, &r.den).degree().max(0),
                0,
                "normalize must leave a reduced fraction"
            );
            // … denominator monic …
            assert!(rn_eq(&r.den.leading_coeff(), &rn_one()));
            // … and still the same element of `Q(n)(k)`.
            let want = RatK {
                num: u.clone(),
                den: v.clone(),
            }
            .normalize();
            assert!(r.eq_ratk(&want));
            assert!(r.num.eq_poly(&want.num) && r.den.eq_poly(&want.den));
        }
    }

    #[test]
    fn rn_arithmetic_matches_the_generic_ratfunc_operators() {
        // `rn_add`/`rn_mul`/`rn_inv` cancel crosswise instead of reducing the
        // full product; the representative they produce must be the same one
        // `RatFunc`'s own (fully normalizing) operators produce.
        let mut rng = Lcg(0x1234_5678);
        for _ in 0..200 {
            let mk = |g: &mut Lcg| {
                let num = rn_of(&[g.small(), g.small(), g.small()]);
                let den = rn_of(&[g.small(), g.small()]);
                if rn_is_zero(&den) {
                    num
                } else {
                    rn_div(&num, &den).unwrap()
                }
            };
            let a = mk(&mut rng);
            let b = mk(&mut rng);
            assert_eq!(rn_add(&a, &b), a.clone() + b.clone());
            assert_eq!(rn_mul(&a, &b), a.mul_ratfunc(&b));
            assert_eq!(rn_inv(&a), a.inv());
        }
    }

    #[test]
    fn q_gcd_matches_the_naive_euclidean_gcd_over_q() {
        let mut rng = Lcg(0x0bad_c0de);
        for _ in 0..100 {
            let mk = |g: &mut Lcg| {
                RatUniPoly {
                    coeffs: (0..4)
                        .map(|_| Rational::from((g.small(), 2)))
                        .collect::<Vec<_>>(),
                }
                .trim()
            };
            let a = mk(&mut rng);
            let b = mk(&mut rng);
            if a.is_zero() || b.is_zero() {
                continue;
            }
            assert_eq!(q_gcd(&a, &b), a.gcd(&b), "a = {a:?}, b = {b:?}");
            let c = &a * &b;
            assert_eq!(q_gcd(&c, &a), c.gcd(&a));
        }
    }

    #[test]
    fn clear_denominators_makes_integer_primitive() {
        let n = rn_var();
        let half = rn_rat(Rational::from((1, 2)));
        let items = vec![rn_mul(&half, &n), rn_div(&rn_one(), &n).unwrap()];
        let out = clear_denominators(&items);
        assert_eq!(out.len(), 2);
        for p in &out {
            for c in &p.coeffs {
                assert_eq!(*c.clone().denom(), Integer::from(1));
            }
        }
    }
}