flint3-sys 3.6.0

Rust bindings to the FLINT C library
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
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
/*
    Copyright (C) 2026 Fredrik Johansson

    This file is part of FLINT.

    FLINT is free software: you can redistribute it and/or modify it under
    the terms of the GNU Lesser General Public License (LGPL) as published
    by the Free Software Foundation; either version 3 of the License, or
    (at your option) any later version.  See <https://www.gnu.org/licenses/>.
*/

#include "padic_radix.h"
#include "fmpz.h"
#include "gr.h"
#include "gr_mat.h"

/* ------------------------------------------------------------------------- */
/*    Internal helpers                                                       */
/* ------------------------------------------------------------------------- */

/*
    Whether |x| < p^k (i.e. x fits in k digits), determined without counting
    digits: we only look at the limb sitting on the digit boundary and compare
    it against the precomputed bound p^(k mod e) (radix->bpow[...]). When k is a
    multiple of e the boundary is a clean limb boundary and no compare is needed.
    Equivalent to radix_integer_size_digits(x) <= k but cheaper.
*/
static int
_radix_integer_fits_digits(const radix_integer_t x, slong k, const radix_t radix)
{
    slong e = radix->exp;
    slong un = FLINT_ABS(x->size);
    slong limbs = k / e;
    slong rem = k - limbs * e;

    if (rem == 0)
        return un <= limbs;
    if (un <= limbs)
        return 1;
    if (un == limbs + 1)
        return x->d[limbs] < radix->bpow[rem];
    return 0;
}

/*
    Compare the nonnegative residues of two nonnegative radix_integers modulo
    p^k, without allocating. Returns 1 if equal, 0 otherwise. Assumes x and y
    have nonnegative size (which holds for all inexact units and for unsigned
    exact units).
*/
static int
_radix_integer_residue_eq_mod(const radix_integer_t x, const radix_integer_t y,
    slong k, const radix_t radix)
{
    slong e = radix->exp;
    slong limbs, rem, i, xs, ys, sig, loop_to;

    if (k <= 0)
        return 1;

    limbs = k / e;
    rem = k - limbs * e;
    xs = x->size;
    ys = y->size;

    /* both operands are zero in every limb at or above sig, so the residues can
       only differ within the first sig limbs; this keeps the work O(unit size)
       even when k (and hence limbs) is enormous. */
    sig = FLINT_MAX(xs, ys);
    loop_to = FLINT_MIN(limbs, sig);

    for (i = 0; i < loop_to; i++)
    {
        ulong xv = (i < xs) ? x->d[i] : 0;
        ulong yv = (i < ys) ? y->d[i] : 0;
        if (xv != yv)
            return 0;
    }

    if (limbs >= sig)
        return 1;                       /* all higher digits (incl. rem) are 0 == 0 */

    if (rem != 0)
    {
        ulong m = radix->bpow[rem];
        ulong xv = (limbs < xs) ? x->d[limbs] : 0;
        ulong yv = (limbs < ys) ? y->d[limbs] : 0;
        xv = n_rem_precomp(xv, m, radix->bpow_div + rem);
        yv = n_rem_precomp(yv, m, radix->bpow_div + rem);
        if (xv != yv)
            return 0;
    }

    return 1;
}

/*
    Whether the unit integers ux, uy (of either sign) are congruent modulo p^k.
    Bounded by the operands' significant size: a nonnegative unit pads its high
    digits with 0 and a negative unit pads with p-1, so once k passes the content
    a sign mismatch is automatically incongruent and matching signs reduce to the
    content. This avoids materialising a residue of ~k digits.
*/
static int
_radix_units_congruent_mod(const radix_integer_t ux, const radix_integer_t uy,
    slong k, const radix_t radix)
{
    slong e = radix->exp;
    slong content;
    int res;
    radix_integer_t rx, ry;

    if (k <= 0)
        return 1;

    if (ux->size >= 0 && uy->size >= 0)
        return _radix_integer_residue_eq_mod(ux, uy, k, radix);

    content = (FLINT_MAX(FLINT_ABS(ux->size), FLINT_ABS(uy->size)) + 1) * e;

    if (k > content)
    {
        if ((ux->size < 0) != (uy->size < 0))
            return 0;                   /* differ in the padding region within p^k */
        k = content;                    /* identical padding: only the content matters */
    }

    /* k is now bounded by 'content' (a few limbs); compare nonnegative residues */
    radix_integer_init(rx, radix);
    radix_integer_init(ry, radix);
    radix_integer_mod_digits(rx, ux, k, radix);
    radix_integer_mod_digits(ry, uy, k, radix);
    res = radix_integer_equal(rx, ry, radix);
    radix_integer_clear(rx, radix);
    radix_integer_clear(ry, radix);
    return res;
}

/*
    Test whether the nonnegative residue of a nonnegative radix_integer u
    modulo p^k equals 1, without allocating.
*/
static int
_radix_integer_residue_is_one_mod(const radix_integer_t u, slong k, const radix_t radix)
{
    slong e = radix->exp;
    slong limbs, rem, i, us;

    if (k <= 0)
        return 1;                 /* everything is congruent mod p^0 */

    limbs = k / e;
    rem = k - limbs * e;
    us = u->size;

    for (i = 0; i < limbs; i++)
    {
        ulong uv = (i < us) ? u->d[i] : 0;
        ulong ov = (i == 0) ? 1 : 0;
        if (uv != ov)
            return 0;
    }

    if (rem != 0)
    {
        ulong m = radix->bpow[rem];
        ulong uv = (limbs < us) ? u->d[limbs] : 0;
        ulong ov = (limbs == 0) ? (UWORD(1) % m) : 0;
        uv = n_rem_precomp(uv, m, radix->bpow_div + rem);
        if (uv != ov)
            return 0;
    }

    return 1;
}

/*
    Test whether the nonnegative residue of a nonnegative radix_integer u
    modulo p^k equals p^k - 1 (i.e. u == -1 mod p^k: every one of the low k
    p-adic digits is p - 1), without allocating.
*/
static int
_radix_integer_residue_is_neg_one_mod(const radix_integer_t u, slong k, const radix_t radix)
{
    slong e = radix->exp;
    slong limbs, rem, i, us;
    ulong full = LIMB_RADIX(radix) - 1;     /* a full limb of (p-1) digits */

    if (k <= 0)
        return 1;

    limbs = k / e;
    rem = k - limbs * e;
    us = u->size;

    for (i = 0; i < limbs; i++)
    {
        ulong uv = (i < us) ? u->d[i] : 0;
        if (uv != full)
            return 0;
    }

    if (rem != 0)
    {
        ulong m = radix->bpow[rem];
        ulong uv = (limbs < us) ? u->d[limbs] : 0;
        uv = n_rem_precomp(uv, m, radix->bpow_div + rem);
        if (uv != m - 1)
            return 0;
    }

    return 1;
}

/* Pull the p-adic valuation of the unit into the exponent v. */
static void
_padic_radix_canonicalise(padic_radix_t x, gr_ctx_t ctx)
{
    radix_struct * radix = PADIC_RADIX_CTX_RADIX(ctx);
    slong w;

    if (x->u.size == 0)
    {
        x->v = 0;
        return;
    }

    w = radix_integer_valuation_digits(&x->u, radix);

    if (w != 0)
    {
        radix_integer_rshift_digits(&x->u, &x->u, w, radix);
        x->v += w;
    }
}

/*
    Target absolute precision for a value of valuation v under the context
    default precisions: min(prec_abs, v + prec_rel), with PREC_INF acting as
    +infinity.
*/
static slong
_padic_radix_target_prec(slong v, gr_ctx_t ctx)
{
    slong a = PADIC_RADIX_CTX_PREC_ABS(ctx);
    slong r = PADIC_RADIX_CTX_PREC_REL(ctx);
    slong t;

    if (r == PADIC_RADIX_PREC_INF)
    {
        t = PADIC_RADIX_PREC_INF;
    }
    else
    {
        /* r is finite and clamped to [0, ERR_MAX]; v is bounded in practice */
        t = v + r;
        if (t < 0 || t > PADIC_RADIX_ERR_MAX)  /* overflow / very large -> treat as inf-ish */
            t = (v >= 0) ? PADIC_RADIX_PREC_INF : t;
    }

    return FLINT_MIN(a, t);
}

/*
    Impose the context precision on a canonical element, truncating when
    required and recording the resulting absolute error. An exact element is
    preserved as exact when its value fits strictly within the target
    precision. Inexact results always use the nonnegative residue.
*/
static void
_padic_radix_reduce(padic_radix_t x, gr_ctx_t ctx)
{
    radix_struct * radix = PADIC_RADIX_CTX_RADIX(ctx);
    slong target, Neff, r;

    if (x->u.size == 0)
    {
        x->v = 0;
        if (x->N != PADIC_RADIX_EXACT)
            x->N = FLINT_MIN(x->N, PADIC_RADIX_ERR_MAX);
        return;
    }

    target = _padic_radix_target_prec(x->v, ctx);
    Neff = (x->N == PADIC_RADIX_EXACT) ? target : FLINT_MIN(x->N, target);

    if (Neff == PADIC_RADIX_PREC_INF)
        return;   /* stays exact */

    r = Neff - x->v;

    if (r <= 0)
    {
        radix_integer_zero(&x->u, radix);
        x->v = 0;
        x->N = FLINT_MIN(Neff, PADIC_RADIX_ERR_MAX);
        return;
    }

    /* exact value that fits: keep it exact (allows signed units) */
    if (x->N == PADIC_RADIX_EXACT && _radix_integer_fits_digits(&x->u, r, radix))
        return;

    /* otherwise the result is inexact: store the nonnegative residue */
    radix_integer_mod_digits(&x->u, &x->u, r, radix);
    if (x->u.size == 0)
        x->v = 0;
    x->N = FLINT_MIN(Neff, PADIC_RADIX_ERR_MAX);
}

/*
    Finish a conversion: a freshly built (possibly signed) canonical element
    with N == EXACT. Handles the unsigned-mode representability of negative
    values and then imposes the context precision.
*/
static int
_padic_radix_finish(padic_radix_t res, gr_ctx_t ctx)
{
    if (res->u.size < 0 && !PADIC_RADIX_CTX_SIGNED(ctx))
    {
        slong target = _padic_radix_target_prec(res->v, ctx);

        if (target == PADIC_RADIX_PREC_INF)
            return GR_UNABLE;   /* no finite residue: cannot represent exactly */

        res->N = target;        /* force inexact; reduce takes the nonneg residue */
    }

    _padic_radix_reduce(res, ctx);
    return GR_SUCCESS;
}

/* ------------------------------------------------------------------------- */
/*    Memory management                                                      */
/* ------------------------------------------------------------------------- */

void
padic_radix_init(padic_radix_t res, gr_ctx_t ctx)
{
    radix_integer_init(&res->u, PADIC_RADIX_CTX_RADIX(ctx));
    res->v = 0;
    res->N = PADIC_RADIX_EXACT;
}

void
padic_radix_clear(padic_radix_t res, gr_ctx_t ctx)
{
    radix_integer_clear(&res->u, PADIC_RADIX_CTX_RADIX(ctx));
}

void
padic_radix_swap(padic_radix_t x, padic_radix_t y, gr_ctx_t ctx)
{
    FLINT_SWAP(padic_radix_struct, *x, *y);
}

void
padic_radix_set_shallow(padic_radix_t res, const padic_radix_t x, gr_ctx_t ctx)
{
    *res = *x;
}

/* ------------------------------------------------------------------------- */
/*    Error term access                                                      */
/* ------------------------------------------------------------------------- */

slong
padic_radix_get_error(const padic_radix_t x, gr_ctx_t ctx)
{
    return x->N;
}

truth_t
padic_radix_is_exact(const padic_radix_t x, gr_ctx_t ctx)
{
    return (x->N == PADIC_RADIX_EXACT) ? T_TRUE : T_FALSE;
}

/* ------------------------------------------------------------------------- */
/*    Assignments                                                            */
/* ------------------------------------------------------------------------- */

int
padic_radix_zero(padic_radix_t res, gr_ctx_t ctx)
{
    radix_integer_zero(&res->u, PADIC_RADIX_CTX_RADIX(ctx));
    res->v = 0;
    res->N = PADIC_RADIX_EXACT;
    return GR_SUCCESS;
}

int
padic_radix_one(padic_radix_t res, gr_ctx_t ctx)
{
    radix_integer_one(&res->u, PADIC_RADIX_CTX_RADIX(ctx));
    res->v = 0;
    res->N = PADIC_RADIX_EXACT;
    _padic_radix_reduce(res, ctx);   /* becomes 0 + O(p^N) if target precision <= 0 */
    return GR_SUCCESS;
}

/* Allows parsing 'O(p^n)' in strings */
static int
padic_radix_big_o_base_fmpz(padic_radix_t res, const padic_radix_t x, const fmpz_t exp, gr_ctx_t ctx)
{
    /* p^exp */
    if (x->v == 1 && radix_integer_is_one(&x->u, PADIC_RADIX_CTX_RADIX(ctx)) && res->N == PADIC_RADIX_EXACT)
    {
        if (fmpz_cmp_si(exp, -PADIC_RADIX_ERR_MAX) >= 0)
        {
            padic_radix_zero(res, ctx);
            res->N = fmpz_cmp_si(exp, PADIC_RADIX_ERR_MAX) <= 0 ? *exp : PADIC_RADIX_ERR_MAX;
            return GR_SUCCESS;
        }
    }

    return GR_UNABLE;
}

int
padic_radix_set(padic_radix_t res, const padic_radix_t x, gr_ctx_t ctx)
{
    if (res != x)
    {
        radix_integer_set(&res->u, &x->u, PADIC_RADIX_CTX_RADIX(ctx));
        res->v = x->v;
        res->N = x->N;
    }

    _padic_radix_reduce(res, ctx);
    return GR_SUCCESS;
}

/*
    exact_set_*: store the exact value, ignoring the context precision (the
    result keeps N == EXACT and is never truncated). The unit may be signed
    regardless of the SIGNED flag, since this is the true value. Fails with
    GR_UNABLE only if the valuation is too large to represent (never in
    practice, as it is bounded by the bit length of the argument).
*/
static int
_padic_radix_exact_set_finish(padic_radix_t res, gr_ctx_t ctx)
{
    _padic_radix_canonicalise(res, ctx);

    if (res->u.size != 0
        && (res->v > PADIC_RADIX_ERR_MAX || res->v < -PADIC_RADIX_ERR_MAX))
        return GR_UNABLE;

    return GR_SUCCESS;
}

int
padic_radix_exact_set_fmpz(padic_radix_t res, const fmpz_t c, gr_ctx_t ctx)
{
    radix_integer_set_fmpz(&res->u, c, PADIC_RADIX_CTX_RADIX(ctx));
    res->v = 0;
    res->N = PADIC_RADIX_EXACT;
    return _padic_radix_exact_set_finish(res, ctx);
}

int
padic_radix_exact_set_ui(padic_radix_t res, ulong c, gr_ctx_t ctx)
{
    radix_integer_set_ui(&res->u, c, PADIC_RADIX_CTX_RADIX(ctx));
    res->v = 0;
    res->N = PADIC_RADIX_EXACT;
    return _padic_radix_exact_set_finish(res, ctx);
}

int
padic_radix_exact_set_si(padic_radix_t res, slong c, gr_ctx_t ctx)
{
    radix_integer_set_si(&res->u, c, PADIC_RADIX_CTX_RADIX(ctx));
    res->v = 0;
    res->N = PADIC_RADIX_EXACT;
    return _padic_radix_exact_set_finish(res, ctx);
}

int
padic_radix_set_fmpz(padic_radix_t res, const fmpz_t c, gr_ctx_t ctx)
{
    int status = padic_radix_exact_set_fmpz(res, c, ctx);
    if (status != GR_SUCCESS)
        return status;
    return _padic_radix_finish(res, ctx);        /* round to context precision */
}

int
padic_radix_set_ui(padic_radix_t res, ulong c, gr_ctx_t ctx)
{
    int status = padic_radix_exact_set_ui(res, c, ctx);
    if (status != GR_SUCCESS)
        return status;
    return _padic_radix_finish(res, ctx);
}

int
padic_radix_set_si(padic_radix_t res, slong c, gr_ctx_t ctx)
{
    int status = padic_radix_exact_set_si(res, c, ctx);
    if (status != GR_SUCCESS)
        return status;
    return _padic_radix_finish(res, ctx);
}

int
padic_radix_get_fmpz(fmpz_t res, const padic_radix_t x, gr_ctx_t ctx)
{
    radix_struct * radix = PADIC_RADIX_CTX_RADIX(ctx);

    if (x->N != PADIC_RADIX_EXACT)
        return GR_UNABLE;       /* not a definite integer */

    if (x->v < 0)
        return GR_DOMAIN;       /* genuine p-adic non-integer */

    if (x->u.size == 0)
    {
        fmpz_zero(res);
        return GR_SUCCESS;
    }

    if (x->v > ctx->size_limit)
        return GR_UNABLE;

    radix_integer_get_fmpz(res, &x->u, radix);

    if (x->v != 0)
    {
        fmpz_t t;
        fmpz_init(t);
        fmpz_ui_pow_ui(t, GR_PADIC_RADIX_CTX(ctx)->p, x->v);
        fmpz_mul(res, res, t);
        fmpz_clear(t);
    }

    return GR_SUCCESS;
}

/* ------------------------------------------------------------------------- */
/*    Arithmetic                                                             */
/* ------------------------------------------------------------------------- */

int
padic_radix_neg(padic_radix_t res, const padic_radix_t x, gr_ctx_t ctx)
{
    radix_struct * radix = PADIC_RADIX_CTX_RADIX(ctx);

    if (res != x)
        padic_radix_set(res, x, ctx);

    radix_integer_neg(&res->u, &res->u, radix);

    if (res->N == PADIC_RADIX_EXACT)
        return _padic_radix_finish(res, ctx);

    /* inexact: re-normalise to the nonnegative residue at precision N */
    {
        slong r = res->N - res->v;

        if (r <= 0)
        {
            radix_integer_zero(&res->u, radix);
            res->v = 0;
        }
        else
        {
            radix_integer_mod_digits(&res->u, &res->u, r, radix);
            if (res->u.size == 0)
                res->v = 0;
        }
    }

    return GR_SUCCESS;
}

/*
    Finalize a result whose unit is ALREADY canonical (valuation 0, i.e. its
    lowest digit is a p-adic unit) -- as produced by multiplication, inversion,
    division, and addition/subtraction when the operand valuations differ. Skips
    the canonicalisation scan that _padic_radix_finalize performs.
*/
static int
_padic_radix_finalize_assume_canonical(padic_radix_t res, gr_ctx_t ctx)
{
    radix_struct * radix = PADIC_RADIX_CTX_RADIX(ctx);

    /*
        Enforce the representability invariant |v| <= ERR_MAX and (N == EXACT
        or |N| <= ERR_MAX). Keeping both exponents within ERR_MAX = WORD_MAX/4
        guarantees that the sums formed by add/sub/mul (v_x + v_y, v_y + N_x,
        ...) never overflow a signed word.
    */
    if (res->N != PADIC_RADIX_EXACT)
    {
        if (res->N < -PADIC_RADIX_ERR_MAX)
            return GR_UNABLE;                       /* precision too low to represent */
        if (res->N > PADIC_RADIX_ERR_MAX)
            res->N = PADIC_RADIX_ERR_MAX;           /* clamp down: always sound */
    }

    if (res->u.size != 0)
    {
        if (res->v > PADIC_RADIX_ERR_MAX)
        {
            /* u * p^v with v > ERR_MAX is == 0 modulo p^ERR_MAX */
            slong newN = (res->N == PADIC_RADIX_EXACT)
                       ? PADIC_RADIX_ERR_MAX
                       : FLINT_MIN(res->N, PADIC_RADIX_ERR_MAX);
            radix_integer_zero(&res->u, radix);
            res->v = 0;
            res->N = newN;                          /* now finite */
        }
        else if (res->v < -PADIC_RADIX_ERR_MAX)
        {
            return GR_UNABLE;                       /* valuation too small to represent */
        }
    }

    if (res->N == PADIC_RADIX_EXACT)
        return _padic_radix_finish(res, ctx);

    _padic_radix_reduce(res, ctx);
    return GR_SUCCESS;
}

int
_padic_radix_finalize(padic_radix_t res, gr_ctx_t ctx)
{
    _padic_radix_canonicalise(res, ctx);
    return _padic_radix_finalize_assume_canonical(res, ctx);
}

/*
    Reference (unoptimized) add/sub: aligns the higher-valuation operand into a
    temporary and lets the finalizer reduce/truncate. Kept as a correctness oracle
    for the optimized _padic_radix_add_sub below (the test suite cross-checks the
    two). res = x + y, with sub != 0 selecting x - y.
*/
int
_padic_radix_add_sub_reference(padic_radix_t res, const padic_radix_t x,
    const padic_radix_t y, int sub, gr_ctx_t ctx)
{
    radix_struct * radix = PADIC_RADIX_CTX_RADIX(ctx);
    slong vx = x->v, vy = y->v, Nx = x->N, Ny = y->N;
    slong vmin = FLINT_MIN(vx, vy);
    slong vmax = FLINT_MAX(vx, vy);
    slong Nz, target, P, Nresult;
    radix_integer_t T;

    /* sum is known modulo p^min(Nx, Ny); EXACT == WORD_MAX acts as +inf */
    Nz = FLINT_MIN(Nx, Ny);

    /*
        Effective absolute precision we actually need to compute: the error
        bound capped by the context rounding precision. Anything at or above
        p^P is invisible in the result, so an operand whose valuation reaches P
        contributes nothing and must NOT be aligned by shifting (the shift
        v_hi - v_min could be astronomically large, e.g. ERR_MAX digits). P ==
        PREC_INF means a genuinely exact computation with no cap.
    */
    target = _padic_radix_target_prec(vmin, ctx);
    if (Nz == PADIC_RADIX_EXACT)
        P = target;
    else if (target == PADIC_RADIX_PREC_INF)
        P = Nz;
    else
        P = FLINT_MIN(Nz, target);

    /*
        Zero operands: the result is the other operand (no shift needed). This
        must be handled before the horizon optimisation below, which assumes
        the lower-valuation operand is nonzero (otherwise the result valuation
        is not v_min and an operand could be dropped incorrectly).
    */
    if (x->u.size == 0 || y->u.size == 0)
    {
        if (x->u.size == 0 && y->u.size == 0)
        {
            radix_integer_zero(&res->u, radix);
            res->v = 0;
        }
        else if (x->u.size == 0)
        {
            if (sub)
                radix_integer_neg(&res->u, &y->u, radix);
            else
                radix_integer_set(&res->u, &y->u, radix);
            res->v = vy;
        }
        else
        {
            radix_integer_set(&res->u, &x->u, radix);
            res->v = vx;
        }
        res->N = Nz;
        /* result is the other operand's (already canonical) unit, or zero */
        return _padic_radix_finalize_assume_canonical(res, ctx);
    }

    /* whole result is below the precision horizon: it is 0 + O(p^P) */
    if (P != PADIC_RADIX_PREC_INF && vmin >= P)
    {
        radix_integer_zero(&res->u, radix);
        res->v = 0;
        res->N = P;                 /* known only modulo p^P (P <= Nz) */
        return _padic_radix_finalize_assume_canonical(res, ctx);   /* zero is canonical */
    }

    /*
        Equal valuations: the sum/difference can be written straight into the
        result unit (no temporary needed, even when res aliases x or y, since
        radix_integer_add/sub handle that). The leading digits may cancel, so
        this is the one case that still needs a canonicalising scan.
    */
    if (vx == vy)
    {
        if (sub)
            radix_integer_sub(&res->u, &x->u, &y->u, radix);
        else
            radix_integer_add(&res->u, &x->u, &y->u, radix);
        res->v = vmin;
        res->N = Nz;
        return _padic_radix_finalize(res, ctx);
    }

    radix_integer_init(T, radix);

    Nresult = Nz;

    if (P != PADIC_RADIX_PREC_INF && vmax >= P)
    {
        /* both operands nonzero, so the result has valuation v_min; the
           higher-valuation operand is negligible modulo p^P and is dropped.
           The dropped digits mean the result is now known only modulo p^P.
           No shift is needed, so this writes the surviving operand straight
           into res->u (radix_integer_set/neg handle res aliasing it). */
        Nresult = P;
        if (vx < vy)
        {
            radix_integer_set(&res->u, &x->u, radix);    /* result ~ x */
        }
        else
        {
            if (sub)
                radix_integer_neg(&res->u, &y->u, radix);    /* x - y, x negligible -> -y */
            else
                radix_integer_set(&res->u, &y->u, radix);
        }
    }
    else if (vx < vy)
    {
        /* T holds the aligned higher-valuation operand; the combination is
           written directly into res->u (safe even when res aliases x or y:
           T is a distinct buffer and the integer add/sub handle in-place). */
        radix_integer_lshift_digits(T, &y->u, vmax - vmin, radix);
        if (sub)
            radix_integer_sub(&res->u, &x->u, T, radix);
        else
            radix_integer_add(&res->u, &x->u, T, radix);
    }
    else
    {
        radix_integer_lshift_digits(T, &x->u, vmax - vmin, radix);
        if (sub)
            radix_integer_sub(&res->u, T, &y->u, radix);
        else
            radix_integer_add(&res->u, T, &y->u, radix);
    }

    radix_integer_clear(T, radix);

    res->v = vmin;
    res->N = Nresult;

    /*
        With differing valuations the low digit of the result is the low digit
        of the lower-valuation operand (a unit), so the result is already
        canonical and needs no canonicalisation.
    */
    return _padic_radix_finalize_assume_canonical(res, ctx);
}

/*
    res = x + y (sub != 0 selects x - y), optimized.

    Identical in behaviour to _padic_radix_add_sub_reference, but the
    differing-valuation alignment is done in place with the fused
    radix_integer_addlsh / radix_integer_sublsh, eliminating the temporary that
    the reference allocates to hold the shifted higher-valuation operand.

    With v_x < v_y the lower operand is x, the result is x_unit +/- (y_unit << d);
    with v_x > v_y the lower operand is y, the result is (x_unit << d) +/- y_unit.
    Writing lo / hi for the lower / higher valuation operand and d = |v_x - v_y|,
    addition is always lo + (hi << d). Subtraction is lo - (hi << d) when x is the
    lower operand, and -(lo - (hi << d)) = (hi << d) - lo when y is, so in the
    latter case we negate the fused difference.
*/
static int
_padic_radix_add_sub(padic_radix_t res, const padic_radix_t x,
    const padic_radix_t y, int sub, gr_ctx_t ctx)
{
    radix_struct * radix = PADIC_RADIX_CTX_RADIX(ctx);
    slong vx = x->v, vy = y->v, Nx = x->N, Ny = y->N;
    slong vmin = FLINT_MIN(vx, vy);
    slong vmax = FLINT_MAX(vx, vy);
    slong Nz, target, P, Nresult;

    Nz = FLINT_MIN(Nx, Ny);

    target = _padic_radix_target_prec(vmin, ctx);
    if (Nz == PADIC_RADIX_EXACT)
        P = target;
    else if (target == PADIC_RADIX_PREC_INF)
        P = Nz;
    else
        P = FLINT_MIN(Nz, target);

    /* zero operands: result is the other operand */
    if (x->u.size == 0 || y->u.size == 0)
    {
        if (x->u.size == 0 && y->u.size == 0)
        {
            radix_integer_zero(&res->u, radix);
            res->v = 0;
        }
        else if (x->u.size == 0)
        {
            if (sub)
                radix_integer_neg(&res->u, &y->u, radix);
            else
                radix_integer_set(&res->u, &y->u, radix);
            res->v = vy;
        }
        else
        {
            radix_integer_set(&res->u, &x->u, radix);
            res->v = vx;
        }
        res->N = Nz;
        return _padic_radix_finalize_assume_canonical(res, ctx);
    }

    /* whole result below the precision horizon: 0 + O(p^P) */
    if (P != PADIC_RADIX_PREC_INF && vmin >= P)
    {
        radix_integer_zero(&res->u, radix);
        res->v = 0;
        res->N = P;
        return _padic_radix_finalize_assume_canonical(res, ctx);
    }

    /* equal valuations: combine straight into res (cancellation possible). */
    if (vx == vy)
    {
        if (sub)
            radix_integer_sub(&res->u, &x->u, &y->u, radix);
        else
            radix_integer_add(&res->u, &x->u, &y->u, radix);
        res->v = vmin;
        res->N = Nz;
        return _padic_radix_finalize(res, ctx);
    }

    Nresult = Nz;

    if (P != PADIC_RADIX_PREC_INF && vmax >= P)
    {
        /* higher-valuation operand is negligible modulo p^P; drop it (no shift). */
        Nresult = P;
        if (vx < vy)
        {
            radix_integer_set(&res->u, &x->u, radix);
        }
        else
        {
            if (sub)
                radix_integer_neg(&res->u, &y->u, radix);
            else
                radix_integer_set(&res->u, &y->u, radix);
        }
    }
    else
    {
        /* align in place via the fused shift, no temporary. lo / hi are the
           lower / higher valuation operands; d is the digit gap. */
        const padic_radix_struct * lo = (vx < vy) ? x : y;
        const padic_radix_struct * hi = (vx < vy) ? y : x;
        slong d = vmax - vmin;
        int negate = (sub && vx > vy);    /* x - y with y the lower operand */

        if (sub)
            radix_integer_sublsh(&res->u, &lo->u, &hi->u, d, radix);
        else
            radix_integer_addlsh(&res->u, &lo->u, &hi->u, d, radix);

        if (negate)
            radix_integer_neg(&res->u, &res->u, radix);
    }

    res->v = vmin;
    res->N = Nresult;

    /* low digit is the lower-valuation operand's (a unit): already canonical. */
    return _padic_radix_finalize_assume_canonical(res, ctx);
}

int
padic_radix_add(padic_radix_t res, const padic_radix_t x, const padic_radix_t y, gr_ctx_t ctx)
{
    return _padic_radix_add_sub(res, x, y, 0, ctx);
}

int
padic_radix_sub(padic_radix_t res, const padic_radix_t x, const padic_radix_t y, gr_ctx_t ctx)
{
    return _padic_radix_add_sub(res, x, y, 1, ctx);
}

/*
    Reference (unoptimized) multiplication: forms the full product of the units
    and lets the finalizer reduce/truncate. Kept as a correctness oracle for the
    optimized padic_radix_mul below (the test suite cross-checks the two). The
    unit product of two canonical units is itself canonical, so this uses the
    canonical-assuming finalizer.
*/
int
_padic_radix_mul_reference(padic_radix_t res, const padic_radix_t x, const padic_radix_t y, gr_ctx_t ctx)
{
    radix_struct * radix = PADIC_RADIX_CTX_RADIX(ctx);
    slong vx = x->v, vy = y->v, Nx = x->N, Ny = y->N;
    slong vz, Nz;
    radix_integer_t U;

    /* an exact zero annihilates exactly, even against an inexact factor */
    if ((x->u.size == 0 && Nx == PADIC_RADIX_EXACT)
     || (y->u.size == 0 && Ny == PADIC_RADIX_EXACT))
        return padic_radix_zero(res, ctx);

    vz = vx + vy;

    Nz = PADIC_RADIX_EXACT;
    if (Nx != PADIC_RADIX_EXACT)
        Nz = FLINT_MIN(Nz, vy + Nx);
    if (Ny != PADIC_RADIX_EXACT)
        Nz = FLINT_MIN(Nz, vx + Ny);

    radix_integer_init(U, radix);
    radix_integer_mul(U, &x->u, &y->u, radix);

    FLINT_SWAP(radix_integer_struct, res->u, *U);
    res->v = vz;
    res->N = Nz;

    radix_integer_clear(U, radix);

    return _padic_radix_finalize_assume_canonical(res, ctx);
}

/*
    res = x * y, with truncating multiplication.

    The product unit u_x * u_y has valuation v_z = v_x + v_y and is needed only
    to the result's absolute precision; we therefore compute it with
    radix_integer_mullow_limbs to just the required number of limbs rather than
    forming the full product (cf. the reference above). The unit product of two
    canonical units is canonical, so no canonicalisation is needed.

    The error term N_z = min(v_y + N_x, v_x + N_y) (an exact factor contributing
    no error). When both inputs are exact the product may still be exact, so we
    detect that and avoid introducing an error radius unnecessarily, using the
    operand sizes:
      - if the product certainly fits the target ((xn+yn)*e <= digits), keep it
        exact (full product, no reduction);
      - if it certainly overflows ((xn+yn-1)*e + 1 > digits), it is inexact, so
        truncate to ceil(digits/e) limbs;
      - otherwise (a one-limb-wide borderline) form the full product and let the
        reducer's fits test decide.
    When an input is inexact the result is always inexact, and we truncate to the
    ceil(r/e) limbs that survive reduction (r = relative precision in digits).

    The final reduction/representability handling is shared with the reference
    via _padic_radix_finalize_assume_canonical.
*/
int
padic_radix_mul(padic_radix_t res, const padic_radix_t x, const padic_radix_t y, gr_ctx_t ctx)
{
    radix_struct * radix = PADIC_RADIX_CTX_RADIX(ctx);
    slong e = radix->exp;
    slong vx = x->v, vy = y->v, Nx = x->N, Ny = y->N;
    slong vz, Nz, xn, yn, target;

    //return _padic_radix_mul_reference(res, x, y, ctx);

    /* an exact zero annihilates exactly */
    if ((x->u.size == 0 && Nx == PADIC_RADIX_EXACT)
     || (y->u.size == 0 && Ny == PADIC_RADIX_EXACT))
        return padic_radix_zero(res, ctx);

    vz = vx + vy;

    Nz = PADIC_RADIX_EXACT;
    if (Nx != PADIC_RADIX_EXACT)
        Nz = FLINT_MIN(Nz, vy + Nx);
    if (Ny != PADIC_RADIX_EXACT)
        Nz = FLINT_MIN(Nz, vx + Ny);

    /* inexact zero operand: the product unit is zero */
    if (x->u.size == 0 || y->u.size == 0)
    {
        radix_integer_zero(&res->u, radix);
        res->v = vz;
        res->N = Nz;
        return _padic_radix_finalize_assume_canonical(res, ctx);
    }

    xn = FLINT_ABS(x->u.size);
    yn = FLINT_ABS(y->u.size);
    target = _padic_radix_target_prec(vz, ctx);

    /*
        The product is written straight into res->u. All scalar operand fields
        (vx, vy, Nx, Ny, xn, yn) are captured above, and radix_integer_mul /
        radix_integer_mullow_limbs handle res aliasing x or y, so no temporary
        is required.
    */
    if (Nz == PADIC_RADIX_EXACT)
    {
        /* both inputs exact */
        if (target == PADIC_RADIX_PREC_INF)
        {
            radix_integer_mul(&res->u, &x->u, &y->u, radix);   /* exact ring: full product */
            res->N = PADIC_RADIX_EXACT;
        }
        else
        {
            slong digits = target - vz;                    /* exact digits permitted */
            slong maxD = (xn + yn) * e;                    /* upper bound on product digits */
            slong minD = (xn + yn - 2) * e + 1;            /* lower bound on product digits */

            if (digits <= 0)
            {
                radix_integer_zero(&res->u, radix);        /* below the horizon: 0 + O(p^target) */
                res->N = target;
            }
            else if (maxD <= digits)
            {
                radix_integer_mul(&res->u, &x->u, &y->u, radix); /* certainly fits: exact */
                res->N = PADIC_RADIX_EXACT;
            }
            else if (minD > digits)
            {
                slong n = (digits + e - 1) / e;            /* certainly inexact: truncate */
                radix_integer_mullow_limbs(&res->u, &x->u, &y->u, n, radix);
                res->N = target;
            }
            else
            {
                radix_integer_mul(&res->u, &x->u, &y->u, radix); /* borderline: reducer decides */
                res->N = PADIC_RADIX_EXACT;
            }
        }
    }
    else
    {
        /* at least one inexact input: the product is inexact */
        slong Neff = (target == PADIC_RADIX_PREC_INF) ? Nz : FLINT_MIN(Nz, target);
        slong r = Neff - vz;                               /* surviving digits */

        if (r <= 0)
        {
            radix_integer_zero(&res->u, radix);
            res->N = Neff;
        }
        else
        {
            slong n = (r + e - 1) / e;
            radix_integer_mullow_limbs(&res->u, &x->u, &y->u, n, radix);
            res->N = Nz;                                   /* reducer recomputes Neff & truncates */
        }
    }

    res->v = vz;

    return _padic_radix_finalize_assume_canonical(res, ctx);
}

/* ------------------------------------------------------------------------- */
/*    Division                                                               */
/* ------------------------------------------------------------------------- */

/*
    res = a / b. The divisor b must be checked for being zero by the caller's
    contract: a definite zero gives GR_DOMAIN, an unknown-zero gives GR_UNABLE.
    For two exact inputs whose units divide over Z the quotient is returned
    exactly; otherwise the unit inverse is computed to the working precision.
*/
static int
_padic_radix_div(padic_radix_t res, const padic_radix_t a, const padic_radix_t b, gr_ctx_t ctx)
{
    radix_struct * radix = PADIC_RADIX_CTX_RADIX(ctx);
    slong e = radix->exp;
    slong va = a->v, vb = b->v, Na = a->N, Nb = b->N;
    slong prec_abs = PADIC_RADIX_CTX_PREC_ABS(ctx);
    slong prec_rel = PADIC_RADIX_CTX_PREC_REL(ctx);
    slong vq, rel_a, rel_b, rel, relcap, krel, nlimbs;
    radix_integer_t unit;
    truth_t bz;
    int invertible;

    bz = padic_radix_is_zero(b, ctx);
    if (bz == T_TRUE)
        return GR_DOMAIN;                       /* division by zero */
    if (bz == T_UNKNOWN)
        return GR_UNABLE;                        /* divisor not known to be nonzero */

    /* b is definitely nonzero, so its unit is a genuine p-adic unit */

    if (a->u.size == 0 && Na == PADIC_RADIX_EXACT)
        return padic_radix_zero(res, ctx);       /* exact 0 / b = exact 0 */

    vq = va - vb;

    /* exact / exact: return an exact quotient when the units divide over Z.

       TODO: depending on the operand sizes this exactness test may be better
       performed as a Hensel division with remainder (radix_divmod_bn with a
       non-NULL rem) rather than a Euclidean division. */
    if (Na == PADIC_RADIX_EXACT && Nb == PADIC_RADIX_EXACT)
    {
        radix_integer_t qint;
        int divides;

        radix_integer_init(qint, radix);
        divides = radix_integer_div(qint, &a->u, &b->u, radix);

        if (divides)
        {
            FLINT_SWAP(radix_integer_struct, res->u, *qint);
            res->v = vq;
            res->N = PADIC_RADIX_EXACT;
            radix_integer_clear(qint, radix);
            return _padic_radix_finalize_assume_canonical(res, ctx);
        }

        radix_integer_clear(qint, radix);
        /* fall through: infinite expansion, truncate to context precision */
    }

    /* relative precision of the quotient = min of the operand relative
       precisions, then capped by the context precisions */
    rel_a = (Na == PADIC_RADIX_EXACT) ? PADIC_RADIX_PREC_INF : (Na - va);
    rel_b = (Nb == PADIC_RADIX_EXACT) ? PADIC_RADIX_PREC_INF : (Nb - vb);
    rel = FLINT_MIN(rel_a, rel_b);

    relcap = PADIC_RADIX_PREC_INF;
    if (prec_rel != PADIC_RADIX_PREC_INF)
        relcap = prec_rel;
    if (prec_abs != PADIC_RADIX_PREC_INF)
    {
        slong c = prec_abs - vq;                 /* bounded: no overflow */
        relcap = (relcap == PADIC_RADIX_PREC_INF) ? c : FLINT_MIN(relcap, c);
    }

    if (rel == PADIC_RADIX_PREC_INF && relcap == PADIC_RADIX_PREC_INF)
        return GR_UNABLE;                        /* exact ring, infinite expansion */

    if (rel == PADIC_RADIX_PREC_INF)
        krel = relcap;
    else if (relcap == PADIC_RADIX_PREC_INF)
        krel = rel;
    else
        krel = FLINT_MIN(rel, relcap);

    if (krel > PADIC_RADIX_ERR_MAX)
        krel = PADIC_RADIX_ERR_MAX;              /* never compute more than we can store */

    if (krel <= 0)
    {
        /* quotient valuation is at/below the precision horizon */
        radix_integer_zero(&res->u, radix);
        res->v = 0;
        res->N = vq + krel;                      /* bounded; finalize clamps */
        return _padic_radix_finalize_assume_canonical(res, ctx);
    }

    nlimbs = (krel + e - 1) / e;                 /* digits -> limbs (ceil) */

    radix_integer_init(unit, radix);

    if (a->u.size == 0)
    {
        /* a is an inexact zero: the quotient unit is zero. */
        radix_integer_zero(unit, radix);
        invertible = 1;                          /* b is a genuine unit */
    }
    else
    {
        slong an = FLINT_MIN(FLINT_ABS(a->u.size), nlimbs);
        slong bn = FLINT_MIN(FLINT_ABS(b->u.size), nlimbs);
        slong sgn = a->u.size ^ b->u.size;
        slong rn = nlimbs;
        nn_ptr ud = radix_integer_fit_limbs(unit, nlimbs, radix);

        invertible = radix_divmod_bn(ud, NULL, a->u.d, an, b->u.d, bn, nlimbs, radix);

        if (invertible)
        {
            MPN_NORM(ud, rn);
            unit->size = (sgn >= 0) ? rn : -rn;
        }
    }

    if (!invertible)
    {
        radix_integer_clear(unit, radix);
        return GR_UNABLE;                        /* defensive: should not happen */
    }

    FLINT_SWAP(radix_integer_struct, res->u, *unit);
    res->v = vq;
    res->N = vq + krel;                          /* bounded; finalize clamps + truncates */

    radix_integer_clear(unit, radix);

    return _padic_radix_finalize_assume_canonical(res, ctx);
}

int
padic_radix_div(padic_radix_t res, const padic_radix_t x, const padic_radix_t y, gr_ctx_t ctx)
{
    return _padic_radix_div(res, x, y, ctx);
}

int
padic_radix_inv(padic_radix_t res, const padic_radix_t x, gr_ctx_t ctx)
{
    radix_struct * radix = PADIC_RADIX_CTX_RADIX(ctx);
    slong e = radix->exp;
    slong vx = x->v, Nx = x->N;
    slong prec_abs = PADIC_RADIX_CTX_PREC_ABS(ctx);
    slong prec_rel = PADIC_RADIX_CTX_PREC_REL(ctx);
    slong vq, rel, relcap, krel, nlimbs;
    truth_t xz;
    int invertible;

    xz = padic_radix_is_zero(x, ctx);
    if (xz == T_TRUE)
        return GR_DOMAIN;                        /* 1 / 0 */
    if (xz == T_UNKNOWN)
        return GR_UNABLE;                        /* x not known to be nonzero */

    /* x is a genuine p-adic unit times p^vx, so 1/x has valuation -vx. */
    vq = -vx;

    /* The only units that invert exactly over Z are +-1; an exact such x gives
       an exact +-p^{-vx}. Any other unit inverts to an infinite expansion,
       handled by truncation to the context precision below. */
    if (Nx == PADIC_RADIX_EXACT && FLINT_ABS(x->u.size) == 1 && x->u.d[0] == 1)
    {
        radix_integer_fit_limbs(&res->u, 1, radix)[0] = 1;
        res->u.size = (x->u.size > 0) ? 1 : -1;
        res->v = vq;
        res->N = PADIC_RADIX_EXACT;
        return _padic_radix_finalize_assume_canonical(res, ctx);
    }

    /* relative precision of 1/x equals that of x, capped by the context
       precisions (mirrors _padic_radix_div with an exact unit numerator). */
    rel = (Nx == PADIC_RADIX_EXACT) ? PADIC_RADIX_PREC_INF : (Nx - vx);

    relcap = PADIC_RADIX_PREC_INF;
    if (prec_rel != PADIC_RADIX_PREC_INF)
        relcap = prec_rel;
    if (prec_abs != PADIC_RADIX_PREC_INF)
    {
        slong c = prec_abs - vq;                 /* bounded: no overflow */
        relcap = (relcap == PADIC_RADIX_PREC_INF) ? c : FLINT_MIN(relcap, c);
    }

    if (rel == PADIC_RADIX_PREC_INF && relcap == PADIC_RADIX_PREC_INF)
        return GR_UNABLE;                        /* exact ring, infinite expansion */

    if (rel == PADIC_RADIX_PREC_INF)
        krel = relcap;
    else if (relcap == PADIC_RADIX_PREC_INF)
        krel = rel;
    else
        krel = FLINT_MIN(rel, relcap);

    if (krel > PADIC_RADIX_ERR_MAX)
        krel = PADIC_RADIX_ERR_MAX;              /* never compute more than we can store */

    if (krel <= 0)
    {
        /* inverse valuation is at/below the precision horizon */
        radix_integer_zero(&res->u, radix);
        res->v = 0;
        res->N = vq + krel;                      /* bounded; finalize clamps */
        return _padic_radix_finalize_assume_canonical(res, ctx);
    }

    nlimbs = (krel + e - 1) / e;                 /* digits -> limbs (ceil) */

    /* res->u = x_unit^{-1} (mod p^{e*nlimbs}); invmod_limbs preserves the sign
       of x, which is also the sign of 1/x. Handles res aliasing x internally. */
    invertible = radix_integer_invmod_limbs(&res->u, &x->u, nlimbs, radix);
    if (!invertible)
        flint_abort();  /* should not happen */

    res->v = vq;
    res->N = vq + krel;                          /* bounded; finalize clamps + truncates */

    return _padic_radix_finalize_assume_canonical(res, ctx);
}

/* TODO: optimize this */
/*
    If the exact unit u = x->u is a perfect square, store its terminating square
    root in res->u and return 1; otherwise return 0. On entry res->u holds one
    square root of u modulo B^M (M limbs, as produced by radix_integer_sqrtmod_
    limbs); the terminating root, if it exists, is that value or its negation
    modulo B^M (both are checked by squaring and comparing against the full u).
*/
static int
_padic_radix_exact_unit_sqrt(padic_radix_t res, const padic_radix_t x, slong M,
    const radix_t radix)
{
    ulong p = DIGIT_RADIX(radix);
    slong ncand = (p == 2) ? 4 : 2;     /* a unit square has 4 roots mod 2^n */
    nn_ptr root, c, sq, d;
    slong i, k, sqn, cn, rs, cmp_limbs;
    int found = 0, neg = 0;
    TMP_INIT;

    if (x->u.size <= 0)         /* a perfect-square exact unit is positive */
        return 0;

    TMP_START;
    root = TMP_ALLOC(M * sizeof(ulong));
    c    = TMP_ALLOC(M * sizeof(ulong));
    sq   = TMP_ALLOC(2 * M * sizeof(ulong));

    /* the canonical branch residue r, zero-extended to M limbs */
    rs = FLINT_MIN(FLINT_ABS(res->u.size), M);
    flint_mpn_copyi(root, res->u.d, rs);
    flint_mpn_zero(root + rs, M - rs);

    /* limbs of r that are reliable for the sign test: all but the top limb,
       whose top bit is the one the 2-adic root leaves undetermined. */
    cmp_limbs = (M > 1) ? (M - 1) : 1;

    /* candidates: root, -root, and (for p = 2) root + B^M/2, -root + B^M/2. The
       candidate that squares (as an exact integer) to x->u is the small positive
       integer root s; only s, not B^M - s, can match exactly. */
    for (k = 0; k < ncand && !found; k++)
    {
        if (k & 1)
            radix_neg(c, root, M, radix);
        else
            flint_mpn_copyi(c, root, M);

        if (k >= 2)             /* add B^M/2 = 2^{eM-1} in the top limb (p = 2) */
        {
            ulong h = UWORD(1) << (radix->exp - 1);
            ulong t = c[M - 1] + h;
            if (t >= LIMB_RADIX(radix))
                t -= LIMB_RADIX(radix);     /* mod B; carry out of B^M dropped */
            c[M - 1] = t;
        }

        radix_mulmid(sq, c, M, c, M, 0, 2 * M, radix);   /* c^2 (full product) */
        sqn = 2 * M;
        MPN_NORM(sq, sqn);

        if (sqn == x->u.size)
        {
            int eq = 1;
            for (i = 0; i < sqn; i++)
                if (sq[i] != x->u.d[i]) { eq = 0; break; }

            if (eq)
            {
                /* c == s, the small positive integer root. The two p-adic roots
                   are +s and -s; the canonical branch is whichever is congruent
                   to r (mod p^k). Store that signed integer so the exact root
                   agrees with the finite-precision result on every shared digit.
                   r == s (on the reliable limbs) selects +s, otherwise -s (whose
                   nonnegative residue B^M - s equals r). */
                neg = 0;
                for (i = 0; i < cmp_limbs; i++)
                    if (root[i] != c[i]) { neg = 1; break; }
                found = 1;
            }
        }
    }

    if (found)
    {
        cn = M;
        MPN_NORM(c, cn);
        if (cn == 0)
            cn = 1;                 /* the root of a unit is nonzero */
        d = radix_integer_fit_limbs(&res->u, cn, radix);
        flint_mpn_copyi(d, c, cn);
        res->u.size = neg ? -cn : cn;   /* signed, consistent with the branch */
    }

    TMP_END;
    return found;
}

/*
    square modulo p (modulo 8 for p = 2). The relative precision of the root
    equals that of x, capped by the context precisions, exactly as for inv/div.
    A definite zero gives the exact zero; an unknown (inexact) zero gives
    GR_UNABLE; an odd valuation or a non-residue unit gives GR_DOMAIN. The branch
    is pinned to a canonical representative, and when the input is exact and a
    perfect square the exact (terminating) root is returned regardless of the
    context precision.
*/
int
padic_radix_sqrt(padic_radix_t res, const padic_radix_t x, gr_ctx_t ctx)
{
    radix_struct * radix = PADIC_RADIX_CTX_RADIX(ctx);
    slong e = radix->exp;
    slong vx = x->v, Nx = x->N;
    slong prec_abs = PADIC_RADIX_CTX_PREC_ABS(ctx);
    slong prec_rel = PADIC_RADIX_CTX_PREC_REL(ctx);
    slong vq, rel, relcap, krel, nlimbs, loss, kin, ndet;
    truth_t xz;
    int issquare, input_exact;
    radix_integer_t unit;

    input_exact = (Nx == PADIC_RADIX_EXACT);

    xz = padic_radix_is_zero(x, ctx);
    if (xz == T_TRUE)
        return padic_radix_zero(res, ctx);       /* sqrt(0) = 0 (exact) */
    if (xz == T_UNKNOWN)
        return GR_UNABLE;                        /* x not known to be nonzero */

    /* A square has even valuation. */
    if (vx & WORD(1))
        return GR_DOMAIN;
    vq = vx / 2;

    /* x = + p^vx exactly (unit 1) has the exact root + p^{vq}. (Other exact
       units have an infinite root expansion, truncated to context precision
       below.) */
    if (Nx == PADIC_RADIX_EXACT && x->u.size == 1 && x->u.d[0] == 1)
    {
        radix_integer_fit_limbs(&res->u, 1, radix)[0] = 1;
        res->u.size = 1;
        res->v = vq;
        res->N = PADIC_RADIX_EXACT;
        return _padic_radix_finalize_assume_canonical(res, ctx);
    }

    /* Unit must be known mod 2^3 */
    if (DIGIT_RADIX(radix) == 2 && Nx - vx < 3)
        return GR_UNABLE;

    /* Relative precision of the root. sqrt preserves relative precision for odd
       p, but the 2-adic square root loses one bit (d/dt t^2 = 2t has valuation 1),
       so an input known to relative precision 'rel' determines the root only to
       'rel - loss'. This loss applies to the input-limited term only: when the
       context's relative cap binds and the input still has bits to spare, the
       capped bits are all determined. Dropping the one unreliable bit is what
       makes sqrt a single precision-independent function (a lower-precision
       result is the truncation of a higher-precision one). */
    loss = (DIGIT_RADIX(radix) == 2) ? 1 : 0;

    rel = (Nx == PADIC_RADIX_EXACT) ? PADIC_RADIX_PREC_INF : (Nx - vx);
    if (rel != PADIC_RADIX_PREC_INF)
        rel = FLINT_MAX(rel - loss, 0);          /* input-limited root precision */

    relcap = PADIC_RADIX_PREC_INF;
    if (prec_rel != PADIC_RADIX_PREC_INF)
        relcap = prec_rel;
    if (prec_abs != PADIC_RADIX_PREC_INF)
    {
        slong c = prec_abs - vq;                 /* bounded: no overflow */
        relcap = (relcap == PADIC_RADIX_PREC_INF) ? c : FLINT_MIN(relcap, c);
    }

    if (rel == PADIC_RADIX_PREC_INF && relcap == PADIC_RADIX_PREC_INF)
        krel = PADIC_RADIX_PREC_INF;             /* exact ring, infinite expansion */
    else if (rel == PADIC_RADIX_PREC_INF)
        krel = relcap;
    else if (relcap == PADIC_RADIX_PREC_INF)
        krel = rel;
    else
        krel = FLINT_MIN(rel, relcap);

    if (krel != PADIC_RADIX_PREC_INF && krel > PADIC_RADIX_ERR_MAX)
        krel = PADIC_RADIX_ERR_MAX;

    /* Input precision to develop: one bit beyond the delivered root precision so
       that the unreliable top bit is computed for headroom and then truncated away
       by the finalizer, leaving every delivered bit pinned. */
    kin = (krel == PADIC_RADIX_PREC_INF) ? PADIC_RADIX_PREC_INF
        : (krel > PADIC_RADIX_ERR_MAX - loss ? PADIC_RADIX_ERR_MAX : krel + loss);

    /* Develop the unit root. If the input is exact the root may terminate (x a
       perfect square), and detecting that needs about half of u's limbs no matter
       what the context precision is -- this is what lets sqrt(4) = 2 exactly even
       in a finite-precision ring. Otherwise develop kin = krel + loss relative
       bits. Non-squareness is read from radix_integer_sqrtmod_limbs, which finds
       the root modulo p itself, so it is never recomputed here. */
    ndet = input_exact ? (FLINT_ABS(x->u.size) / 2 + 2) : 0;

    if (krel == PADIC_RADIX_PREC_INF)
        nlimbs = ndet;                              /* exact ring implies input exact */
    else if (kin <= 0)
        nlimbs = 1;
    else
        nlimbs = (kin + e - 1) / e;

    if (input_exact && ndet > nlimbs)
        nlimbs = ndet;                              /* enough to detect termination */

    /* Materialise the unit's nonnegative residue modulo p^{e*nlimbs} (this also
       resolves a signed exact unit), then take its square root. */
    radix_integer_init(unit, radix);
    radix_integer_mod_digits(unit, &x->u, e * nlimbs, radix);
    issquare = radix_integer_sqrtmod_limbs(&res->u, unit, nlimbs, radix);
    radix_integer_clear(unit, radix);

    if (!issquare)
        return GR_DOMAIN;                            /* unit is not a square mod p */

    /* Exact input + perfect-square unit: return the exact (terminating) root, with
       the sign matching the canonical branch so the exact result agrees with the
       finite-precision result on every shared digit. Works in any context. */
    if (input_exact &&
        _padic_radix_exact_unit_sqrt(res, x, (ndet > 0 ? ndet : nlimbs), radix))
    {
        res->v = vq;
        res->N = PADIC_RADIX_EXACT;
        return _padic_radix_finalize_assume_canonical(res, ctx);
    }

    if (krel == PADIC_RADIX_PREC_INF)
        return GR_UNABLE;       /* exact ring: an irrational root cannot be exact */

    if (krel <= 0)
    {
        /* root is zero to the tracked precision */
        radix_integer_zero(&res->u, radix);
        res->v = 0;
        res->N = vq + krel;                          /* bounded; finalize clamps */
        return _padic_radix_finalize_assume_canonical(res, ctx);
    }

    res->v = vq;
    res->N = vq + krel;                              /* bounded; finalize clamps + truncates */

    return _padic_radix_finalize_assume_canonical(res, ctx);
}

/*
    Whether x is a square. A square has even valuation and a unit that is a square
    in Z_p: for odd p this is decided by the single low digit (a quadratic residue
    modulo p, which always lifts), and that digit is always known; for p = 2 it
    needs the unit modulo 8, so a relative precision below 3 is undecided. A
    definite zero is a square; an inexact (unknown) zero is undecided.
*/
truth_t
padic_radix_is_square(const padic_radix_t x, gr_ctx_t ctx)
{
    radix_struct * radix = PADIC_RADIX_CTX_RADIX(ctx);
    ulong p = DIGIT_RADIX(radix);
    truth_t xz;

    xz = padic_radix_is_zero(x, ctx);
    if (xz == T_TRUE)
        return T_TRUE;                  /* 0 = 0^2 */
    if (xz == T_UNKNOWN)
        return T_UNKNOWN;               /* inexact zero: cannot tell */

    if (x->v & WORD(1))
        return T_FALSE;                 /* a square has even valuation */

    if (p == 2)
    {
        slong rel = (x->N == PADIC_RADIX_EXACT)
            ? PADIC_RADIX_PREC_INF : (x->N - x->v);
        if (rel != PADIC_RADIX_PREC_INF && rel < 3)
            return T_UNKNOWN;           /* need the unit modulo 8 */
    }

    ulong d = x->u.d[0];

    if (x->u.size < 0)
        d = p - d;

    if (p == 2)
        return ((d & 7) == 1) ? T_TRUE : T_FALSE;

    return (n_jacobi_unsigned(nmod_set_ui(d, radix->b), p) == 1) ? T_TRUE : T_FALSE;
}

/*
    Reciprocal square root x^{-1/2}. Computed directly from
    radix_integer_rsqrtmod_limbs (the same primitive that underlies sqrt), not by
    inverting sqrt. The unit's reciprocal root carries valuation -v/2; relative
    precision and the one-bit 2-adic loss are handled exactly as for sqrt. The
    branch is pinned to the reciprocal of the canonical square root, so
    rsqrt(x) * sqrt(x) == 1. GR_DOMAIN when x is not a square (odd valuation or a
    non-residue unit) or is a definite zero; GR_UNABLE when x is not known nonzero,
    or in the exact ring when the reciprocal root has an infinite expansion (every
    case except x = +p^v, whose reciprocal root is the exact + p^{-v/2}).
*/
int
padic_radix_rsqrt(padic_radix_t res, const padic_radix_t x, gr_ctx_t ctx)
{
    radix_struct * radix = PADIC_RADIX_CTX_RADIX(ctx);
    slong e = radix->exp;
    slong vx = x->v, Nx = x->N;
    slong prec_abs = PADIC_RADIX_CTX_PREC_ABS(ctx);
    slong prec_rel = PADIC_RADIX_CTX_PREC_REL(ctx);
    slong vq, vr, rel, relcap, krel, nlimbs, loss, kin;
    truth_t xz;
    int issquare;
    radix_integer_t unit;

    xz = padic_radix_is_zero(x, ctx);
    if (xz == T_TRUE)
        return GR_DOMAIN;                        /* 1/sqrt(0) is undefined */
    if (xz == T_UNKNOWN)
        return GR_UNABLE;                        /* x not known to be nonzero */

    if (vx & WORD(1))
        return GR_DOMAIN;                        /* a square has even valuation */
    vq = vx / 2;
    vr = -vq;                                    /* valuation of x^{-1/2} */

    /* x = + p^vx exactly (unit 1) has the exact reciprocal root + p^{-vq}. */
    if (Nx == PADIC_RADIX_EXACT && x->u.size == 1 && x->u.d[0] == 1)
    {
        radix_integer_fit_limbs(&res->u, 1, radix)[0] = 1;
        res->u.size = 1;
        res->v = vr;
        res->N = PADIC_RADIX_EXACT;
        return _padic_radix_finalize_assume_canonical(res, ctx);
    }

    loss = (DIGIT_RADIX(radix) == 2) ? 1 : 0;

    rel = (Nx == PADIC_RADIX_EXACT) ? PADIC_RADIX_PREC_INF : (Nx - vx);
    if (rel != PADIC_RADIX_PREC_INF)
        rel = FLINT_MAX(rel - loss, 0);

    relcap = PADIC_RADIX_PREC_INF;
    if (prec_rel != PADIC_RADIX_PREC_INF)
        relcap = prec_rel;
    if (prec_abs != PADIC_RADIX_PREC_INF)
    {
        slong c = prec_abs - vr;                 /* absolute cap relative to vr = -vq */
        relcap = (relcap == PADIC_RADIX_PREC_INF) ? c : FLINT_MIN(relcap, c);
    }

    if (rel == PADIC_RADIX_PREC_INF && relcap == PADIC_RADIX_PREC_INF)
        krel = PADIC_RADIX_PREC_INF;             /* exact ring */
    else if (rel == PADIC_RADIX_PREC_INF)
        krel = relcap;
    else if (relcap == PADIC_RADIX_PREC_INF)
        krel = rel;
    else
        krel = FLINT_MIN(rel, relcap);

    if (krel != PADIC_RADIX_PREC_INF && krel > PADIC_RADIX_ERR_MAX)
        krel = PADIC_RADIX_ERR_MAX;

    kin = (krel == PADIC_RADIX_PREC_INF) ? PADIC_RADIX_PREC_INF
        : (krel > PADIC_RADIX_ERR_MAX - loss ? PADIC_RADIX_ERR_MAX : krel + loss);

    /* Develop the reciprocal unit root. In the exact ring the result is infinite
       (the unit-1 case is already returned above), so one limb is enough to decide
       squareness; otherwise develop kin = krel + loss relative bits. Non-squareness
       is read directly from radix_integer_rsqrtmod_limbs. */
    if (krel == PADIC_RADIX_PREC_INF || kin <= 0)
        nlimbs = 1;
    else
        nlimbs = (kin + e - 1) / e;

    radix_integer_init(unit, radix);
    radix_integer_mod_digits(unit, &x->u, e * nlimbs, radix);
    issquare = radix_integer_rsqrtmod_limbs(&res->u, unit, nlimbs, radix);
    radix_integer_clear(unit, radix);

    if (!issquare)
        return GR_DOMAIN;                        /* unit is not a square mod p */

    if (krel == PADIC_RADIX_PREC_INF)
        return GR_UNABLE;       /* exact ring: an infinite reciprocal root */

    if (krel <= 0)
    {
        radix_integer_zero(&res->u, radix);
        res->v = 0;
        res->N = vr + krel;
        return _padic_radix_finalize_assume_canonical(res, ctx);
    }

    res->v = vr;
    res->N = vr + krel;
    return _padic_radix_finalize_assume_canonical(res, ctx);
}

/* ------------------------------------------------------------------------- */
/*    Predicates                                                             */
/* ------------------------------------------------------------------------- */

truth_t
padic_radix_is_zero(const padic_radix_t x, gr_ctx_t ctx)
{
    if (x->N == PADIC_RADIX_EXACT)
        return (x->u.size == 0) ? T_TRUE : T_FALSE;

    /* inexact: x = u p^v + O(p^N) */
    if (x->u.size == 0)
        return T_UNKNOWN;            /* 0 + O(p^N): might be zero or not */

    /* nonzero unit: its lowest (nonzero) digit sits at position v */
    return (x->N > x->v) ? T_FALSE : T_UNKNOWN;
}

truth_t
padic_radix_is_one(const padic_radix_t x, gr_ctx_t ctx)
{
    radix_struct * radix = PADIC_RADIX_CTX_RADIX(ctx);

    if (x->N == PADIC_RADIX_EXACT)
        return (x->v == 0 && radix_integer_is_one(&x->u, radix)) ? T_TRUE : T_FALSE;

    if (x->N <= 0)
        return T_UNKNOWN;            /* not even the units digit is known */

    /* one has valuation 0 and units digit 1 */
    if (x->u.size == 0)
        return T_UNKNOWN;            /* 0 + O(p^N): cannot rule one in or out beyond horizon */

    if (x->v != 0)
        return T_FALSE;              /* units digit (0) differs from 1, and N >= 1 so it is known */

    /* v == 0: compare the unit's residue modulo p^N to 1 (units are nonnegative) */
    return _radix_integer_residue_is_one_mod(&x->u, x->N, radix) ? T_UNKNOWN : T_FALSE;
}

truth_t
padic_radix_is_neg_one(const padic_radix_t x, gr_ctx_t ctx)
{
    radix_struct * radix = PADIC_RADIX_CTX_RADIX(ctx);

    if (x->N == PADIC_RADIX_EXACT)
        return (x->v == 0 && radix_integer_is_neg_one(&x->u, radix)) ? T_TRUE : T_FALSE;

    if (x->N <= 0)
        return T_UNKNOWN;            /* not even the units digit is known */

    /* -1 has valuation 0; its residue mod p^N is p^N - 1 (all digits p-1) */
    if (x->v != 0)
        return T_FALSE;              /* x has a known digit incompatible with -1 */

    /* v == 0: compare the unit's residue modulo p^N to p^N - 1 (units nonnegative) */
    return _radix_integer_residue_is_neg_one_mod(&x->u, x->N, radix) ? T_UNKNOWN : T_FALSE;
}

truth_t
padic_radix_equal(const padic_radix_t x, const padic_radix_t y, gr_ctx_t ctx)
{
    radix_struct * radix = PADIC_RADIX_CTX_RADIX(ctx);
    slong err, vx = x->v, vy = y->v;
    int xz, yz, eq;

    if (x->N == PADIC_RADIX_EXACT && y->N == PADIC_RADIX_EXACT)
    {
        if (vx != vy)
            return T_FALSE;
        return radix_integer_equal(&x->u, &y->u, radix) ? T_TRUE : T_FALSE;
    }

    /* at least one is inexact: they agree as ring elements modulo p^err */
    err = FLINT_MIN(x->N, y->N);   /* EXACT == WORD_MAX acts as +inf */

    if (err <= 0)
        return T_UNKNOWN;

    /* Decide x == y (mod p^err) structurally from the valuations and units. The
       lowest digit of a unit (either sign) sits at its valuation and is nonzero,
       so differing valuations disagree at min(vx, vy); equal valuations reduce to
       a unit congruence that _radix_units_congruent_mod settles in O(unit size),
       regardless of how large err or the valuations are. */
    xz = (x->u.size == 0);
    yz = (y->u.size == 0);

    if (xz && yz)
        eq = 1;
    else if (xz)
        eq = (vy >= err);                 /* y == 0 mod p^err iff its valuation reaches the horizon */
    else if (yz)
        eq = (vx >= err);
    else if (vx == vy)
        eq = _radix_units_congruent_mod(&x->u, &y->u, err - vx, radix);
    else
        eq = (FLINT_MIN(vx, vy) >= err);  /* differ at the lower valuation if it is within the horizon */

    return eq ? T_UNKNOWN : T_FALSE;
}

truth_t
padic_radix_is_invertible(const padic_radix_t x, gr_ctx_t ctx)
{
    /* the radix p-adic numbers form a field: x is invertible iff x is nonzero */
    return truth_not(padic_radix_is_zero(x, ctx));
}

/* ------------------------------------------------------------------------- */
/*    Randomisation                                                          */
/* ------------------------------------------------------------------------- */

int
padic_radix_randtest(padic_radix_t res, flint_rand_t state, gr_ctx_t ctx)
{
    radix_struct * radix = PADIC_RADIX_CTX_RADIX(ctx);
    int ctx_exact = (PADIC_RADIX_CTX_PREC_ABS(ctx) == PADIC_RADIX_PREC_INF
                  && PADIC_RADIX_CTX_PREC_REL(ctx) == PADIC_RADIX_PREC_INF);

    /* the limits mode is only meaningful for an inexact ring (it produces
       error terms and over-large valuations that an exact ring cannot hold) */
    int limits = (PADIC_RADIX_CTX_FLAGS(ctx) & PADIC_RADIX_TEST_LIMITS)
              && PADIC_RADIX_CTX_PREC_REL(ctx) != PADIC_RADIX_PREC_INF
              && (n_randint(state, 2) == 0);

    if (n_randint(state, 2))
        radix_integer_set_si(&res->u, n_randint(state, 5) - 2, radix);
    else
        radix_integer_randtest_limbs(&res->u, state, 1 + n_randint(state, 10), radix);

    if (!PADIC_RADIX_CTX_SIGNED(ctx))
        radix_integer_abs(&res->u, &res->u, radix);

    if (limits && (n_randint(state, 4) == 0))
    {
        /* valuation and precision at or just inside the representable range, so
           that subsequent operations push the intermediate exponents over the
           ERR_MAX boundary and exercise the clamping in _padic_radix_finalize */
        slong big = PADIC_RADIX_ERR_MAX - n_randint(state, 4);

        res->v = (n_randlimb(state) & 1) ? big : -big;

        switch (n_randint(state, 3))
        {
            case 0:  res->N = PADIC_RADIX_EXACT; break;
            case 1:  res->N = (n_randlimb(state) & 1) ? big : -big; break;
            default: res->N = res->v + n_randint(state, 6); break;
        }
    }
    else
    {
        res->v = n_randint(state, 4);
        res->N = PADIC_RADIX_EXACT;

        if (!ctx_exact && (n_randlimb(state) & 1))
            res->N = res->v + n_randint(state, 6);   /* random finite absolute precision */
    }

    if (_padic_radix_finalize(res, ctx) != GR_SUCCESS)
        padic_radix_zero(res, ctx);                  /* always return a valid element */

    return GR_SUCCESS;
}

/* ------------------------------------------------------------------------- */
/*    Output                                                                 */
/* ------------------------------------------------------------------------- */

int
padic_radix_write(gr_stream_t out, const padic_radix_t x, gr_ctx_t ctx)
{
    radix_struct * radix = PADIC_RADIX_CTX_RADIX(ctx);
    ulong p = GR_PADIC_RADIX_CTX(ctx)->p;
    int status = GR_SUCCESS;

    if (x->u.size == 0)
    {
        status |= gr_stream_write(out, "0");
    }
    else
    {
        slong size = x->u.size;
        char * str;

        if (PADIC_RADIX_CTX_DECIMAL(ctx))
            str = radix_get_str_decimal(NULL, x->u.d, FLINT_ABS(size), size < 0, radix);
        else
            str = radix_get_str_sum(NULL, x->u.d, FLINT_ABS(size), size < 0, 1, radix);

        if (x->v != 0)
            status |= gr_stream_write(out, "(");
        status |= gr_stream_write_free(out, str);
        if (x->v != 0)
            status |= gr_stream_write(out, ")");

        if (x->v != 0)
        {
            status |= gr_stream_write(out, " * ");
            status |= gr_stream_write_ui(out, p);
            status |= gr_stream_write(out, "^");
            status |= gr_stream_write_si(out, x->v);
        }
    }

    if (x->N != PADIC_RADIX_EXACT)
    {
        status |= gr_stream_write(out, " + O(");
        status |= gr_stream_write_ui(out, p);
        status |= gr_stream_write(out, "^");
        status |= gr_stream_write_si(out, x->N);
        status |= gr_stream_write(out, ")");
    }

    return status;
}

/* ------------------------------------------------------------------------- */
/*    Context                                                                */
/* ------------------------------------------------------------------------- */

void
padic_radix_ctx_clear(gr_ctx_t ctx)
{
    radix_clear(PADIC_RADIX_CTX_RADIX(ctx));
    flint_free(GR_PADIC_RADIX_CTX(ctx));
}

int
padic_radix_ctx_write(gr_stream_t out, gr_ctx_t ctx)
{
    int status = GR_SUCCESS;
    status |= gr_stream_write(out, "Radix ");
    status |= gr_stream_write_ui(out, GR_PADIC_RADIX_CTX(ctx)->p);
    status |= gr_stream_write(out, "-adic numbers");

    status |= gr_stream_write(out, " (rel prec ");
    if (PADIC_RADIX_CTX_PREC_REL(ctx) == PADIC_RADIX_PREC_INF)
        status |= gr_stream_write(out, "inf");
    else
        status |= gr_stream_write_si(out, PADIC_RADIX_CTX_PREC_REL(ctx));

    status |= gr_stream_write(out, ", abs prec ");
    if (PADIC_RADIX_CTX_PREC_ABS(ctx) == PADIC_RADIX_PREC_INF)
        status |= gr_stream_write(out, "inf");
    else
        status |= gr_stream_write_si(out, PADIC_RADIX_CTX_PREC_ABS(ctx));

    status |= gr_stream_write(out, ")");
    return status;
}

static truth_t
padic_radix_ctx_is_exact(gr_ctx_t ctx)
{
    return (PADIC_RADIX_CTX_PREC_ABS(ctx) == PADIC_RADIX_PREC_INF
         && PADIC_RADIX_CTX_PREC_REL(ctx) == PADIC_RADIX_PREC_INF) ? T_TRUE : T_FALSE;
}

int _padic_radix_methods_initialized = 0;

gr_static_method_table _padic_radix_methods;

gr_method_tab_input _padic_radix_methods_input[] =
{
    {GR_METHOD_CTX_CLEAR,       (gr_funcptr) padic_radix_ctx_clear},
    {GR_METHOD_CTX_WRITE,       (gr_funcptr) padic_radix_ctx_write},
    {GR_METHOD_CTX_IS_RING,     (gr_funcptr) gr_generic_ctx_predicate_true},
    {GR_METHOD_CTX_IS_COMMUTATIVE_RING,
                                (gr_funcptr) gr_generic_ctx_predicate_true},
    {GR_METHOD_CTX_IS_INTEGRAL_DOMAIN,
                                (gr_funcptr) gr_generic_ctx_predicate_true},
    {GR_METHOD_CTX_IS_FIELD,    (gr_funcptr) gr_generic_ctx_predicate_true},
    {GR_METHOD_CTX_IS_UNIQUE_FACTORIZATION_DOMAIN,
                                (gr_funcptr) gr_generic_ctx_predicate_true},
    {GR_METHOD_CTX_IS_RATIONAL_VECTOR_SPACE,
                                (gr_funcptr) gr_generic_ctx_predicate_true},
    {GR_METHOD_CTX_IS_FINITE_CHARACTERISTIC,
                                (gr_funcptr) gr_generic_ctx_predicate_false},
    {GR_METHOD_CTX_IS_EXACT,    (gr_funcptr) padic_radix_ctx_is_exact},
    {GR_METHOD_INIT,            (gr_funcptr) padic_radix_init},
    {GR_METHOD_CLEAR,           (gr_funcptr) padic_radix_clear},
    {GR_METHOD_SWAP,            (gr_funcptr) padic_radix_swap},
    {GR_METHOD_SET_SHALLOW,     (gr_funcptr) padic_radix_set_shallow},
    {GR_METHOD_RANDTEST,        (gr_funcptr) padic_radix_randtest},
    {GR_METHOD_WRITE,           (gr_funcptr) padic_radix_write},
    {GR_METHOD_BIG_O_BASE_FMPZ, (gr_funcptr) padic_radix_big_o_base_fmpz},
    {GR_METHOD_ZERO,            (gr_funcptr) padic_radix_zero},
    {GR_METHOD_ONE,             (gr_funcptr) padic_radix_one},
    {GR_METHOD_IS_ZERO,         (gr_funcptr) padic_radix_is_zero},
    {GR_METHOD_IS_ONE,          (gr_funcptr) padic_radix_is_one},
    {GR_METHOD_IS_NEG_ONE,      (gr_funcptr) padic_radix_is_neg_one},
    {GR_METHOD_IS_INVERTIBLE,   (gr_funcptr) padic_radix_is_invertible},
    {GR_METHOD_EQUAL,           (gr_funcptr) padic_radix_equal},
    {GR_METHOD_SET,             (gr_funcptr) padic_radix_set},
    {GR_METHOD_SET_SI,          (gr_funcptr) padic_radix_set_si},
    {GR_METHOD_SET_UI,          (gr_funcptr) padic_radix_set_ui},
    {GR_METHOD_SET_FMPZ,        (gr_funcptr) padic_radix_set_fmpz},
    {GR_METHOD_GET_FMPZ,        (gr_funcptr) padic_radix_get_fmpz},
    {GR_METHOD_NEG,             (gr_funcptr) padic_radix_neg},
    {GR_METHOD_ADD,             (gr_funcptr) padic_radix_add},
    {GR_METHOD_SUB,             (gr_funcptr) padic_radix_sub},
    {GR_METHOD_MUL,             (gr_funcptr) padic_radix_mul},
    {GR_METHOD_INV,             (gr_funcptr) padic_radix_inv},
    {GR_METHOD_DIV,             (gr_funcptr) padic_radix_div},
    {GR_METHOD_SQRT,            (gr_funcptr) padic_radix_sqrt},
    {GR_METHOD_RSQRT,           (gr_funcptr) padic_radix_rsqrt},
    {GR_METHOD_IS_SQUARE,       (gr_funcptr) padic_radix_is_square},
    {GR_METHOD_EXP,             (gr_funcptr) padic_radix_exp},
    {GR_METHOD_LOG,             (gr_funcptr) padic_radix_log},
    {GR_METHOD_VEC_DOT,         (gr_funcptr) padic_radix_dot},
    {GR_METHOD_VEC_DOT_REV,     (gr_funcptr) padic_radix_dot_rev},
    {GR_METHOD_VEC_DOT_STRIDED, (gr_funcptr) padic_radix_dot_strided},
    /* todo: this ought to be automatic */
    /* todo: use different algorithm with exact precision */
    {GR_METHOD_MAT_DET,         (gr_funcptr) gr_mat_det_generic_field},
    {0,                         (gr_funcptr) NULL},
};

int
gr_ctx_init_padic_radix(gr_ctx_t ctx, ulong p, slong prec_rel, slong prec_abs, int flags)
{
    padic_radix_ctx_struct * pctx;

    FLINT_ASSERT(n_is_prime(p));

    ctx->which_ring = GR_CTX_PADIC_RADIX;
    ctx->sizeof_elem = sizeof(padic_radix_struct);
    ctx->size_limit = WORD_MAX;

    GR_CTX_DATA_AS_PTR(ctx) = flint_malloc(sizeof(padic_radix_ctx_struct));
    pctx = GR_PADIC_RADIX_CTX(ctx);

    radix_init(&pctx->radix, p, 0);   /* limb radix p^e with e chosen automatically */
    pctx->p = p;

    if (prec_rel == PADIC_RADIX_PREC_INF)
        pctx->prec_rel = PADIC_RADIX_PREC_INF;
    else
        pctx->prec_rel = FLINT_MIN(FLINT_MAX(prec_rel, 0), PADIC_RADIX_ERR_MAX);

    if (prec_abs == PADIC_RADIX_PREC_INF)
        pctx->prec_abs = PADIC_RADIX_PREC_INF;
    else
        pctx->prec_abs = FLINT_MAX(FLINT_MIN(prec_abs, PADIC_RADIX_ERR_MAX),
                                   -PADIC_RADIX_ERR_MAX);

    pctx->flags = flags;

    ctx->methods = _padic_radix_methods;

    if (!_padic_radix_methods_initialized)
    {
        gr_method_tab_init(_padic_radix_methods, _padic_radix_methods_input);
        _padic_radix_methods_initialized = 1;
    }

    return GR_SUCCESS;
}

int
gr_ctx_init_padic_radix_randtest(gr_ctx_t ctx, flint_rand_t state, slong maxprec)
{
    ulong p = n_randtest_prime(state, 0);
    slong prec_abs, prec_rel;
    int flags = 0;

    if (n_randint(state, 2))
        flags |= PADIC_RADIX_SIGNED;

    switch (n_randint(state, 4))
    {
        case 0:   /* classic padic: absolute precision only */
            prec_abs = 1 + n_randint(state, maxprec);
            prec_rel = PADIC_RADIX_PREC_INF;
            break;
        case 1:   /* relative precision only */
            prec_abs = PADIC_RADIX_PREC_INF;
            prec_rel = 1 + n_randint(state, maxprec);
            break;
        case 2:   /* both */
            prec_abs = 1 + n_randint(state, maxprec);
            prec_rel = 1 + n_randint(state, maxprec);
            break;
        default:  /* exact ring */
            prec_abs = PADIC_RADIX_PREC_INF;
            prec_rel = PADIC_RADIX_PREC_INF;
            break;
    }

    if (n_randint(state, 2))
        flags |= PADIC_RADIX_TEST_LIMITS;

    /* allow e.g. get_fmpz roundtrip to return unable for huge test values */
    if (flags & PADIC_RADIX_TEST_LIMITS)
        ctx->size_limit = (1 << 16);

    return gr_ctx_init_padic_radix(ctx, p, prec_rel, prec_abs, flags);
}