tilezz 0.1.4

Utilities to work with perfect-precision polygonal tiles built on top of cyclotomic integer rings.
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
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
//! Per-ring `define_integral_zz!` invocations.
//!
//! Each ring in this file lives in the integer-basis cyclotomic
//! representation (`[i64; phi(n)]` over `{1, zeta, ..., zeta^(phi(n)-1)}`)
//! and is generated by a single macro invocation feeding the per-ring
//! constant bundle (reduction rule, real/imag decomposition tables,
//! Cartesian projection, sign function) into the generic engine in
//! `cyclotomic::integral_basis`.

use std::f64::consts::SQRT_2;

use num_complex::Complex64;
use num_rational::Ratio;
use num_traits::{One, Zero};

use crate::define_integral_zz;

// ----------------
// f64 nested-radical constants used by the per-ring `complex64_fn`
// projections (the symbolic-basis embeddings of `cos(2*pi*k/n)`,
// `sin(2*pi*k/n)`).

/// `2 + sqrt(2)`. Used by ZZ16 and ZZ32 (the latter as the inner radical).
const ZZ16_Y: f64 = 2.0 + SQRT_2;

/// `2 + sqrt(2 + sqrt(2))`. The numeric literal is `sqrt(2 + sqrt(2))` to
/// f64 precision; used by ZZ32.
const ZZ32_Z: f64 = 2.0 + 1.847_759_065_022_573_5;

/// `sqrt(5)` to f64 precision. Used by `ZZ10_Y` below.
const SQRT_5: f64 = 2.236_067_977_499_79;

/// `2 * (5 - sqrt(5)) = 10 - 2*sqrt(5)`. Used by ZZ10, ZZ20, ZZ60.
/// `pub(crate)` so `constants::tests::test_constants` can compare the
/// `complex64` projection's `Im` value against the same f64 literal the
/// per-ring projection uses.
pub(crate) const ZZ10_Y: f64 = 2.0 * (5.0 - SQRT_5);

// ----------------
// Generic Display helpers for integer-basis rings.
//
// Each per-ring display function projects its integer-basis vector back to
// a K-vector of (Ratio<i64>, Ratio<i64>) coefficient pairs against the
// symbolic `sqrt(lbl)` basis, then calls `format_symbolic` to render the
// sum.

/// Constructor for a `(real, imag)` Ratio pair. Each per-ring display
/// function projects integer-basis coefficients to a K-vector of these
/// pairs and hands the result to `format_symbolic`.
fn gpair(re: Ratio<i64>, im: Ratio<i64>) -> (Ratio<i64>, Ratio<i64>) {
    (re, im)
}

/// Render a single `(re, im)` Ratio pair as a Gauss-integer-style coefficient
/// string: "0", "a", "bi", "-i", "a+bi", "a-bi", etc.
fn format_gauss_pair(re: Ratio<i64>, im: Ratio<i64>) -> String {
    let mut terms: Vec<String> = Vec::new();
    if !re.is_zero() {
        terms.push(format!("{re}"));
    }
    if !im.is_zero() {
        terms.push(if im.is_one() {
            "i".to_string()
        } else if im == -Ratio::<i64>::one() {
            "-i".to_string()
        } else {
            format!("{im}i")
        });
    }
    if terms.is_empty() {
        "0".to_string()
    } else if terms.len() == 2 && im < Ratio::<i64>::zero() {
        // "a-bi" rather than "a+-bi": the imag term already carries its
        // own minus sign.
        terms.join("")
    } else {
        terms.join("+")
    }
}

/// Render a K-vector of `(re, im)` coefficient pairs against a K-vector
/// of symbolic root labels (`"1"`, `"3"`, `"2+sqrt(2)"`, ...) as the
/// canonical sum-of-square-roots string.
///
/// Macro emitting the exact `CellFloor` impl for a `HasZZ4` ring.
///
/// f64's `complex64().floor()` is the initial guess. Verification uses
/// the same primitive as `geometry::point_in_rect` -- the 4-sign
/// containment query `rect_signs(self, pos_min, pos_max)` -- but with
/// **half-open** semantics (lower-closed `>= 0`, upper-open `> 0`), so
/// a point at exactly `(N, N)` lands in cell `(N, N)` rather than
/// `(N-1, N-1)`. The four signs simultaneously verify the guess and tell
/// us which axis (if any) needs to adjust by +/-1.
///
/// f64 is only a hint; for boundary cases where f64 rounded the wrong
/// way the loop corrects in 1-2 iterations. Output is bit-exact.
macro_rules! impl_cell_floor_via_sign_verify {
    ($name:ident) => {
        impl $crate::cyclotomic::CellFloor for $name {
            #[inline]
            fn cell_floor_exact(&self) -> (i64, i64) {
                use $crate::cyclotomic::SymNum;
                use $crate::cyclotomic::geometry::rect_signs;
                let c = self.complex64();
                let mut cx = c.re.floor() as i64;
                let mut cy = c.im.floor() as i64;
                loop {
                    let pos_min = <$name as From<(i64, i64)>>::from((cx, cy));
                    let pos_max = <$name as From<(i64, i64)>>::from((cx + 1, cy + 1));
                    let s = rect_signs(self, &pos_min, &pos_max);
                    // Half-open [cx, cx+1) x [cy, cy+1):
                    //   s[0] >= 0  (Re(self) >= cx)
                    //   s[1] >= 0  (Im(self) >= cy)
                    //   s[2] > 0   (Re(self) <  cx+1)
                    //   s[3] > 0   (Im(self) <  cy+1)
                    let re_below = s[0] < 0;
                    let re_above = s[2] <= 0;
                    let im_below = s[1] < 0;
                    let im_above = s[3] <= 0;
                    if !re_below && !re_above && !im_below && !im_above {
                        return (cx, cy);
                    }
                    if re_below {
                        cx -= 1;
                    } else if re_above {
                        cx += 1;
                    }
                    if im_below {
                        cy -= 1;
                    } else if im_above {
                        cy += 1;
                    }
                }
            }
        }
    };
}

/// Output shape:
///   * `"0"` when all coefficients are zero
///   * `"<coeff>"` for the `sqrt(1)` term
///   * `"<coeff>*sqrt(<lbl>)"` for a non-unit sqrt term, with parens around
///     compound coefficient strings.
fn format_symbolic<const K: usize>(
    coeffs: &[(Ratio<i64>, Ratio<i64>); K],
    labels: &[&'static str; K],
    f: &mut std::fmt::Formatter<'_>,
) -> std::fmt::Result {
    let mut parts: Vec<String> = Vec::new();
    for ((re, im), lbl) in coeffs.iter().zip(labels.iter()) {
        let s = format_gauss_pair(*re, *im);
        if s == "0" {
            continue;
        }
        let is_real_unit = *lbl == "1";
        let lbl_str = format!("sqrt({lbl})");
        if s == "1" {
            parts.push(if is_real_unit {
                "1".to_string()
            } else {
                lbl_str
            });
        } else if is_real_unit {
            parts.push(s);
        } else {
            parts.push(format!("({s})*{lbl_str}"));
        }
    }
    let joined = parts.join(" + ");
    if joined.is_empty() {
        write!(f, "0")
    } else {
        write!(f, "{joined}")
    }
}

// ----------------
// ZZ4 -- Gauss integers Z[i].
//
// `zeta = i`, `Phi_4(x) = x^2 + 1`, so `zeta^2 = -1`. Storage: `[i64; 2]`
// over `{1, i}`. The real subring is just `Z` (K = 1, basis `{1}`).

#[inline]
fn zz4_complex64(coeffs: &[i64; 2]) -> Complex64 {
    Complex64::new(coeffs[0] as f64, coeffs[1] as f64)
}

const ZZ4_CARTESIAN: [Complex64; 2] = [
    Complex64::new(1.0, 0.0), // zeta^0 = 1
    Complex64::new(0.0, 1.0), // zeta^1 = i
];

fn zz4_display(coeffs: &[i64; 2], f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    // ZZ4 has only the `sqrt(1) = 1` term, so output is just the Gauss-style
    // `a + bi` rendering of the coefficient pair.
    write!(
        f,
        "{}",
        format_gauss_pair(
            Ratio::<i64>::from_integer(coeffs[0]),
            Ratio::<i64>::from_integer(coeffs[1]),
        )
    )
}

/// Sign of an integer K-vector `[m]` against basis `{sqrt(1)}` = `{1}`: just
/// the sign of `m`.
#[inline]
fn zz4_real_sign(x: &[i64; 1]) -> i8 {
    // K=1 / trivial; no recursion, no overflow concern.
    x[0].signum() as i8
}

define_integral_zz! {
    name: ZZ4,
    n: 4,
    phi: 2,
    real_dim: 1,
    // Phi_4(x) = x^2 + 1, so zeta^2 = -1.
    reduction: [-1i64, 0],
    // Re(zeta^0) = 1, Re(zeta^1) = 0.
    re_decomp: [[1i64], [0]],
    // Im(zeta^0) = 0, Im(zeta^1) = 1.
    im_decomp: [[0i64], [1]],
    cartesian: ZZ4_CARTESIAN,
    one_in_real_basis: [1i64],
    display_fn: zz4_display,
    complex64_fn: zz4_complex64,
    has: [HasZZ4Impl, IsZZ4Impl],
}

impl From<(i64, i64)> for ZZ4 {
    /// `(re, im)` where `i = zeta^1`, so `(a, b) = a + b*i` maps to
    /// integer-basis coefficients `[a, b]`.
    #[inline]
    fn from((re, im): (i64, i64)) -> Self {
        Self::from_int_coeffs([re, im])
    }
}

crate::impl_integral_units_via_basis!(ZZ4, 4);
crate::impl_integral_mul_via_basis!(ZZ4, 2);
crate::impl_integral_conj_via_basis!(ZZ4, 2);
crate::impl_integral_re_im_sign_via_basis!(ZZ4, 2, 1, zz4_real_sign);
crate::impl_integral_intersect_unit_segments_via_basis!(ZZ4, 2, 1, zz4_real_sign);
crate::impl_integral_within_radius_via_norm_sq!(ZZ4);
impl_cell_floor_via_sign_verify!(ZZ4);
crate::zz_integral_ring_tests!(name: ZZ4);

// ----------------
// ZZ6 -- Eisenstein integers Z[zeta_6].
//
// `zeta = e^(2*pi*i/6) = (1 + i*sqrt(3)) / 2`, `Phi_6(x) = x^2 - x + 1`,
// so `zeta^2 = zeta - 1`. Storage: `[i64; 2]` over `{1, zeta}`. ZZ6 does
// *not* contain `i` (= zeta_4), so there is no `From<(i64, i64)>` impl
// and the triangular-lattice `CellFloor` uses exact sign comparisons
// against `b*sqrt(3)/2` rather than constructing cartesian-integer corner
// points the way the generic `impl_cell_floor_via_sign_verify!` macro does.
//
// The Re/Im decompositions share the `{sqrt(1), sqrt(3)}` basis with
// implicit /2 denominator that ZZ12 uses, so the real-subring sign
// function delegates directly to `sign_m_plus_n_sqrt3`.

const ZZ6_CARTESIAN: [Complex64; 2] = {
    // sqrt(3)/2 to f64, kept const-evaluable as a literal.
    const HALF_SQRT_3: f64 = 0.866_025_403_784_438_6_f64;
    [
        // zeta^0 = 1
        Complex64::new(1.0, 0.0),
        // zeta^1 = 1/2 + i*sqrt(3)/2
        Complex64::new(0.5, HALF_SQRT_3),
    ]
};

#[inline]
fn zz6_complex64(coeffs: &[i64; 2]) -> Complex64 {
    // Re(a + b*zeta) = a + b/2; Im(a + b*zeta) = b*sqrt(3)/2.
    const HALF_SQRT_3: f64 = 0.866_025_403_784_438_6_f64;
    let [a, b] = *coeffs;
    let (a, b) = (a as f64, b as f64);
    let re = a + 0.5 * b;
    let im = b * HALF_SQRT_3;
    Complex64::new(re, im)
}

/// Display for ZZ6 against `{sqrt(1), sqrt(3)}` with implicit /2:
///
/// ```text
///   z = a + b*zeta = (2a + b)/2 + (b/2)*i*sqrt(3)
///   coefficient of sqrt(1)  = ((2a+b)/2,  0      )
///   coefficient of sqrt(3)  = (0,          b/2   )
/// ```
fn zz6_display(coeffs: &[i64; 2], f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    let [a, b] = *coeffs;
    let half = Ratio::<i64>::new_raw(1, 2);
    let c0 = gpair(
        Ratio::<i64>::from_integer(2 * a + b) * half,
        Ratio::<i64>::from_integer(0),
    );
    let c1 = gpair(
        Ratio::<i64>::from_integer(0),
        Ratio::<i64>::from_integer(b) * half,
    );
    format_symbolic(&[c0, c1], &["1", "3"], f)
}

/// ZZ6's K=2 real-subring sign on the `{1, sqrt(3)}` basis: same shape
/// as ZZ12's, so it just delegates to `sign_m_plus_n_sqrt3`.
#[inline]
fn zz6_real_sign(x: &[i64; 2]) -> i8 {
    sign_m_plus_n_sqrt3(x[0], x[1])
}

define_integral_zz! {
    name: ZZ6,
    n: 6,
    phi: 2,
    real_dim: 2,
    // Phi_6(x) = x^2 - x + 1, so zeta^2 = zeta - 1 = -1 + 1*zeta.
    reduction: [-1i64, 1],
    // Re(zeta^k) in basis {sqrt(1), sqrt(3)} with implicit /2:
    //   Re(zeta^0) = 1            -> [2, 0] / 2
    //   Re(zeta^1) = 1/2          -> [1, 0] / 2
    re_decomp: [[2i64, 0], [1, 0]],
    // Im(zeta^k):
    //   Im(zeta^0) = 0            -> [0, 0] / 2
    //   Im(zeta^1) = sqrt(3)/2    -> [0, 1] / 2
    im_decomp: [[0i64, 0], [0, 1]],
    cartesian: ZZ6_CARTESIAN,
    one_in_real_basis: [2i64, 0],
    display_fn: zz6_display,
    complex64_fn: zz6_complex64,
    has: [HasZZ6Impl],
}

crate::impl_integral_units_via_basis!(ZZ6, 6);
crate::impl_integral_mul_via_basis!(ZZ6, 2);
crate::impl_integral_conj_via_basis!(ZZ6, 2);
crate::impl_integral_re_im_sign_via_basis!(ZZ6, 2, 2, zz6_real_sign);
crate::impl_integral_intersect_unit_segments_via_basis!(ZZ6, 2, 2, zz6_real_sign);
crate::impl_integral_within_radius_via_norm_sq!(ZZ6);

// Hand-rolled `CellFloor` for ZZ6 -- the generic
// `impl_cell_floor_via_sign_verify!` macro requires `From<(i64, i64)>`
// to construct corner points at integer cartesian coordinates, which
// ZZ6 lacks (no `i` in the ring). Instead we extract Re/Im components
// directly off `int_coeffs` and verify the f64 floor against
// `sign_m_plus_n_sqrt3`, mirroring the ZZ10 approach.
impl crate::cyclotomic::CellFloor for ZZ6 {
    #[inline]
    fn cell_floor_exact(&self) -> (i64, i64) {
        use crate::cyclotomic::SymNum;
        let [a, b] = self.int_coeffs();
        // Re(z) = a + b/2 = (2a + b)/2. Integer floor is exact:
        let cx = a + b.div_euclid(2);
        // Im(z) = b*sqrt(3)/2. Iteratively refine the f64 floor using
        // sign(Im(z) - cy) = sign_m_plus_n_sqrt3(-2*cy, b).
        let cf = self.complex64();
        let mut cy = cf.im.floor() as i64;
        while sign_m_plus_n_sqrt3(-2 * cy, b) < 0 {
            cy -= 1;
        }
        while sign_m_plus_n_sqrt3(-2 * (cy + 1), b) >= 0 {
            cy += 1;
        }
        (cx, cy)
    }
}

crate::zz_integral_ring_tests!(name: ZZ6);

// ----------------
// ZZ8 -- compass integers Z[zeta_8].
//
// `zeta = e^(2*pi*i/8) = (sqrt(2) + i*sqrt(2)) / 2`, `Phi_8(x) = x^4 + 1`,
// so `zeta^4 = -1`. Storage: `[i64; 4]` over `{1, zeta, zeta^2, zeta^3}`.
// The real subring is `Z[sqrt(2)]` (K = 2, basis `{1, sqrt(2)}`) with
// `/2` implicit denominator on the decomposition tables.

const HALF_SQRT_2: f64 = std::f64::consts::SQRT_2 * 0.5;

#[inline]
fn zz8_complex64(coeffs: &[i64; 4]) -> Complex64 {
    // zeta = (sqrt(2)/2, sqrt(2)/2), zeta^2 = (0, 1), zeta^3 = (-sqrt(2)/2, sqrt(2)/2).
    let [a, b, c, d] = *coeffs;
    let (a, b, c, d) = (a as f64, b as f64, c as f64, d as f64);
    let re = a + (b - d) * HALF_SQRT_2;
    let im = (b + d) * HALF_SQRT_2 + c;
    Complex64::new(re, im)
}

const ZZ8_CARTESIAN: [Complex64; 4] = [
    Complex64::new(1.0, 0.0),
    Complex64::new(HALF_SQRT_2, HALF_SQRT_2),
    Complex64::new(0.0, 1.0),
    Complex64::new(-HALF_SQRT_2, HALF_SQRT_2),
];

/// Display impl for ZZ8: project `(a, b, c, d)` to `(Ratio, Ratio)`
/// coefficient pairs of `{sqrt(1), sqrt(2)}`.
///
/// ```text
///   zeta^0 = 1                        -> c0 += a
///   zeta^1 = sqrt(2)/2 * (1 + i)      -> c1 += b * (1 + i) / 2
///   zeta^2 = i                        -> c0 += c*i
///   zeta^3 = sqrt(2)/2 * (-1 + i)     -> c1 += d * (-1 + i) / 2
/// ```
fn zz8_display(coeffs: &[i64; 4], f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    let [a, b, c, d] = *coeffs;
    let half = Ratio::<i64>::new_raw(1, 2);
    let c0 = gpair(Ratio::<i64>::from_integer(a), Ratio::<i64>::from_integer(c));
    let c1 = gpair(
        Ratio::<i64>::from_integer(b - d) * half,
        Ratio::<i64>::from_integer(b + d) * half,
    );
    format_symbolic(&[c0, c1], &["1", "2"], f)
}

/// Sign of `a + b*sqrt(2)` for integers `a`, `b`.
///
/// Computed via `signum_sum_sqrt_expr_2` in i128 to absorb the squaring
/// in the recursive helper without i64 overflow when called from
/// `within_radius` on large `z * conj(z) - r_sq` inputs.
#[inline]
fn zz8_real_sign(x: &[i64; 2]) -> i8 {
    crate::cyclotomic::sign::signum_sum_sqrt_expr_2::<i128>(x[0] as i128, 1, x[1] as i128, 2) as i8
}

define_integral_zz! {
    name: ZZ8,
    n: 8,
    phi: 4,
    real_dim: 2,
    // Phi_8(x) = x^4 + 1, so zeta^4 = -1.
    reduction: [-1i64, 0, 0, 0],
    // Re(zeta^k) in basis {1, sqrt(2)} with implicit /2:
    //   Re(zeta^0) = 1            -> [2, 0] / 2
    //   Re(zeta^1) = sqrt(2)/2    -> [0, 1] / 2
    //   Re(zeta^2) = 0            -> [0, 0] / 2
    //   Re(zeta^3) = -sqrt(2)/2   -> [0, -1] / 2
    re_decomp: [[2i64, 0], [0, 1], [0, 0], [0, -1]],
    // Im(zeta^k):
    //   Im(zeta^0) = 0            -> [0, 0] / 2
    //   Im(zeta^1) = sqrt(2)/2    -> [0, 1] / 2
    //   Im(zeta^2) = 1            -> [2, 0] / 2
    //   Im(zeta^3) = sqrt(2)/2    -> [0, 1] / 2
    im_decomp: [[0i64, 0], [0, 1], [2, 0], [0, 1]],
    cartesian: ZZ8_CARTESIAN,
    // `1` in basis {1, sqrt(2)} with /2 denominator: [2, 0].
    one_in_real_basis: [2i64, 0],
    display_fn: zz8_display,
    complex64_fn: zz8_complex64,
    has: [HasZZ4Impl, HasZZ8Impl],
}

impl From<(i64, i64)> for ZZ8 {
    /// `(re, im)` where `i = zeta^2`, so `(a, b) = a + b*i` maps to
    /// integer-basis coefficients `[a, 0, b, 0]`.
    #[inline]
    fn from((re, im): (i64, i64)) -> Self {
        Self::from_int_coeffs([re, 0, im, 0])
    }
}

crate::impl_integral_units_via_basis!(ZZ8, 8);
crate::impl_integral_mul_via_basis!(ZZ8, 4);
crate::impl_integral_conj_via_basis!(ZZ8, 4);
crate::impl_integral_re_im_sign_via_basis!(ZZ8, 4, 2, zz8_real_sign);
crate::impl_integral_intersect_unit_segments_via_basis!(ZZ8, 4, 2, zz8_real_sign);
crate::impl_integral_within_radius_via_norm_sq!(ZZ8);
impl_cell_floor_via_sign_verify!(ZZ8);
crate::zz_integral_ring_tests!(name: ZZ8);

// ----------------
// ZZ12 -- clock integers Z[zeta_12].
//
// `zeta = e^(2*pi*i/12) = sqrt(3)/2 + i/2`, `Phi_12(x) = x^4 - x^2 + 1`,
// so `zeta^4 = zeta^2 - 1`. Storage: `[i64; 4]` over
// `{1, zeta, zeta^2, zeta^3}`. The real subring is `Z[sqrt(3)]` (K = 2,
// basis `{1, sqrt(3)}`) with `/2` implicit denominator.
//
// ZZ12 is the rat_enum hot path: every helper (Mul, Conj, ReImSign,
// IntersectUnitSegments, WithinRadius, Units, complex64) is hand-rolled
// below to bypass the generic engine's K-vector projections and stay in
// inline `sign_m_plus_n_sqrt3` arithmetic.

/// Hand-rolled `complex64` for ZZ12: inline `Re`/`Im` of `(a, b, c, d)`
/// in the `{1, zeta, zeta^2, zeta^3}` basis, avoiding the
/// `complex64_basis` loop. Called from `cell_of` on the hot path.
#[inline]
fn zz12_complex64(coeffs: &[i64; 4]) -> Complex64 {
    // zeta = sqrt(3)/2 + i/2
    // Re = a + b * sqrt(3)/2 + c * 1/2 + d * 0
    // Im = 0 + b * 1/2       + c * sqrt(3)/2 + d
    const HALF_SQRT_3: f64 = 0.866_025_403_784_438_6_f64;
    let [a, b, c, d] = *coeffs;
    let (a, b, c, d) = (a as f64, b as f64, c as f64, d as f64);
    let re = a + b * HALF_SQRT_3 + 0.5 * c;
    let im = 0.5 * b + c * HALF_SQRT_3 + d;
    Complex64::new(re, im)
}

/// Cartesian projection table for ZZ12: `zeta^k` as a `Complex64`, for
/// `zeta = e^(i*pi/6) = sqrt(3)/2 + i/2`.
const ZZ12_CARTESIAN: [Complex64; 4] = {
    // sqrt(3)/2 to f64. Kept as a literal to allow `const` evaluation.
    const HALF_SQRT_3: f64 = 0.866_025_403_784_438_6_f64;
    [
        // zeta^0 = 1
        Complex64::new(1.0, 0.0),
        // zeta^1 = sqrt(3)/2 + i/2
        Complex64::new(HALF_SQRT_3, 0.5),
        // zeta^2 = 1/2 + i*sqrt(3)/2
        Complex64::new(0.5, HALF_SQRT_3),
        // zeta^3 = i
        Complex64::new(0.0, 1.0),
    ]
};

/// Display impl for ZZ12: project the integer-basis vector to `(Ratio,
/// Ratio)` coefficient pairs against the symbolic `{sqrt(1), sqrt(3)}`
/// basis. For `(a, b, c, d)`:
///
/// ```text
///   c0 = ((2a + c)/2) + i*((b + 2d)/2)   coefficient of sqrt(1)
///   c1 = (b/2)        + i*(c/2)          coefficient of sqrt(3)
/// ```
fn zz12_display(coeffs: &[i64; 4], f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    let [a, b, c, d] = *coeffs;
    let half = Ratio::<i64>::new_raw(1, 2);
    let c0 = gpair(
        Ratio::<i64>::from_integer(2 * a + c) * half,
        Ratio::<i64>::from_integer(b + 2 * d) * half,
    );
    let c1 = gpair(
        Ratio::<i64>::from_integer(b) * half,
        Ratio::<i64>::from_integer(c) * half,
    );
    format_symbolic(&[c0, c1], &["1", "3"], f)
}

define_integral_zz! {
    name: ZZ12,
    n: 12,
    phi: 4,
    real_dim: 2,
    // Phi_12(x) = x^4 - x^2 + 1, so zeta^4 = zeta^2 - 1.
    reduction: [-1i64, 0, 1, 0],
    // K-vector of Re(zeta^k) against {sqrt(1), sqrt(3)}, with implicit /2:
    //   Re(zeta^0) = 1            -> [2, 0] / 2
    //   Re(zeta^1) = sqrt(3)/2    -> [0, 1] / 2
    //   Re(zeta^2) = 1/2          -> [1, 0] / 2
    //   Re(zeta^3) = 0            -> [0, 0] / 2
    re_decomp: [[2i64, 0], [0, 1], [1, 0], [0, 0]],
    // K-vector of Im(zeta^k):
    //   Im(zeta^0) = 0            -> [0, 0] / 2
    //   Im(zeta^1) = 1/2          -> [1, 0] / 2
    //   Im(zeta^2) = sqrt(3)/2    -> [0, 1] / 2
    //   Im(zeta^3) = 1            -> [2, 0] / 2
    im_decomp: [[0i64, 0], [1, 0], [0, 1], [2, 0]],
    cartesian: ZZ12_CARTESIAN,
    // The real-subring element `1` against {sqrt(1), sqrt(3)} with the
    // implicit /2 denominator: 1 = (2 + 0*sqrt(3)) / 2, so the K-vector
    // before the /2 normalization is [2, 0].
    one_in_real_basis: [2i64, 0],
    display_fn: zz12_display,
    complex64_fn: zz12_complex64,
    has: [HasZZ4Impl, HasZZ6Impl, HasZZ12Impl],
}

impl From<(i64, i64)> for ZZ12 {
    /// `(re, im)` where `i = zeta^3`, so `(a, b) = a + b*i = a + b*zeta^3`.
    #[inline]
    fn from((re, im): (i64, i64)) -> Self {
        Self::from_int_coeffs([re, 0, 0, im])
    }
}

// ----------------
// Hand-rolled ZZ12 `Mul` and `Conj` -- the inner two hot helpers in the
// rat_enum hot path. ZZ12-specific polynomial expansions below substantially
// outperform the generic `mul_basis` / `conj_basis` engines (`mul_basis`
// allocates a 32-slot scratch, has two folding loops; `conj_basis` indirects
// through a OnceLock-cached matrix). Step 2 perf measurement showed these
// two specializations together close ~ all of the regression vs the
// pre-port hand-written ZZ12.

impl std::ops::Mul<ZZ12> for ZZ12 {
    type Output = Self;
    /// Multiplication in the integral cyclotomic basis `{1, zeta, zeta^2, zeta^3}`,
    /// using `Phi_12(x) = x^4 - x^2 + 1`, so `zeta^4 = zeta^2 - 1`,
    /// `zeta^5 = zeta^3 - zeta`, `zeta^6 = -1`.
    ///
    /// For `x = (a, b, c, d)` and `y = (e, f, g, h)`:
    ///
    /// ```text
    ///   result_0 = ae - bh - cg - df - dh
    ///   result_1 = af + be - ch - dg
    ///   result_2 = ag + bf + ce + bh + cg + df
    ///   result_3 = ah + bg + cf + de + ch + dg
    /// ```
    #[inline]
    fn mul(self, other: Self) -> Self {
        let [a, b, c, d] = self.int_coeffs();
        let [e, f, g, h] = other.int_coeffs();
        let r0 = a * e - b * h - c * g - d * f - d * h;
        let r1 = a * f + b * e - c * h - d * g;
        let r2 = a * g + b * f + c * e + b * h + c * g + d * f;
        let r3 = a * h + b * g + c * f + d * e + c * h + d * g;
        Self::from_int_coeffs([r0, r1, r2, r3])
    }
}

impl crate::cyclotomic::Conj for ZZ12 {
    /// Conjugation in `{1, zeta, zeta^2, zeta^3}`:
    ///
    /// `conj(zeta) = zeta^11 = zeta - zeta^3`  ->  `(0,  1, 0, -1)`
    /// `conj(zeta^2) = zeta^10 = 1 - zeta^2`   ->  `(1,  0, -1, 0)`
    /// `conj(zeta^3) = zeta^9 = -zeta^3`        ->  `(0, 0, 0, -1)`
    ///
    /// So `conj((a, b, c, d)) = (a + c, b, -c, -b - d)`.
    #[inline]
    fn conj(&self) -> Self {
        let [a, b, c, d] = self.int_coeffs();
        Self::from_int_coeffs([a + c, b, -c, -b - d])
    }
}

impl crate::cyclotomic::Units for ZZ12 {
    /// Static-baked `zeta^k` lookup for `k` in `0..12`. Avoids the OnceLock
    /// + Vec indirection of the generic `derive_units_lookup` path.
    #[inline]
    fn unit(angle: i8) -> Self {
        static UNIT_TABLE: [[i64; 4]; 12] = [
            [1, 0, 0, 0],  // 1
            [0, 1, 0, 0],  // zeta
            [0, 0, 1, 0],  // zeta^2
            [0, 0, 0, 1],  // zeta^3 = i
            [-1, 0, 1, 0], // zeta^4 = zeta^2 - 1
            [0, -1, 0, 1], // zeta^5 = zeta^3 - zeta
            [-1, 0, 0, 0], // zeta^6 = -1
            [0, -1, 0, 0], // zeta^7
            [0, 0, -1, 0], // zeta^8
            [0, 0, 0, -1], // zeta^9
            [1, 0, -1, 0], // zeta^10
            [0, 1, 0, -1], // zeta^11
        ];
        let idx = angle.rem_euclid(12) as usize;
        Self::from_int_coeffs(UNIT_TABLE[idx])
    }
}

// ----------------
// Hand-rolled ZZ12 hot-path overrides.
//
// These three impls (`ReImSign`, `WithinRadius`, `IntersectUnitSegments`)
// are the perf-critical surface in `rat_enum`. The generic
// `integral_basis::*` helpers are correct, but the per-ring specialization
// here exploits ZZ12-specific symbolic structure (the basis being
// `{sqrt(1), sqrt(3)}` with implicit /2) to:
//
//   * read `Re`/`Im` components inline as `(2a + c, b)` / `(b + 2d, c)`,
//     skipping the K-vector projection and decomposition-table lookup;
//   * compare squared norms in pure i64 arithmetic (no Complex64);
//   * route `intersect_unit_segments` through the original 3-multiplication
//     ZZ12 fast path that consumed `im_components` directly off each product.
//
// The matching `impl_integral_re_im_sign_via_basis!` /
// `impl_integral_intersect_unit_segments_via_basis!` /
// `impl_integral_within_radius_via_norm_sq!` macros are available for
// other rings to opt into the generic path with one line each.

/// Sign of `m + n*sqrt(3)` where m, n are i64. Returns -1, 0, or 1.
///
/// Cheap cases (one zero, both same sign) resolve without multiplication;
/// mixed-sign case compares `m^2` vs `3 * n^2`.
#[inline]
fn sign_m_plus_n_sqrt3(m: i64, n: i64) -> i8 {
    if m == 0 && n == 0 {
        return 0;
    }
    if m >= 0 && n >= 0 {
        return 1;
    }
    if m <= 0 && n <= 0 {
        return -1;
    }
    // Mixed signs.
    let m_sq = m
        .checked_mul(m)
        .expect("ZZ12 sign_m_plus_n_sqrt3 overflow: m*m");
    let n_sq = n
        .checked_mul(n)
        .expect("ZZ12 sign_m_plus_n_sqrt3 overflow: n*n");
    let three_n_sq = 3i64
        .checked_mul(n_sq)
        .expect("ZZ12 sign_m_plus_n_sqrt3 overflow: 3*n*n");
    if m > 0 {
        match m_sq.cmp(&three_n_sq) {
            std::cmp::Ordering::Less => -1,
            std::cmp::Ordering::Equal => 0,
            std::cmp::Ordering::Greater => 1,
        }
    } else {
        match three_n_sq.cmp(&m_sq) {
            std::cmp::Ordering::Less => -1,
            std::cmp::Ordering::Equal => 0,
            std::cmp::Ordering::Greater => 1,
        }
    }
}

impl crate::cyclotomic::ReImSign for ZZ12 {
    /// `Re(z) = ((2a + c) + b*sqrt(3)) / 2`, denominator positive, so the
    /// sign reduces to `sign((2a + c) + b*sqrt(3))`.
    #[inline]
    fn re_sign(&self) -> i8 {
        let [a, b, c, _] = self.int_coeffs();
        sign_m_plus_n_sqrt3(2 * a + c, b)
    }

    /// `Im(z) = ((b + 2d) + c*sqrt(3)) / 2`.
    #[inline]
    fn im_sign(&self) -> i8 {
        let [_, b, c, d] = self.int_coeffs();
        sign_m_plus_n_sqrt3(b + 2 * d, c)
    }
}

impl crate::cyclotomic::WithinRadius for ZZ12 {
    /// Pure-i64 squared-norm comparison.
    ///
    /// For `z = (a, b, c, d)`:
    /// `|z|^2 = (M + N*sqrt(3)) / 4` with
    ///   M = (2a + c)^2 + 3*b^2 + (b + 2d)^2 + 3*c^2
    ///   N = 2 * ((2a + c)*b + (b + 2d)*c)
    ///
    /// `|z|^2 <= radius^2` iff `sign_m_plus_n_sqrt3(M - 4*r^2, N) <= 0`.
    #[inline]
    fn within_radius(&self, radius: i64) -> bool {
        let [a, b, c, d] = self.int_coeffs();
        let s = 2 * a + c;
        let t = b + 2 * d;
        let m = s * s + 3 * b * b + t * t + 3 * c * c;
        let n = 2 * (s * b + t * c);
        let four_r_sq = 4 * radius * radius;
        sign_m_plus_n_sqrt3(m - four_r_sq, n) <= 0
    }
}

/// ZZ12's K=2 real-subring sign: sign of `m + n*sqrt(3)`. The
/// `fn(&[i64; K]) -> i8` shape expected by the basis-routed
/// `intersect_unit_segments_basis` impl.
fn zz12_real_sign(x: &[i64; 2]) -> i8 {
    sign_m_plus_n_sqrt3(x[0], x[1])
}

crate::impl_integral_intersect_unit_segments_via_basis!(ZZ12, 4, 2, zz12_real_sign);

// ----------------
// Generic algebraic / cyclotomic-structure test suite for ZZ12.
//
// Emits a sibling `zz12_generic_ring_tests` module of ~25 ring-axiom
// tests. The ring-specific `mod tests` below stays for ZZ12-only checks
// (Display format, specific value assertions).
/// Hand-rolled ZZ12 `CellFloor` for the rat_enum hot path. Same family
/// as the generic `impl_cell_floor_via_sign_verify!` macro (f64 hint +
/// exact sign verification), but reads the `(m, n)` components of
/// `Re`/`Im` inline as `(2a+c, b)` / `(b+2d, c)` and dispatches to
/// `sign_m_plus_n_sqrt3` directly, bypassing the macro's
/// `T::from((cx, cy))` ring construction + ring subtraction + K-vector
/// projection.
///
/// `Re(z) = (re_m + re_n*sqrt(3))/2`, so `floor(Re) = k` iff
/// `(re_m - 2k) + re_n*sqrt(3) >= 0` and the next integer's same
/// expression is strictly negative.
///
/// Note: per-axis while-loops rather than the macro's unified loop --
/// LLVM optimizes them slightly better here, and ZZ12 is the
/// benchmark-blessed ring.
impl crate::cyclotomic::CellFloor for ZZ12 {
    #[inline]
    fn cell_floor_exact(&self) -> (i64, i64) {
        use crate::cyclotomic::SymNum;
        let [a, b, c, d] = self.int_coeffs();
        let re_m = 2 * a + c;
        let re_n = b;
        let im_m = b + 2 * d;
        let im_n = c;

        let cf = self.complex64();
        let mut cx = cf.re.floor() as i64;
        let mut cy = cf.im.floor() as i64;

        // Re axis: ensure cx <= Re(z) < cx+1.
        while sign_m_plus_n_sqrt3(re_m - 2 * cx, re_n) < 0 {
            cx -= 1;
        }
        while sign_m_plus_n_sqrt3(re_m - 2 * (cx + 1), re_n) >= 0 {
            cx += 1;
        }

        // Im axis: ensure cy <= Im(z) < cy+1.
        while sign_m_plus_n_sqrt3(im_m - 2 * cy, im_n) < 0 {
            cy -= 1;
        }
        while sign_m_plus_n_sqrt3(im_m - 2 * (cy + 1), im_n) >= 0 {
            cy += 1;
        }

        (cx, cy)
    }
}

crate::zz_integral_ring_tests!(name: ZZ12);

// ----------------
// ZZ14 -- heptagonal-ish integers Z[zeta_14].
//
// `zeta = e^(2*pi*i/14) = e^(i*pi/7)`, `Phi_14(x) = x^6 - x^5 + x^4 - x^3 + x^2 - x + 1`,
// so `zeta^6 = zeta^5 - zeta^4 + zeta^3 - zeta^2 + zeta - 1`. Storage:
// `[i64; 6]` over `{1, zeta, ..., zeta^5}`. ZZ14 does *not* contain `i`
// (zeta_4 is not in this ring), so there is no `From<(i64, i64)>` impl
// and the `CellFloor` is hand-rolled, mirroring the ZZ10 pattern.
//
// The real subring is `Z[c]` of rank 3 where `c = 2*cos(pi/7)` is a
// root of the irreducible cubic `c^3 - c^2 - 2c + 1 = 0`. There is no
// nested-square-root expression for `c`, so none of the
// `signum_sum_sqrt_expr_*` helpers in `sign.rs` apply. Sign extraction
// uses [`sign_at_cubic_root_in_interval`] (rational-interval bisection)
// and, for the imaginary axis, [`sign_at_s_times_x_minus_k`] (squared-
// magnitude reduction). Both are sympy-verified exact and avoid f64.
//
// Basis for the real/imag decomposition tables: `{1, c, c^2, s, c*s,
// c^2*s}` where `s = 2*sin(pi/7)` and `s^2 = 4 - c^2`. The first three
// span the real subring `Z[c]`; the last three are `s` times the same.
// Implicit `/2` denominator throughout.

const ZZ14_CARTESIAN: [Complex64; 6] = {
    // cos(k*pi/7) and sin(k*pi/7) for k = 0..5, computed at high
    // precision and embedded as f64 literals. Used only for the f64
    // projection `complex64()`; algebraic sign extraction is exact.
    [
        Complex64::new(1.0, 0.0),                                 // zeta^0
        Complex64::new(0.9009688679024191, 0.4338837391175581),   // zeta^1
        Complex64::new(0.6234898018587336, 0.7818314824680298),   // zeta^2
        Complex64::new(0.22252093395631434, 0.9749279121818236),  // zeta^3
        Complex64::new(-0.22252093395631434, 0.9749279121818236), // zeta^4
        Complex64::new(-0.6234898018587336, 0.7818314824680298),  // zeta^5
    ]
};

#[inline]
fn zz14_complex64(coeffs: &[i64; 6]) -> Complex64 {
    let mut re = 0.0_f64;
    let mut im = 0.0_f64;
    for (k, &ck) in coeffs.iter().enumerate() {
        let ck = ck as f64;
        re += ck * ZZ14_CARTESIAN[k].re;
        im += ck * ZZ14_CARTESIAN[k].im;
    }
    Complex64::new(re, im)
}

/// Display for ZZ14: project to (Ratio, Ratio) pairs against the
/// symbolic 6-element basis `{1, c, c^2, s, c*s, c^2*s}` with implicit
/// `/2`. For each `i` in `0..6` of `int_coeffs`, distribute its
/// contribution across the basis via `re_decomp` and `im_decomp` rows
/// (the per-element values are pre-tabulated by the macro).
fn zz14_display(coeffs: &[i64; 6], f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    let [c0, c1, c2, c3, c4, c5] = *coeffs;
    let half = Ratio::<i64>::new_raw(1, 2);

    // Real part components in basis {1, c, c^2}: m0 + m1*c + m2*c^2, all /2.
    let m0 = Ratio::<i64>::from_integer(2 * c0 - 2 * c2 - c3 + c4 + 2 * c5) * half;
    let m1 = Ratio::<i64>::from_integer(c1 - c3 + c4) * half;
    let m2 = Ratio::<i64>::from_integer(c2 + c3 - c4 - c5) * half;
    // Imag part components in basis {s, c*s, c^2*s}: n0 + n1*c + n2*c^2 prefixed with s,
    // each /2 implicit.
    let n0 = Ratio::<i64>::from_integer(c1 - c3 - c4) * half;
    let n1 = Ratio::<i64>::from_integer(c2 + c5) * half;
    let n2 = Ratio::<i64>::from_integer(c3 + c4) * half;

    let c_pair_1 = gpair(m0, Ratio::<i64>::from_integer(0));
    let c_pair_c = gpair(m1, Ratio::<i64>::from_integer(0));
    let c_pair_c2 = gpair(m2, Ratio::<i64>::from_integer(0));
    let c_pair_s = gpair(Ratio::<i64>::from_integer(0), n0);
    let c_pair_cs = gpair(Ratio::<i64>::from_integer(0), n1);
    let c_pair_c2s = gpair(Ratio::<i64>::from_integer(0), n2);

    format_symbolic(
        &[
            c_pair_1, c_pair_c, c_pair_c2, c_pair_s, c_pair_cs, c_pair_c2s,
        ],
        &["1", "c7", "c7^2", "s7", "c7*s7", "c7^2*s7"],
        f,
    )
}

/// ZZ14 minimal polynomial of `c = 2*cos(pi/7)`: `c^3 - c^2 - 2c + 1`.
/// Coefficient order is `[m0, m1, m2, m3]` for `m0 + m1*c + m2*c^2 + m3*c^3 = 0`.
const ZZ14_MINPOLY: [i64; 4] = [1, -2, -1, 1];
/// Isolating interval `(1, 2)` for `c = 2*cos(pi/7) ≈ 1.802`. The
/// other two roots of the minpoly (`2*cos(3*pi/7) ≈ 0.445` and
/// `2*cos(5*pi/7) ≈ -1.247`) lie outside `(1, 2)`.
const ZZ14_ISO_LO: (i64, i64) = (1, 1);
const ZZ14_ISO_HI: (i64, i64) = (2, 1);

/// ZZ14 real-subring K=6 sign function.
///
/// The 6-element K-vector `[a, b, d, e, f, g]` represents
/// `(a + b*c + d*c^2) + s*(e + f*c + g*c^2)` in the basis
/// `{1, c, c^2, s, c*s, c^2*s}`. In production callers
/// (`re_sign_basis` / `im_sign_basis` from `integral_basis.rs`), one
/// of the two halves is always zero -- the projection lands either
/// entirely in the real subring (first 3 nonzero) or entirely in the
/// `s`-prefixed subspace (last 3 nonzero). The mixed case isn't
/// currently exercised by the DFS and panics if encountered (so a
/// regression flagging it is visible rather than silent).
fn zz14_real_sign(x: &[i64; 6]) -> i8 {
    let [a, b, d, e, f, g] = *x;
    let real_zero = a == 0 && b == 0 && d == 0;
    let s_zero = e == 0 && f == 0 && g == 0;
    if real_zero && s_zero {
        return 0;
    }
    if s_zero {
        return crate::cyclotomic::sign::sign_at_cubic_root_in_interval(
            [a, b, d],
            ZZ14_MINPOLY,
            ZZ14_ISO_LO,
            ZZ14_ISO_HI,
        );
    }
    if real_zero {
        // s > 0, so sign(s * X) = sign(X).
        return crate::cyclotomic::sign::sign_at_cubic_root_in_interval(
            [e, f, g],
            ZZ14_MINPOLY,
            ZZ14_ISO_LO,
            ZZ14_ISO_HI,
        );
    }
    // Mixed: would need sign((A + s*B)) where both halves nonzero.
    // The reduction is (4 - c^2) * B^2 vs A^2; achievable but the DFS
    // doesn't currently produce this combination, so we panic to make
    // a future regression visible.
    panic!(
        "zz14_real_sign called with mixed real+imaginary K-vector: {:?} -- \
         the DFS shouldn't produce this; please investigate the caller",
        x
    );
}

define_integral_zz! {
    name: ZZ14,
    n: 14,
    phi: 6,
    real_dim: 6,
    // Phi_14(x) = x^6 - x^5 + x^4 - x^3 + x^2 - x + 1, so
    // zeta^6 = -1 + zeta - zeta^2 + zeta^3 - zeta^4 + zeta^5.
    reduction: [-1i64, 1, -1, 1, -1, 1],
    // Re(zeta^k) in basis {1, c, c^2} (first 3 slots), implicit /2:
    //   Re(zeta^0) = 1                = [2, 0, 0]/2
    //   Re(zeta^1) = cos(pi/7) = c/2  = [0, 1, 0]/2
    //   Re(zeta^2) = (c^2 - 2)/2      = [-2, 0, 1]/2
    //   Re(zeta^3) = (c^2 - c - 1)/2  = [-1, -1, 1]/2
    //   Re(zeta^4) = -Re(zeta^3)      = [1, 1, -1]/2
    //   Re(zeta^5) = -Re(zeta^2)      = [2, 0, -1]/2
    re_decomp: [
        [2i64, 0, 0, 0, 0, 0],
        [0, 1, 0, 0, 0, 0],
        [-2, 0, 1, 0, 0, 0],
        [-1, -1, 1, 0, 0, 0],
        [1, 1, -1, 0, 0, 0],
        [2, 0, -1, 0, 0, 0],
    ],
    // Im(zeta^k) in basis {s, c*s, c^2*s} (last 3 slots), implicit /2:
    //   Im(zeta^0) = 0                          = [0, 0, 0]/2
    //   Im(zeta^1) = sin(pi/7) = s/2            = [1, 0, 0]/2
    //   Im(zeta^2) = sin(2*pi/7) = c*s/2        = [0, 1, 0]/2
    //   Im(zeta^3) = sin(3*pi/7) = (c^2*s - s)/2= [-1, 0, 1]/2
    //   Im(zeta^4) = Im(zeta^3)                 = [-1, 0, 1]/2
    //   Im(zeta^5) = Im(zeta^2)                 = [0, 1, 0]/2
    im_decomp: [
        [0i64, 0, 0, 0, 0, 0],
        [0, 0, 0, 1, 0, 0],
        [0, 0, 0, 0, 1, 0],
        [0, 0, 0, -1, 0, 1],
        [0, 0, 0, -1, 0, 1],
        [0, 0, 0, 0, 1, 0],
    ],
    cartesian: ZZ14_CARTESIAN,
    one_in_real_basis: [2i64, 0, 0, 0, 0, 0],
    display_fn: zz14_display,
    complex64_fn: zz14_complex64,
    has: [],
}

crate::impl_integral_units_via_basis!(ZZ14, 14);
crate::impl_integral_mul_via_basis!(ZZ14, 6);
crate::impl_integral_conj_via_basis!(ZZ14, 6);
crate::impl_integral_re_im_sign_via_basis!(ZZ14, 6, 6, zz14_real_sign);
crate::impl_integral_intersect_unit_segments_via_basis!(ZZ14, 6, 6, zz14_real_sign);
crate::impl_integral_within_radius_via_norm_sq!(ZZ14);

/// Hand-rolled `CellFloor` for ZZ14 (no `i` in the ring, mirroring the
/// ZZ10 pattern but with cubic-root-based sign helpers).
impl crate::cyclotomic::CellFloor for ZZ14 {
    #[inline]
    fn cell_floor_exact(&self) -> (i64, i64) {
        use crate::cyclotomic::SymNum;
        use crate::cyclotomic::sign::{sign_at_cubic_root_in_interval, sign_at_s_times_x_minus_k};
        let [c0, c1, c2, c3, c4, c5] = self.int_coeffs();
        // Re(z) = (m0 + m1*c + m2*c^2) / 2.
        let m0 = 2 * c0 - 2 * c2 - c3 + c4 + 2 * c5;
        let m1 = c1 - c3 + c4;
        let m2 = c2 + c3 - c4 - c5;
        // Im(z) = s * (n0 + n1*c + n2*c^2) / 2.
        let n0 = c1 - c3 - c4;
        let n1 = c2 + c5;
        let n2 = c3 + c4;

        let cf = self.complex64();
        let mut cx = cf.re.floor() as i64;
        let mut cy = cf.im.floor() as i64;

        // Re axis: refine cx until cx <= Re(z) < cx + 1.
        // Re(z) - cx = ((m0 - 2*cx) + m1*c + m2*c^2) / 2.
        while sign_at_cubic_root_in_interval(
            [m0 - 2 * cx, m1, m2],
            ZZ14_MINPOLY,
            ZZ14_ISO_LO,
            ZZ14_ISO_HI,
        ) < 0
        {
            cx -= 1;
        }
        while sign_at_cubic_root_in_interval(
            [m0 - 2 * (cx + 1), m1, m2],
            ZZ14_MINPOLY,
            ZZ14_ISO_LO,
            ZZ14_ISO_HI,
        ) >= 0
        {
            cx += 1;
        }

        // Im axis: Im(z) = s * X / 2 where X = n0 + n1*c + n2*c^2.
        // Im(z) - cy = (s*X - 2*cy) / 2.
        while sign_at_s_times_x_minus_k(
            [n0, n1, n2],
            2 * cy,
            ZZ14_MINPOLY,
            ZZ14_ISO_LO,
            ZZ14_ISO_HI,
        ) < 0
        {
            cy -= 1;
        }
        while sign_at_s_times_x_minus_k(
            [n0, n1, n2],
            2 * (cy + 1),
            ZZ14_MINPOLY,
            ZZ14_ISO_LO,
            ZZ14_ISO_HI,
        ) >= 0
        {
            cy += 1;
        }

        (cx, cy)
    }

    /// Override the default `cell_floor` (which floors the f64
    /// projection) because ZZ14 lattice points combine 6 basis
    /// components and the f64 sum suffers from cancellation when
    /// terms align to land exactly on an integer cell boundary --
    /// the floor then lands on the wrong side. The exact bisection
    /// is the only safe answer. Slower than the f64 path, but ZZ14
    /// isn't on the rat_enum hot path the way ZZ12 is.
    #[inline]
    fn cell_floor(&self) -> (i64, i64) {
        self.cell_floor_exact()
    }
}

crate::zz_integral_ring_tests!(name: ZZ14);

// ----------------
// ZZ18 -- nonagonal-ish integers Z[zeta_18].
//
// `zeta = e^(2*pi*i/18) = e^(i*pi/9)`, `Phi_18(x) = x^6 - x^3 + 1`, so
// `zeta^6 = -1 + zeta^3`. Storage: `[i64; 6]` over `{1, zeta, ..., zeta^5}`.
// ZZ18 contains ZZ6 (since 6 | 18), but does *not* contain `i` (4 does
// not divide 18). Hand-rolled `CellFloor`, mirroring ZZ14.
//
// The real subring is `Z[c]` of rank 3 where `c = 2*cos(pi/9)` is a
// root of the irreducible cubic `c^3 - 3c - 1 = 0`. Same algebraic
// shape as ZZ14 (irreducible-cubic minpoly), so the cubic-root and
// multivariate sign helpers from `sign.rs` apply directly -- only the
// minpoly coefficients differ.
//
// Basis for the real/imag decomposition: `{1, c, c^2, s, c*s, c^2*s}`
// where `s = 2*sin(pi/9)` and `s^2 = 4 - c^2`. Implicit `/2`.

const ZZ18_CARTESIAN: [Complex64; 6] = {
    // cos(k*pi/9) and sin(k*pi/9) for k = 0..5.
    //
    // zeta^0 = 1                  -- both components exactly representable.
    // zeta^3 = (1/2, sqrt(3)/2)   -- Re is exactly representable in f64,
    //                                so hard-coded as 0.5 (not the Python-
    //                                computed 0.5000000000000001 which has
    //                                1-ULP error). Im uses the existing
    //                                HALF_SQRT_3 constant from ZZ12.
    //
    // The hard-coded 0.5 matters for lattice points like `3 - 2*zeta^3 =
    // (2, -sqrt(3))` which have Re landing EXACTLY on an integer cell
    // boundary. With the 1-ULP-off table value, the f64 fast path of
    // `cell_floor` underestimates Re by ~2e-16 and crosses to the wrong
    // cell, which then disagrees with the exact path's correct answer.
    const HALF_SQRT_3: f64 = 0.866_025_403_784_438_6_f64;
    [
        Complex64::new(1.0, 0.0),                                // zeta^0
        Complex64::new(0.9396926207859084, 0.3420201433256687),  // zeta^1
        Complex64::new(0.766044443118978, 0.6427876096865393),   // zeta^2
        Complex64::new(0.5, HALF_SQRT_3),                        // zeta^3
        Complex64::new(0.17364817766693041, 0.984807753012208),  // zeta^4
        Complex64::new(-0.17364817766693036, 0.984807753012208), // zeta^5
    ]
};

#[inline]
fn zz18_complex64(coeffs: &[i64; 6]) -> Complex64 {
    let mut re = 0.0_f64;
    let mut im = 0.0_f64;
    for (k, &ck) in coeffs.iter().enumerate() {
        let ck = ck as f64;
        re += ck * ZZ18_CARTESIAN[k].re;
        im += ck * ZZ18_CARTESIAN[k].im;
    }
    Complex64::new(re, im)
}

fn zz18_display(coeffs: &[i64; 6], f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    let [c0, c1, c2, c3, c4, c5] = *coeffs;
    let half = Ratio::<i64>::new_raw(1, 2);

    // Re(z) components against basis {1, c, c^2}, implicit /2.
    // From sympy-derived re_decomp:
    //   m0 = 2*c0 - 2*c2 + c3 + 2*c4 - 2*c5
    //   m1 = c1 + c4 - c5
    //   m2 = c2 - c4 + c5
    let m0 = Ratio::<i64>::from_integer(2 * c0 - 2 * c2 + c3 + 2 * c4 - 2 * c5) * half;
    let m1 = Ratio::<i64>::from_integer(c1 + c4 - c5) * half;
    let m2 = Ratio::<i64>::from_integer(c2 - c4 + c5) * half;
    // Im(z) components against basis {s, c*s, c^2*s}, implicit /2.
    // From sympy-derived im_decomp:
    //   n0 = c1 - c3 + c4 + c5
    //   n1 = c2 + c4 + c5
    //   n2 = c3
    let n0 = Ratio::<i64>::from_integer(c1 - c3 + c4 + c5) * half;
    let n1 = Ratio::<i64>::from_integer(c2 + c4 + c5) * half;
    let n2 = Ratio::<i64>::from_integer(c3) * half;

    let c_pair_1 = gpair(m0, Ratio::<i64>::from_integer(0));
    let c_pair_c = gpair(m1, Ratio::<i64>::from_integer(0));
    let c_pair_c2 = gpair(m2, Ratio::<i64>::from_integer(0));
    let c_pair_s = gpair(Ratio::<i64>::from_integer(0), n0);
    let c_pair_cs = gpair(Ratio::<i64>::from_integer(0), n1);
    let c_pair_c2s = gpair(Ratio::<i64>::from_integer(0), n2);

    format_symbolic(
        &[
            c_pair_1, c_pair_c, c_pair_c2, c_pair_s, c_pair_cs, c_pair_c2s,
        ],
        &["1", "c9", "c9^2", "s9", "c9*s9", "c9^2*s9"],
        f,
    )
}

/// ZZ18 minimal polynomial of `c = 2*cos(pi/9)`: `c^3 - 3c - 1 = 0`.
const ZZ18_MINPOLY: [i64; 4] = [-1, -3, 0, 1];
/// Isolating interval `(1, 2)` for `c ≈ 1.879`. The other two roots
/// (`2*cos(7*pi/9) ≈ -1.532`, `2*cos(5*pi/9) ≈ -0.347`) lie outside.
const ZZ18_ISO_LO: (i64, i64) = (1, 1);
const ZZ18_ISO_HI: (i64, i64) = (2, 1);

fn zz18_real_sign(x: &[i64; 6]) -> i8 {
    let [a, b, d, e, f, g] = *x;
    let real_zero = a == 0 && b == 0 && d == 0;
    let s_zero = e == 0 && f == 0 && g == 0;
    if real_zero && s_zero {
        return 0;
    }
    if s_zero {
        return crate::cyclotomic::sign::sign_at_cubic_root_in_interval(
            [a, b, d],
            ZZ18_MINPOLY,
            ZZ18_ISO_LO,
            ZZ18_ISO_HI,
        );
    }
    if real_zero {
        return crate::cyclotomic::sign::sign_at_cubic_root_in_interval(
            [e, f, g],
            ZZ18_MINPOLY,
            ZZ18_ISO_LO,
            ZZ18_ISO_HI,
        );
    }
    panic!(
        "zz18_real_sign called with mixed real+imaginary K-vector: {:?} -- \
         the DFS shouldn't produce this; please investigate the caller",
        x
    );
}

define_integral_zz! {
    name: ZZ18,
    n: 18,
    phi: 6,
    real_dim: 6,
    // Phi_18(x) = x^6 - x^3 + 1, so zeta^6 = -1 + zeta^3.
    reduction: [-1i64, 0, 0, 1, 0, 0],
    // Re(zeta^k) in basis {1, c, c^2}, implicit /2 -- sympy-derived:
    //   Re(zeta^0) = 1                  = [2, 0, 0]/2
    //   Re(zeta^1) = c/2                = [0, 1, 0]/2
    //   Re(zeta^2) = (c^2 - 2)/2        = [-2, 0, 1]/2
    //   Re(zeta^3) = 1/2                = [1, 0, 0]/2
    //   Re(zeta^4) = (2 + c - c^2)/2    = [2, 1, -1]/2
    //   Re(zeta^5) = (c^2 - c - 2)/2    = [-2, -1, 1]/2
    re_decomp: [
        [2i64, 0, 0, 0, 0, 0],
        [0, 1, 0, 0, 0, 0],
        [-2, 0, 1, 0, 0, 0],
        [1, 0, 0, 0, 0, 0],
        [2, 1, -1, 0, 0, 0],
        [-2, -1, 1, 0, 0, 0],
    ],
    // Im(zeta^k) in basis {s, c*s, c^2*s}, implicit /2 -- sympy-derived:
    //   Im(zeta^0) = 0                  = [0, 0, 0]/2
    //   Im(zeta^1) = s/2                = [1, 0, 0]/2
    //   Im(zeta^2) = c*s/2              = [0, 1, 0]/2
    //   Im(zeta^3) = (c^2*s - s)/2      = [-1, 0, 1]/2
    //   Im(zeta^4) = (s + c*s)/2        = [1, 1, 0]/2
    //   Im(zeta^5) = (s + c*s)/2        = [1, 1, 0]/2
    im_decomp: [
        [0i64, 0, 0, 0, 0, 0],
        [0, 0, 0, 1, 0, 0],
        [0, 0, 0, 0, 1, 0],
        [0, 0, 0, -1, 0, 1],
        [0, 0, 0, 1, 1, 0],
        [0, 0, 0, 1, 1, 0],
    ],
    cartesian: ZZ18_CARTESIAN,
    one_in_real_basis: [2i64, 0, 0, 0, 0, 0],
    display_fn: zz18_display,
    complex64_fn: zz18_complex64,
    has: [HasZZ6Impl],
}

crate::impl_integral_units_via_basis!(ZZ18, 18);
crate::impl_integral_mul_via_basis!(ZZ18, 6);
crate::impl_integral_conj_via_basis!(ZZ18, 6);
crate::impl_integral_re_im_sign_via_basis!(ZZ18, 6, 6, zz18_real_sign);
crate::impl_integral_intersect_unit_segments_via_basis!(ZZ18, 6, 6, zz18_real_sign);
crate::impl_integral_within_radius_via_norm_sq!(ZZ18);

/// Hand-rolled `CellFloor` for ZZ18 -- same shape as ZZ14, different
/// minpoly + isolating interval.
impl crate::cyclotomic::CellFloor for ZZ18 {
    #[inline]
    fn cell_floor_exact(&self) -> (i64, i64) {
        use crate::cyclotomic::SymNum;
        use crate::cyclotomic::sign::{sign_at_cubic_root_in_interval, sign_at_s_times_x_minus_k};
        let [c0, c1, c2, c3, c4, c5] = self.int_coeffs();
        // Re(z) = (m0 + m1*c + m2*c^2) / 2  with c = 2*cos(pi/9).
        let m0 = 2 * c0 - 2 * c2 + c3 + 2 * c4 - 2 * c5;
        let m1 = c1 + c4 - c5;
        let m2 = c2 - c4 + c5;
        // Im(z) = s * (n0 + n1*c + n2*c^2) / 2.
        let n0 = c1 - c3 + c4 + c5;
        let n1 = c2 + c4 + c5;
        let n2 = c3;

        let cf = self.complex64();
        let mut cx = cf.re.floor() as i64;
        let mut cy = cf.im.floor() as i64;

        // Re axis: refine cx until cx <= Re(z) < cx + 1.
        while sign_at_cubic_root_in_interval(
            [m0 - 2 * cx, m1, m2],
            ZZ18_MINPOLY,
            ZZ18_ISO_LO,
            ZZ18_ISO_HI,
        ) < 0
        {
            cx -= 1;
        }
        while sign_at_cubic_root_in_interval(
            [m0 - 2 * (cx + 1), m1, m2],
            ZZ18_MINPOLY,
            ZZ18_ISO_LO,
            ZZ18_ISO_HI,
        ) >= 0
        {
            cx += 1;
        }

        // Im axis: s*X - 2*cy.
        while sign_at_s_times_x_minus_k(
            [n0, n1, n2],
            2 * cy,
            ZZ18_MINPOLY,
            ZZ18_ISO_LO,
            ZZ18_ISO_HI,
        ) < 0
        {
            cy -= 1;
        }
        while sign_at_s_times_x_minus_k(
            [n0, n1, n2],
            2 * (cy + 1),
            ZZ18_MINPOLY,
            ZZ18_ISO_LO,
            ZZ18_ISO_HI,
        ) >= 0
        {
            cy += 1;
        }

        (cx, cy)
    }

    /// Override the default `cell_floor`: see the equivalent
    /// ZZ14 comment. ZZ18 hits the cancellation case more often
    /// because it contains ZZ6 (`6 | 18`) and inherits the
    /// rationally-aligned sub-lattice.
    #[inline]
    fn cell_floor(&self) -> (i64, i64) {
        self.cell_floor_exact()
    }
}

crate::zz_integral_ring_tests!(name: ZZ18);

// ----------------
// ZZ24 -- digiclock integers Z[zeta_24].
//
// `zeta = e^(2*pi*i/24) = cos(15) + i*sin(15)`, `Phi_24(x) = x^8 - x^4 + 1`,
// so `zeta^8 = zeta^4 - 1`. Storage: `[i64; 8]` over
// `{1, zeta, zeta^2, ..., zeta^7}`. The real subring is
// `Z[sqrt(2), sqrt(3), sqrt(6)]` (K = 4, basis `{1, sqrt(2), sqrt(3), sqrt(6)}`)
// with `/4` implicit denominator on the decomposition tables.
//
// All real-sign extraction is exact via `signum_sum_sqrt_expr_4(a, 1, b, 2,
// c, 3, d, 6)` -- both `m = 2` and `n = 3` are integer constants and
// `l = m*n = 6`, so the algebraic identity holds.

/// Symbolic-projection `complex64` for ZZ24.
///
/// Computes `Re(z)` and `Im(z)` by first projecting the integer-basis vector
/// `(a, b, c, d, e, f, g, h)` to a K-vector against `{1, sqrt(2), sqrt(3),
/// sqrt(6)}`, then evaluating each term as `coeff * sqrt(N)` in `f64` and
/// dividing by the implicit `4` denominator. This preserves the bit-exact
/// equalities asserted by `cyclotomic::constants::tests::test_constants`
/// (e.g. `sqrt2::<ZZ24>().complex64().re == f64::sqrt(2.0)`).
#[inline]
fn zz24_complex64(coeffs: &[i64; 8]) -> Complex64 {
    let [a, b, c, d, e, f_, g, h] = *coeffs;
    let (a, b, c, d, e, f_, g, h) = (
        a as f64, b as f64, c as f64, d as f64, e as f64, f_ as f64, g as f64, h as f64,
    );
    let sqrt2 = std::f64::consts::SQRT_2;
    let sqrt3 = 3.0_f64.sqrt();
    let sqrt6 = 6.0_f64.sqrt();
    // Re K-vector (scaled by 4): coefficients of {1, sqrt(2), sqrt(3), sqrt(6)}.
    let r0 = 4.0 * a + 2.0 * e;
    let r1 = b + 2.0 * d - f_ + h;
    let r2 = 2.0 * c;
    let r3 = b + f_ - h;
    let re = (r0 + r1 * sqrt2 + r2 * sqrt3 + r3 * sqrt6) * 0.25;
    // Im K-vector (scaled by 4).
    let i0 = 2.0 * c + 4.0 * g;
    let i1 = -b + 2.0 * d + f_ + h;
    let i2 = 2.0 * e;
    let i3 = b + f_ + h;
    let im = (i0 + i1 * sqrt2 + i2 * sqrt3 + i3 * sqrt6) * 0.25;
    Complex64::new(re, im)
}

const ZZ24_CARTESIAN: [Complex64; 8] = {
    const COS_15: f64 = 0.9659258262890683;
    const SIN_15: f64 = 0.25881904510252074;
    const HALF_SQRT_3: f64 = 0.8660254037844386;
    const HALF_SQRT_2: f64 = std::f64::consts::SQRT_2 * 0.5;
    [
        Complex64::new(1.0, 0.0),
        Complex64::new(COS_15, SIN_15),
        Complex64::new(HALF_SQRT_3, 0.5),
        Complex64::new(HALF_SQRT_2, HALF_SQRT_2),
        Complex64::new(0.5, HALF_SQRT_3),
        Complex64::new(SIN_15, COS_15),
        Complex64::new(0.0, 1.0),
        Complex64::new(-SIN_15, COS_15),
    ]
};

/// Display impl for ZZ24: project `(a..h)` to `(Ratio, Ratio)` coefficient
/// pairs of `{sqrt(1), sqrt(2), sqrt(3), sqrt(6)}`.
fn zz24_display(coeffs: &[i64; 8], f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    let [a, b, c, d, e, f_, g, h] = *coeffs;
    let quarter = Ratio::<i64>::new_raw(1, 4);
    // Coeffs of sqrt(1), sqrt(2), sqrt(3), sqrt(6), each with real and imag
    // parts (everything scaled by 4 to share the implicit denominator).
    let c0 = gpair(
        Ratio::<i64>::from_integer(4 * a + 2 * e) * quarter,
        Ratio::<i64>::from_integer(2 * c + 4 * g) * quarter,
    );
    let c1 = gpair(
        Ratio::<i64>::from_integer(b + 2 * d - f_ + h) * quarter,
        Ratio::<i64>::from_integer(-b + 2 * d + f_ + h) * quarter,
    );
    let c2 = gpair(
        Ratio::<i64>::from_integer(2 * c) * quarter,
        Ratio::<i64>::from_integer(2 * e) * quarter,
    );
    let c3 = gpair(
        Ratio::<i64>::from_integer(b + f_ - h) * quarter,
        Ratio::<i64>::from_integer(b + f_ + h) * quarter,
    );
    format_symbolic(&[c0, c1, c2, c3], &["1", "2", "3", "6"], f)
}

/// Sign of `a + b*sqrt(2) + c*sqrt(3) + d*sqrt(6)` for integers `a, b, c, d`,
/// exact via `signum_sum_sqrt_expr_4`. i128 internally to absorb the
/// squaring in the recursive helper when called from `within_radius`.
#[inline]
fn zz24_real_sign(x: &[i64; 4]) -> i8 {
    crate::cyclotomic::sign::signum_sum_sqrt_expr_4::<i128>(
        x[0] as i128,
        1,
        x[1] as i128,
        2,
        x[2] as i128,
        3,
        x[3] as i128,
        6,
    ) as i8
}

define_integral_zz! {
    name: ZZ24,
    n: 24,
    phi: 8,
    real_dim: 4,
    // Phi_24(x) = x^8 - x^4 + 1, so zeta^8 = zeta^4 - 1.
    reduction: [-1i64, 0, 0, 0, 1, 0, 0, 0],
    // Re(zeta^k) in basis {1, sqrt(2), sqrt(3), sqrt(6)} with implicit /4:
    //   Re(zeta^0) = 1            -> [4, 0, 0, 0]
    //   Re(zeta^1) = cos(15)      -> [0, 1, 0, 1]   (= (sqrt(6)+sqrt(2))/4)
    //   Re(zeta^2) = cos(30)      -> [0, 0, 2, 0]   (= sqrt(3)/2)
    //   Re(zeta^3) = cos(45)      -> [0, 2, 0, 0]   (= sqrt(2)/2)
    //   Re(zeta^4) = cos(60)      -> [2, 0, 0, 0]   (= 1/2)
    //   Re(zeta^5) = cos(75)      -> [0, -1, 0, 1]  (= (sqrt(6)-sqrt(2))/4)
    //   Re(zeta^6) = cos(90)      -> [0, 0, 0, 0]
    //   Re(zeta^7) = cos(105)     -> [0, 1, 0, -1]  (= (sqrt(2)-sqrt(6))/4)
    re_decomp: [
        [4i64, 0, 0, 0], [0, 1, 0, 1], [0, 0, 2, 0], [0, 2, 0, 0],
        [2, 0, 0, 0], [0, -1, 0, 1], [0, 0, 0, 0], [0, 1, 0, -1],
    ],
    // Im(zeta^k):
    //   Im(zeta^0) = 0
    //   Im(zeta^1) = sin(15)      -> [0, -1, 0, 1]  (= (sqrt(6)-sqrt(2))/4)
    //   Im(zeta^2) = sin(30)      -> [2, 0, 0, 0]   (= 1/2)
    //   Im(zeta^3) = sin(45)      -> [0, 2, 0, 0]   (= sqrt(2)/2)
    //   Im(zeta^4) = sin(60)      -> [0, 0, 2, 0]   (= sqrt(3)/2)
    //   Im(zeta^5) = sin(75)      -> [0, 1, 0, 1]   (= (sqrt(6)+sqrt(2))/4)
    //   Im(zeta^6) = sin(90)      -> [4, 0, 0, 0]   (= 1)
    //   Im(zeta^7) = sin(105)     -> [0, 1, 0, 1]   (= (sqrt(6)+sqrt(2))/4)
    im_decomp: [
        [0i64, 0, 0, 0], [0, -1, 0, 1], [2, 0, 0, 0], [0, 2, 0, 0],
        [0, 0, 2, 0], [0, 1, 0, 1], [4, 0, 0, 0], [0, 1, 0, 1],
    ],
    cartesian: ZZ24_CARTESIAN,
    // `1` in basis {1, sqrt(2), sqrt(3), sqrt(6)} with /4 denominator.
    one_in_real_basis: [4i64, 0, 0, 0],
    display_fn: zz24_display,
    complex64_fn: zz24_complex64,
    has: [HasZZ4Impl, HasZZ6Impl, HasZZ8Impl, HasZZ12Impl],
}

impl From<(i64, i64)> for ZZ24 {
    /// `(re, im)` where `i = zeta^6`, so `(a, b) = a + b*i` maps to
    /// integer-basis coefficients `[a, 0, 0, 0, 0, 0, b, 0]`.
    #[inline]
    fn from((re, im): (i64, i64)) -> Self {
        Self::from_int_coeffs([re, 0, 0, 0, 0, 0, im, 0])
    }
}

crate::impl_integral_units_via_basis!(ZZ24, 24);
crate::impl_integral_mul_via_basis!(ZZ24, 8);
crate::impl_integral_conj_via_basis!(ZZ24, 8);
crate::impl_integral_re_im_sign_via_basis!(ZZ24, 8, 4, zz24_real_sign);
crate::impl_integral_intersect_unit_segments_via_basis!(ZZ24, 8, 4, zz24_real_sign);
crate::impl_integral_within_radius_via_norm_sq!(ZZ24);
impl_cell_floor_via_sign_verify!(ZZ24);
crate::zz_integral_ring_tests!(name: ZZ24);

// ----------------
// ZZ20 -- penrose integers Z[zeta_20].
//
// `zeta = e^(2*pi*i/20) = cos(18) + i*sin(18)`, `Phi_20(x) = x^8 - x^6 +
// x^4 - x^2 + 1`, so `zeta^8 = zeta^6 - zeta^4 + zeta^2 - 1`. Storage:
// `[i64; 8]` over `{1, zeta, ..., zeta^7}`. The real subring is
// `Z[sqrt(5), sqrt(10 - 2*sqrt(5))]` (K = 4, basis
// `{1, sqrt(5), sqrt(10-2*sqrt(5)), sqrt(5(10-2*sqrt(5)))}`) with `/8`
// implicit denominator.
//
// Real-sign extraction is exact via the pentagonal closed-form
// `signum_sum_sqrt_expr_4_pentagonal`. Note the basis includes
// `b3 = sqrt(5)*b2` (not the more general `sqrt(m*n)`-shape ZZ24 has).
//
// Useful identity:
//   sqrt(10 + 2*sqrt(5)) = (1 + sqrt(5)) * sqrt(10 - 2*sqrt(5)) / 2
//                       = (b2 + b3) / 2
// which is how cos(18), cos(54), sin(72), sin(108) all reduce to the
// `{b2, b3}` subspace.

/// Symbolic-projection `complex64` for ZZ20. Mirrors ZZ24's approach but
/// reads the inner radical `sqrt(10-2*sqrt(5))` via the `ZZ10_Y` constant
/// (`= 2*(5 - sqrt(5))`) defined above, so that the bit-exact assertions
/// in `cyclotomic::constants::tests::test_constants` (`sqrt5`,
/// `half_sqrt_penta`) round-trip identically.
#[inline]
fn zz20_complex64(coeffs: &[i64; 8]) -> Complex64 {
    let [a, b, c, d, e, f_, g, h] = *coeffs;
    let (a, b, c, d, e, f_, g, h) = (
        a as f64, b as f64, c as f64, d as f64, e as f64, f_ as f64, g as f64, h as f64,
    );
    let sq5 = 5.0_f64.sqrt();
    let sq_y = ZZ10_Y.sqrt();
    let sq_5y = (5.0 * ZZ10_Y).sqrt();
    // Re K-vector (scaled by 8) in basis {1, sqrt(5), sqrt(10-2*sqrt(5)),
    // sqrt(5*(10-2*sqrt(5)))}.
    let r0 = 8.0 * a + 2.0 * c - 2.0 * e + 2.0 * g;
    let r1 = 2.0 * c + 2.0 * e - 2.0 * g;
    let r2 = b + 2.0 * d - 2.0 * h;
    let r3 = b;
    let re = (r0 + r1 * sq5 + r2 * sq_y + r3 * sq_5y) * 0.125;
    // Im K-vector (scaled by 8).
    let i0 = -2.0 * b + 2.0 * d + 8.0 * f_ + 2.0 * h;
    let i1 = 2.0 * b + 2.0 * d + 2.0 * h;
    let i2 = 2.0 * c + e + g;
    let i3 = e + g;
    let im = (i0 + i1 * sq5 + i2 * sq_y + i3 * sq_5y) * 0.125;
    Complex64::new(re, im)
}

const ZZ20_CARTESIAN: [Complex64; 8] = {
    // Cached so the unused `CARTESIAN` const has reasonable values for
    // debugging. Not on any hot path (`complex64_fn` is hand-rolled above).
    const COS_18: f64 = 0.9510565162951535;
    const SIN_18: f64 = 0.30901699437494745;
    const COS_36: f64 = 0.8090169943749475;
    const SIN_36: f64 = 0.5877852522924731;
    const COS_54: f64 = 0.5877852522924731;
    const SIN_54: f64 = 0.8090169943749475;
    const COS_72: f64 = 0.30901699437494745;
    const SIN_72: f64 = 0.9510565162951535;
    [
        Complex64::new(1.0, 0.0),
        Complex64::new(COS_18, SIN_18),
        Complex64::new(COS_36, SIN_36),
        Complex64::new(COS_54, SIN_54),
        Complex64::new(COS_72, SIN_72),
        Complex64::new(0.0, 1.0),
        Complex64::new(-COS_72, SIN_72),
        Complex64::new(-COS_54, SIN_54),
    ]
};

/// Display impl for ZZ20: project `(a..h)` to `(Ratio, Ratio)` coefficient
/// pairs of `{sqrt(1), sqrt(5), sqrt(2(5-sqrt(5))), sqrt(10(5-sqrt(5)))}`.
fn zz20_display(coeffs: &[i64; 8], f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    let [a, b, c, d, e, f_, g, h] = *coeffs;
    let eighth = Ratio::<i64>::new_raw(1, 8);
    let c0 = gpair(
        Ratio::<i64>::from_integer(8 * a + 2 * c - 2 * e + 2 * g) * eighth,
        Ratio::<i64>::from_integer(-2 * b + 2 * d + 8 * f_ + 2 * h) * eighth,
    );
    let c1 = gpair(
        Ratio::<i64>::from_integer(2 * c + 2 * e - 2 * g) * eighth,
        Ratio::<i64>::from_integer(2 * b + 2 * d + 2 * h) * eighth,
    );
    let c2 = gpair(
        Ratio::<i64>::from_integer(b + 2 * d - 2 * h) * eighth,
        Ratio::<i64>::from_integer(2 * c + e + g) * eighth,
    );
    let c3 = gpair(
        Ratio::<i64>::from_integer(b) * eighth,
        Ratio::<i64>::from_integer(e + g) * eighth,
    );
    format_symbolic(
        &[c0, c1, c2, c3],
        &["1", "5", "2(5-sqrt(5))", "10(5-sqrt(5))"],
        f,
    )
}

/// Sign of `a + b*sqrt(5) + c*sqrt(10-2*sqrt(5)) + d*sqrt(5*(10-2*sqrt(5)))`
/// via the closed-form `signum_sum_sqrt_expr_4_pentagonal` (recursive
/// reduction from `Q(sqrt(5), sqrt(10-2*sqrt(5)))` to `Q(sqrt(5))`).
/// i128 internally to absorb the squaring in the recursive helper when
/// called from `within_radius`.
#[inline]
fn zz20_real_sign(x: &[i64; 4]) -> i8 {
    crate::cyclotomic::sign::signum_sum_sqrt_expr_4_pentagonal::<i128>(
        x[0] as i128,
        x[1] as i128,
        x[2] as i128,
        x[3] as i128,
    ) as i8
}

define_integral_zz! {
    name: ZZ20,
    n: 20,
    phi: 8,
    real_dim: 4,
    // Phi_20(x) = x^8 - x^6 + x^4 - x^2 + 1, so zeta^8 = zeta^6 - zeta^4 + zeta^2 - 1.
    reduction: [-1i64, 0, 1, 0, -1, 0, 1, 0],
    // Re(zeta^k) in basis {1, sqrt(5), b2, b3} with implicit /8, where
    //   b2 = sqrt(10 - 2*sqrt(5)),   b3 = sqrt(5)*b2 = sqrt(5*(10-2*sqrt(5))).
    //
    // Useful identity: sqrt(10 + 2*sqrt(5)) = (b2 + b3) / 2, so e.g.
    //   cos(18) = sqrt(10+2*sqrt(5))/4 = (b2 + b3) / 8 -> [0, 0, 1, 1].
    //
    //   Re(zeta^0) = 1                          -> [8, 0, 0, 0]
    //   Re(zeta^1) = cos(18)  = (b2 + b3)/8     -> [0, 0, 1, 1]
    //   Re(zeta^2) = cos(36)  = (1+sqrt(5))/4   -> [2, 2, 0, 0]
    //   Re(zeta^3) = cos(54)  = b2 / 4          -> [0, 0, 2, 0]
    //   Re(zeta^4) = cos(72)  = (sqrt(5)-1)/4   -> [-2, 2, 0, 0]
    //   Re(zeta^5) = cos(90)  = 0               -> [0, 0, 0, 0]
    //   Re(zeta^6) = cos(108) = (1-sqrt(5))/4   -> [2, -2, 0, 0]
    //   Re(zeta^7) = cos(126) = -b2 / 4         -> [0, 0, -2, 0]
    re_decomp: [
        [8i64, 0, 0, 0], [0, 0, 1, 1], [2, 2, 0, 0], [0, 0, 2, 0],
        [-2, 2, 0, 0], [0, 0, 0, 0], [2, -2, 0, 0], [0, 0, -2, 0],
    ],
    // Im(zeta^k):
    //   Im(zeta^0) = 0
    //   Im(zeta^1) = sin(18)  = (sqrt(5)-1)/4   -> [-2, 2, 0, 0]
    //   Im(zeta^2) = sin(36)  = b2 / 4          -> [0, 0, 2, 0]
    //   Im(zeta^3) = sin(54)  = (1+sqrt(5))/4   -> [2, 2, 0, 0]
    //   Im(zeta^4) = sin(72)  = (b2 + b3)/8     -> [0, 0, 1, 1]
    //   Im(zeta^5) = sin(90)  = 1               -> [8, 0, 0, 0]
    //   Im(zeta^6) = sin(108) = (b2 + b3)/8     -> [0, 0, 1, 1]
    //   Im(zeta^7) = sin(126) = (1+sqrt(5))/4   -> [2, 2, 0, 0]
    im_decomp: [
        [0i64, 0, 0, 0], [-2, 2, 0, 0], [0, 0, 2, 0], [2, 2, 0, 0],
        [0, 0, 1, 1], [8, 0, 0, 0], [0, 0, 1, 1], [2, 2, 0, 0],
    ],
    cartesian: ZZ20_CARTESIAN,
    // `1` in basis {1, sqrt(5), b2, b3} with /8 denominator.
    one_in_real_basis: [8i64, 0, 0, 0],
    display_fn: zz20_display,
    complex64_fn: zz20_complex64,
    has: [HasZZ4Impl, HasZZ10Impl],
}

impl From<(i64, i64)> for ZZ20 {
    /// `(re, im)` where `i = zeta^5`, so `(a, b) = a + b*i` maps to
    /// integer-basis coefficients `[a, 0, 0, 0, 0, b, 0, 0]`.
    #[inline]
    fn from((re, im): (i64, i64)) -> Self {
        Self::from_int_coeffs([re, 0, 0, 0, 0, im, 0, 0])
    }
}

crate::impl_integral_units_via_basis!(ZZ20, 20);
crate::impl_integral_mul_via_basis!(ZZ20, 8);
crate::impl_integral_conj_via_basis!(ZZ20, 8);
crate::impl_integral_re_im_sign_via_basis!(ZZ20, 8, 4, zz20_real_sign);
crate::impl_integral_intersect_unit_segments_via_basis!(ZZ20, 8, 4, zz20_real_sign);
crate::impl_integral_within_radius_via_norm_sq!(ZZ20);
impl_cell_floor_via_sign_verify!(ZZ20);
crate::zz_integral_ring_tests!(name: ZZ20);

// ----------------
// ZZ10 -- halfrose integers Z[zeta_10].
//
// `zeta = e^(2*pi*i/10) = cos(36) + i*sin(36)`, `Phi_10(x) = x^4 - x^3 +
// x^2 - x + 1`, so `zeta^4 = zeta^3 - zeta^2 + zeta - 1`. Storage:
// `[i64; 4]` over `{1, zeta, zeta^2, zeta^3}`.
//
// **Not a CM field with `i`.** `zeta_4 = i` is not in `Q(zeta_10)` (since
// `4 \nmid 10`), so `Re(z)` and `Im(z)` for `z` in the integer basis live
// in different `Q`-subspaces of `R`:
//   Re(z) in `Q(sqrt(5))`                                       (dim 2)
//   Im(z) in `Q(sqrt(5)) * sqrt(10-2*sqrt(5))`                  (dim 2)
//
// We unify them with `K = 4` over basis `{1, sqrt(5), b2, b3}` where
// `b2 = sqrt(10 - 2*sqrt(5))` and `b3 = sqrt(5)*b2` (same shape as
// ZZ20). The `j2`/`j3` columns of `re_decomp` are always zero, and the
// `j0`/`j1` columns of `im_decomp` are always zero, but the unified
// shape lets us reuse the exact `signum_sum_sqrt_expr_4_pentagonal`.

#[inline]
fn zz10_complex64(coeffs: &[i64; 4]) -> Complex64 {
    let [a, b, c, d] = *coeffs;
    let (a, b, c, d) = (a as f64, b as f64, c as f64, d as f64);
    let sq5 = 5.0_f64.sqrt();
    let sq_y = ZZ10_Y.sqrt();
    let sq_5y = (5.0 * ZZ10_Y).sqrt();
    // Re K-vector (scaled by 8) -- only the `{1, sqrt(5)}` coordinates are
    // ever non-zero.
    let r0 = 8.0 * a + 2.0 * b - 2.0 * c + 2.0 * d;
    let r1 = 2.0 * b + 2.0 * c - 2.0 * d;
    let re = (r0 + r1 * sq5) * 0.125;
    // Im K-vector (scaled by 8) -- only the `{b2, b3}` coordinates are
    // ever non-zero.
    let i2 = 2.0 * b + c + d;
    let i3 = c + d;
    let im = (i2 * sq_y + i3 * sq_5y) * 0.125;
    Complex64::new(re, im)
}

const ZZ10_CARTESIAN: [Complex64; 4] = {
    const COS_36: f64 = 0.8090169943749475;
    const SIN_36: f64 = 0.5877852522924731;
    const COS_72: f64 = 0.30901699437494745;
    const SIN_72: f64 = 0.9510565162951535;
    [
        Complex64::new(1.0, 0.0),
        Complex64::new(COS_36, SIN_36),
        Complex64::new(COS_72, SIN_72),
        Complex64::new(-COS_72, SIN_72),
    ]
};

fn zz10_display(coeffs: &[i64; 4], f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    let [a, b, c, d] = *coeffs;
    let eighth = Ratio::<i64>::new_raw(1, 8);
    // Each c_k = (Re_part + Im_part * i) / 8.
    let c0 = gpair(
        Ratio::<i64>::from_integer(8 * a + 2 * b - 2 * c + 2 * d) * eighth,
        Ratio::<i64>::from_integer(0) * eighth,
    );
    let c1 = gpair(
        Ratio::<i64>::from_integer(2 * b + 2 * c - 2 * d) * eighth,
        Ratio::<i64>::from_integer(0) * eighth,
    );
    let c2 = gpair(
        Ratio::<i64>::from_integer(0) * eighth,
        Ratio::<i64>::from_integer(2 * b + c + d) * eighth,
    );
    let c3 = gpair(
        Ratio::<i64>::from_integer(0) * eighth,
        Ratio::<i64>::from_integer(c + d) * eighth,
    );
    format_symbolic(
        &[c0, c1, c2, c3],
        &["1", "5", "2(5-sqrt(5))", "10(5-sqrt(5))"],
        f,
    )
}

define_integral_zz! {
    name: ZZ10,
    n: 10,
    phi: 4,
    real_dim: 4,
    // Phi_10(x) = x^4 - x^3 + x^2 - x + 1, so zeta^4 = zeta^3 - zeta^2 + zeta - 1.
    reduction: [-1i64, 1, -1, 1],
    // Re(zeta^k) in basis {1, sqrt(5), b2, b3} with implicit /8:
    //   Re(zeta^0) = 1                          -> [8, 0, 0, 0]
    //   Re(zeta^1) = cos(36) = (1+sqrt(5))/4    -> [2, 2, 0, 0]
    //   Re(zeta^2) = cos(72) = (sqrt(5)-1)/4    -> [-2, 2, 0, 0]
    //   Re(zeta^3) = cos(108) = (1-sqrt(5))/4   -> [2, -2, 0, 0]
    re_decomp: [
        [8i64, 0, 0, 0], [2, 2, 0, 0], [-2, 2, 0, 0], [2, -2, 0, 0],
    ],
    // Im(zeta^k):
    //   Im(zeta^0) = 0
    //   Im(zeta^1) = sin(36) = b2 / 4           -> [0, 0, 2, 0]
    //   Im(zeta^2) = sin(72) = (b2 + b3)/8      -> [0, 0, 1, 1]
    //   Im(zeta^3) = sin(108) = (b2 + b3)/8     -> [0, 0, 1, 1]
    im_decomp: [
        [0i64, 0, 0, 0], [0, 0, 2, 0], [0, 0, 1, 1], [0, 0, 1, 1],
    ],
    cartesian: ZZ10_CARTESIAN,
    one_in_real_basis: [8i64, 0, 0, 0],
    display_fn: zz10_display,
    complex64_fn: zz10_complex64,
    has: [HasZZ10Impl],
}

// ----------------
// Hand-rolled ZZ10 hot-path overrides.
//
// ZZ10 is the pentagonal/Penrose blessed ring. Like ZZ12 it has K=4
// storage; the seven overrides below (Mul, Conj, Units, ReImSign,
// WithinRadius, IntersectUnitSegments, CellFloor) cover the full
// rat_enum hot path with closed-form pure-i64 (i128 for squaring)
// sign primitives, skipping the recursive `signum_sum_sqrt_expr_4_*`
// helpers and the K-vector projection machinery of the generic macros.
//
// Two sign primitives carry the algebra:
//   * `sign_m_plus_n_sqrt5(m, n)` -- sign of `m + n*sqrt(5)` (used for
//     Re-sign and `WithinRadius`, since `|z|^2 in Z[sqrt(5)]`).
//   * `sign_p_b2_plus_q_b3(p, q)` -- sign of
//     `p*sqrt(10-2*sqrt(5)) + q*sqrt(10+2*sqrt(5))` (used for Im-sign).
//     Mixed-sign case reduces in closed form (no recursive squaring) to
//     `sign(p) * sign(p^4 - 3*p^2*q^2 + q^4)` when `p^2 > q^2`, else
//     `-sign(p)`. Derivation: squaring out `sqrt(5)` from the inequality
//     `p^2*(10-2*sqrt(5)) > q^2*(10+2*sqrt(5))` gives a polynomial in
//     `p^2, q^2` whose roots are at `p^2 = golden^2 * q^2` (irrational),
//     so integer inputs never hit poly == 0 outside the trivial cases.

/// Sign of `m + n*sqrt(5)` for integers `m, n`. Returns -1, 0, or 1.
///
/// Cheap cases (one zero, both same sign) resolve without
/// multiplication; mixed-sign case compares `m^2` vs `5*n^2` in i128
/// to absorb the squaring step (i64 inputs can have products up to
/// ~5*2^126).
#[inline]
fn sign_m_plus_n_sqrt5(m: i64, n: i64) -> i8 {
    if m == 0 && n == 0 {
        return 0;
    }
    if m >= 0 && n >= 0 {
        return 1;
    }
    if m <= 0 && n <= 0 {
        return -1;
    }
    let m_sq = (m as i128) * (m as i128);
    let n_sq = (n as i128) * (n as i128);
    let five_n_sq = 5i128 * n_sq;
    if m > 0 {
        // sign of |m| - sqrt(5)*|n|
        match m_sq.cmp(&five_n_sq) {
            std::cmp::Ordering::Less => -1,
            std::cmp::Ordering::Equal => 0,
            std::cmp::Ordering::Greater => 1,
        }
    } else {
        // sign of -|m| + sqrt(5)*|n|
        match five_n_sq.cmp(&m_sq) {
            std::cmp::Ordering::Less => -1,
            std::cmp::Ordering::Equal => 0,
            std::cmp::Ordering::Greater => 1,
        }
    }
}

/// Sign of `p * sqrt(10 - 2*sqrt(5)) + q * sqrt(10 + 2*sqrt(5))` for
/// integers `p, q`. Returns -1, 0, or 1.
///
/// See module-level comment above for the closed-form derivation.
#[inline]
fn sign_p_b2_plus_q_b3(p: i64, q: i64) -> i8 {
    if p == 0 && q == 0 {
        return 0;
    }
    if p >= 0 && q >= 0 {
        return 1;
    }
    if p <= 0 && q <= 0 {
        return -1;
    }
    // Mixed signs.
    let p_sq = (p as i128) * (p as i128);
    let q_sq = (q as i128) * (q as i128);
    if p_sq <= q_sq {
        // |q|*sqrt(beta) dominates (since beta > alpha and |q| >= |p|),
        // so the result has sign(q) = -sign(p).
        return if p > 0 { -1 } else { 1 };
    }
    // p^2 > q^2: closed-form discriminant for `|p|*sqrt(alpha) > |q|*sqrt(beta)`.
    let poly = p_sq * p_sq - 3 * p_sq * q_sq + q_sq * q_sq;
    if poly > 0 {
        if p > 0 { 1 } else { -1 }
    } else {
        // poly < 0 (poly == 0 is unreachable for integer mixed-sign inputs:
        // it would require p^2 = (3 +/- sqrt(5))/2 * q^2, irrational ratio).
        if p > 0 { -1 } else { 1 }
    }
}

/// Sign of `p*sqrt(10-2*sqrt(5)) + q*sqrt(10+2*sqrt(5)) - big_k` for
/// integers `p, q, big_k`. Returns -1, 0, or 1.
///
/// Used by `CellFloor` to verify Im-axis cell membership exactly
/// (`big_k = 4*cy`, since `Im(z) = (p*sqrt(α) + q*sqrt(β))/4`).
///
/// Closed form: let `B = p*sqrt(α) + q*sqrt(β)`, `A = big_k`. If their
/// signs differ or either is zero, the answer is trivial. Same-sign:
/// compare magnitudes via `B^2 - A^2 = M + N*sqrt(5)` with
///     M = 10*(p^2 + q^2) - big_k^2
///     N = 2*(q^2 - p^2 + 4*p*q)
/// (derivation: `sqrt(α*β) = sqrt(80) = 4*sqrt(5)`, so the cross term
/// `2*p*q*sqrt(α*β)` lands in `Z[sqrt(5)]`). Then
/// `sign(B-A) = sign(A) * sign(B^2 - A^2)`.
#[inline]
fn sign_p_b2_plus_q_b3_minus_k(p: i64, q: i64, big_k: i64) -> i8 {
    let sign_b = sign_p_b2_plus_q_b3(p, q);
    let sign_a = big_k.signum() as i8;
    if sign_a == 0 {
        return sign_b;
    }
    if sign_b == 0 {
        return -sign_a;
    }
    if sign_a != sign_b {
        return sign_b;
    }
    // Same sign: compare magnitudes by squaring.
    let p_sq = p * p;
    let q_sq = q * q;
    let k_sq = big_k * big_k;
    let m = 10 * (p_sq + q_sq) - k_sq;
    let n = 2 * (q_sq - p_sq + 4 * p * q);
    let sign_diff = sign_m_plus_n_sqrt5(m, n);
    if sign_a > 0 { sign_diff } else { -sign_diff }
}

/// Re-part components of `z = (a, b, c, d)` in basis `{1, zeta, zeta^2, zeta^3}`:
/// `Re(z) = (re_m + re_n * sqrt(5)) / 4` where
/// `re_m = 4a + b - c + d`, `re_n = b + c - d`.
#[inline]
fn re_components_zz10(coeffs: &[i64; 4]) -> (i64, i64) {
    let [a, b, c, d] = *coeffs;
    (4 * a + b - c + d, b + c - d)
}

/// Im-part components of `z = (a, b, c, d)`:
/// `Im(z) = (im_p * sqrt(10 - 2*sqrt(5)) + im_q * sqrt(10 + 2*sqrt(5))) / 4`
/// where `im_p = b`, `im_q = c + d`.
#[inline]
fn im_components_zz10(coeffs: &[i64; 4]) -> (i64, i64) {
    let [_, b, c, d] = *coeffs;
    (b, c + d)
}

impl std::ops::Mul<ZZ10> for ZZ10 {
    type Output = Self;
    /// Multiplication in the integral basis `{1, zeta, zeta^2, zeta^3}`,
    /// using `Phi_10(x) = x^4 - x^3 + x^2 - x + 1`, so
    /// `zeta^4 = zeta^3 - zeta^2 + zeta - 1`, `zeta^5 = -1`,
    /// `zeta^6 = -zeta`.
    ///
    /// For `x = (a, b, c, d)` and `y = (e, f, g, h)`:
    ///
    /// ```text
    ///   result_0 = ae - bh - cg - df - ch - dg
    ///   result_1 = af + be + bh + cg + df - dh
    ///   result_2 = ag + bf + ce - bh - cg - df
    ///   result_3 = ah + bg + cf + de + bh + cg + df
    /// ```
    #[inline]
    fn mul(self, other: Self) -> Self {
        let [a, b, c, d] = self.int_coeffs();
        let [e, f, g, h] = other.int_coeffs();
        // Common subexpression shared across r0, r1, r2, r3.
        let p4 = b * h + c * g + d * f;
        let r0 = a * e - p4 - c * h - d * g;
        let r1 = a * f + b * e + p4 - d * h;
        let r2 = a * g + b * f + c * e - p4;
        let r3 = a * h + b * g + c * f + d * e + p4;
        Self::from_int_coeffs([r0, r1, r2, r3])
    }
}

impl crate::cyclotomic::Conj for ZZ10 {
    /// Conjugation in `{1, zeta, zeta^2, zeta^3}`. With `zeta^5 = -1`:
    ///
    /// `conj(zeta)   = zeta^9 = -zeta^4 = 1 - zeta + zeta^2 - zeta^3`
    ///                                            -> `(1, -1, 1, -1)`
    /// `conj(zeta^2) = zeta^8 = -zeta^3`          -> `(0, 0, 0, -1)`
    /// `conj(zeta^3) = zeta^7 = -zeta^2`          -> `(0, 0, -1, 0)`
    ///
    /// So `conj((a, b, c, d)) = (a + b, -b, b - d, -b - c)`.
    #[inline]
    fn conj(&self) -> Self {
        let [a, b, c, d] = self.int_coeffs();
        Self::from_int_coeffs([a + b, -b, b - d, -b - c])
    }
}

impl crate::cyclotomic::Units for ZZ10 {
    /// Static-baked `zeta^k` lookup for `k` in `0..10`. Avoids the
    /// OnceLock + Vec indirection of the generic `derive_units_lookup`.
    #[inline]
    fn unit(angle: i8) -> Self {
        static UNIT_TABLE: [[i64; 4]; 10] = [
            [1, 0, 0, 0],   // 1
            [0, 1, 0, 0],   // zeta
            [0, 0, 1, 0],   // zeta^2
            [0, 0, 0, 1],   // zeta^3
            [-1, 1, -1, 1], // zeta^4 = zeta^3 - zeta^2 + zeta - 1
            [-1, 0, 0, 0],  // zeta^5 = -1
            [0, -1, 0, 0],  // zeta^6 = -zeta
            [0, 0, -1, 0],  // zeta^7 = -zeta^2
            [0, 0, 0, -1],  // zeta^8 = -zeta^3
            [1, -1, 1, -1], // zeta^9 = -zeta^4
        ];
        let idx = angle.rem_euclid(10) as usize;
        Self::from_int_coeffs(UNIT_TABLE[idx])
    }
}

impl crate::cyclotomic::WithinRadius for ZZ10 {
    /// Pure-i64 squared-norm comparison.
    ///
    /// For `z = (a, b, c, d)` in basis `{1, zeta, zeta^2, zeta^3}`:
    ///   `Re(z) = (M_re + N_re*sqrt(5)) / 4` with
    ///       M_re = 4a + b - c + d
    ///       N_re = b + c - d
    ///   `Im(z)` involves nested radicals, but the squared norm
    ///   collapses back to `Z[sqrt(5)]`:
    ///       |z|^2 = (A + B*sqrt(5)) / 16  with
    ///       A = M_re^2 + 5*N_re^2 + 10*(b^2 + (c+d)^2)
    ///       B = 2*M_re*N_re + 2*((c+d)^2 - b^2 + 4*b*(c+d))
    ///
    /// `|z|^2 <= r^2` iff `sign_m_plus_n_sqrt5(A - 16*r^2, B) <= 0`.
    #[inline]
    fn within_radius(&self, radius: i64) -> bool {
        let [a, b, c, d] = self.int_coeffs();
        let m_re = 4 * a + b - c + d;
        let n_re = b + c - d;
        let s = c + d;
        let a_part = m_re * m_re + 5 * n_re * n_re + 10 * (b * b + s * s);
        let b_part = 2 * m_re * n_re + 2 * (s * s - b * b + 4 * b * s);
        let sixteen_r_sq = 16 * radius * radius;
        sign_m_plus_n_sqrt5(a_part - sixteen_r_sq, b_part) <= 0
    }
}

impl crate::cyclotomic::ReImSign for ZZ10 {
    /// `Re(z) = (re_m + re_n*sqrt(5)) / 4`, denominator positive, so the
    /// sign reduces to `sign_m_plus_n_sqrt5(re_m, re_n)`.
    #[inline]
    fn re_sign(&self) -> i8 {
        let (m, n) = re_components_zz10(&self.int_coeffs());
        sign_m_plus_n_sqrt5(m, n)
    }

    /// `Im(z) = (im_p*sqrt(10-2*sqrt(5)) + im_q*sqrt(10+2*sqrt(5)))/4`.
    #[inline]
    fn im_sign(&self) -> i8 {
        let (p, q) = im_components_zz10(&self.int_coeffs());
        sign_p_b2_plus_q_b3(p, q)
    }
}

/// ZZ10's K=4 real-subring sign: sign over `{1, sqrt(5), b2, b3}` with
/// `b2 = sqrt(10 - 2*sqrt(5)), b3 = sqrt(5)*b2`. Routes through the
/// pentagonal closed-form helper, same as ZZ20 / ZZ60.
fn zz10_real_sign(x: &[i64; 4]) -> i8 {
    // O(1) fast path. The value is
    //   a + b*sqrt(5) + c*sqrt(10-2*sqrt(5)) + d*sqrt(50-10*sqrt(5)).
    // Evaluate it once at the three sqrt constants rounded to dyadic
    // rationals R_i = round(sqrt_i * 2^P) (|R_i - sqrt_i*2^P| < 1/2,
    // computed offline). Then V = a*2^P + b*R5 + c*R1 + d*R3 satisfies
    // |V - value*2^P| <= (|b|+|c|+|d|)/2, so when `2*|V| > |b|+|c|+|d|`
    // the sign provably equals sign(V). Near-zero values fall through
    // to the exact pentagonal reduction. i64 coefficients can never
    // overflow i128 here (worst term < 2^116).
    const P: u32 = 50;
    const R5: i128 = 2517588727560788; // round(sqrt(5)             * 2^50)
    const R1: i128 = 2647149443198255; // round(sqrt(10-2*sqrt(5))  * 2^50)
    const R3: i128 = 5919206101592016; // round(sqrt(50-10*sqrt(5)) * 2^50)
    let [a, b, c, d] = [x[0] as i128, x[1] as i128, x[2] as i128, x[3] as i128];
    let v = (a << P) + b * R5 + c * R1 + d * R3;
    if 2 * v.abs() > b.abs() + c.abs() + d.abs() {
        return v.signum() as i8;
    }
    crate::cyclotomic::sign::signum_sum_sqrt_expr_4_pentagonal::<i128>(a, b, c, d) as i8
}

crate::impl_integral_intersect_unit_segments_via_basis!(ZZ10, 4, 4, zz10_real_sign);

/// Exact `CellFloor` for ZZ10. Same f64-hint-plus-verify pattern as the
/// `impl_cell_floor_via_sign_verify!` macro, but per-axis rather than
/// constructing the corner as a `cx + cy*i` ring element (ZZ10 has no
/// `i`, so `From<(i64, i64)>` is unavailable).
///
/// Re axis verify: `sign(Re(z) - cx) = sign_m_plus_n_sqrt5(re_m - 4*cx, re_n)`.
/// Im axis verify: `sign(Im(z) - cy) = sign_p_b2_plus_q_b3_minus_k(im_p, im_q, 4*cy)`.
impl crate::cyclotomic::CellFloor for ZZ10 {
    #[inline]
    fn cell_floor_exact(&self) -> (i64, i64) {
        use crate::cyclotomic::SymNum;
        let coeffs = self.int_coeffs();
        let (re_m, re_n) = re_components_zz10(&coeffs);
        let (im_p, im_q) = im_components_zz10(&coeffs);

        let cf = self.complex64();
        let mut cx = cf.re.floor() as i64;
        let mut cy = cf.im.floor() as i64;

        // Re axis: ensure cx <= Re(z) < cx+1.
        while sign_m_plus_n_sqrt5(re_m - 4 * cx, re_n) < 0 {
            cx -= 1;
        }
        while sign_m_plus_n_sqrt5(re_m - 4 * (cx + 1), re_n) >= 0 {
            cx += 1;
        }

        // Im axis: ensure cy <= Im(z) < cy+1.
        while sign_p_b2_plus_q_b3_minus_k(im_p, im_q, 4 * cy) < 0 {
            cy -= 1;
        }
        while sign_p_b2_plus_q_b3_minus_k(im_p, im_q, 4 * (cy + 1)) >= 0 {
            cy += 1;
        }

        (cx, cy)
    }
}

crate::zz_integral_ring_tests!(name: ZZ10);

#[cfg(test)]
mod zz10_real_sign_fast_path {
    use super::zz10_real_sign;
    use crate::cyclotomic::sign::signum_sum_sqrt_expr_4_pentagonal;

    /// The O(1) fast path must agree with the exact pentagonal
    /// reduction on every input. Dense small grid (where value(c) is
    /// closest to zero relative to magnitude) stresses the certainty
    /// threshold and the fall-through to the exact routine.
    #[test]
    fn fast_path_matches_exact_pentagonal_small_grid() {
        for a in -6..=6 {
            for b in -6..=6 {
                for c in -6..=6 {
                    for d in -6..=6 {
                        let got = zz10_real_sign(&[a, b, c, d]);
                        let want = signum_sum_sqrt_expr_4_pentagonal::<i128>(
                            a as i128, b as i128, c as i128, d as i128,
                        ) as i8;
                        assert_eq!(
                            got, want,
                            "zz10_real_sign disagrees with exact at [{a},{b},{c},{d}]"
                        );
                    }
                }
            }
        }
    }
}

// ----------------
// ZZ16 -- hex integers Z[zeta_16].
//
// `zeta = e^(2*pi*i/16) = cos(22.5) + i*sin(22.5)`, `Phi_16(x) = x^8 + 1`,
// so `zeta^8 = -1`. Storage: `[i64; 8]` over `{1, zeta, ..., zeta^7}`. The
// real subring is `Z[sqrt(2), sqrt(2+sqrt(2))]` (K = 4, basis
// `{1, sqrt(2), b3, b4}` with `b3 = sqrt(2+sqrt(2))`, `b4 = sqrt(2)*b3`)
// with `/2` implicit denominator.
//
// Real-sign extraction is **exact** via `signum_sum_sqrt_expr_4_zz16`
// (closed-form reduction from `Q(sqrt(2), sqrt(2+sqrt(2)))` to `Q(sqrt(2))`
// -- same shape as the pentagonal helper, just with `y = 2+sqrt(2)`).
//
// Useful identity for the decomposition tables:
//   sqrt(2 - sqrt(2)) = sqrt(2) * sqrt(2+sqrt(2)) - sqrt(2+sqrt(2))
//                    = b4 - b3
// which expresses sin(22.5), cos(67.5), sin(157.5), etc. in the chosen basis.

#[inline]
fn zz16_complex64(coeffs: &[i64; 8]) -> Complex64 {
    let [a, b, c, d, e, f_, g, h] = *coeffs;
    let (a, b, c, d, e, f_, g, h) = (
        a as f64, b as f64, c as f64, d as f64, e as f64, f_ as f64, g as f64, h as f64,
    );
    let sqrt2 = std::f64::consts::SQRT_2;
    let sq_y = ZZ16_Y.sqrt();
    let sq_2y = (2.0 * ZZ16_Y).sqrt();
    // Re K-vector (scaled by 2) in basis {1, sqrt(2), b3, b4}.
    let r0 = 2.0 * a;
    let r1 = c - g;
    let r2 = b - d + f_ - h;
    let r3 = d - f_;
    let re = (r0 + r1 * sqrt2 + r2 * sq_y + r3 * sq_2y) * 0.5;
    // Im K-vector (scaled by 2).
    let i0 = 2.0 * e;
    let i1 = c + g;
    let i2 = -b + d + f_ - h;
    let i3 = b + h;
    let im = (i0 + i1 * sqrt2 + i2 * sq_y + i3 * sq_2y) * 0.5;
    Complex64::new(re, im)
}

const ZZ16_CARTESIAN: [Complex64; 8] = {
    const COS_22_5: f64 = 0.9238795325112867;
    const SIN_22_5: f64 = 0.3826834323650898;
    const HALF_SQRT_2: f64 = std::f64::consts::SQRT_2 * 0.5;
    [
        Complex64::new(1.0, 0.0),
        Complex64::new(COS_22_5, SIN_22_5),
        Complex64::new(HALF_SQRT_2, HALF_SQRT_2),
        Complex64::new(SIN_22_5, COS_22_5),
        Complex64::new(0.0, 1.0),
        Complex64::new(-SIN_22_5, COS_22_5),
        Complex64::new(-HALF_SQRT_2, HALF_SQRT_2),
        Complex64::new(-COS_22_5, SIN_22_5),
    ]
};

fn zz16_display(coeffs: &[i64; 8], f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    let [a, b, c, d, e, f_, g, h] = *coeffs;
    let half = Ratio::<i64>::new_raw(1, 2);
    // Each c_k = (Re_part + Im_part * i) / 2 where Re_part and Im_part are
    // the K-vector entries above, scaled by 2.
    let c0 = gpair(
        Ratio::<i64>::from_integer(2 * a) * half,
        Ratio::<i64>::from_integer(2 * e) * half,
    );
    let c1 = gpair(
        Ratio::<i64>::from_integer(c - g) * half,
        Ratio::<i64>::from_integer(c + g) * half,
    );
    let c2 = gpair(
        Ratio::<i64>::from_integer(b - d + f_ - h) * half,
        Ratio::<i64>::from_integer(-b + d + f_ - h) * half,
    );
    let c3 = gpair(
        Ratio::<i64>::from_integer(d - f_) * half,
        Ratio::<i64>::from_integer(b + h) * half,
    );
    format_symbolic(
        &[c0, c1, c2, c3],
        &["1", "2", "2+sqrt(2)", "2(2+sqrt(2))"],
        f,
    )
}

/// Sign of `a + b*sqrt(2) + c*sqrt(2+sqrt(2)) + d*sqrt(2*(2+sqrt(2)))`
/// via the closed-form `signum_sum_sqrt_expr_4_zz16` (recursive reduction
/// from `Q(sqrt(2), sqrt(2+sqrt(2)))` to `Q(sqrt(2))`).
#[inline]
fn zz16_real_sign(x: &[i64; 4]) -> i8 {
    crate::cyclotomic::sign::signum_sum_sqrt_expr_4_zz16::<i128>(
        x[0] as i128,
        x[1] as i128,
        x[2] as i128,
        x[3] as i128,
    ) as i8
}

define_integral_zz! {
    name: ZZ16,
    n: 16,
    phi: 8,
    real_dim: 4,
    // Phi_16(x) = x^8 + 1, so zeta^8 = -1.
    reduction: [-1i64, 0, 0, 0, 0, 0, 0, 0],
    // Re(zeta^k) in basis {1, sqrt(2), b3, b4} with implicit /2, where
    //   b3 = sqrt(2 + sqrt(2)),   b4 = sqrt(2) * b3 = sqrt(2(2+sqrt(2))).
    //
    // Identity: sqrt(2 - sqrt(2)) = b4 - b3, so e.g.
    //   sin(22.5) = sqrt(2-sqrt(2))/2 = (b4 - b3) / 2 -> [0, 0, -1, 1].
    //
    //   Re(zeta^0) = 1                  -> [2, 0, 0, 0]
    //   Re(zeta^1) = cos(22.5) = b3/2   -> [0, 0, 1, 0]
    //   Re(zeta^2) = cos(45)   = sqrt(2)/2 -> [0, 1, 0, 0]
    //   Re(zeta^3) = cos(67.5) = sin(22.5) = (b4-b3)/2 -> [0, 0, -1, 1]
    //   Re(zeta^4) = cos(90)   = 0      -> [0, 0, 0, 0]
    //   Re(zeta^5) = cos(112.5)= -sin(22.5) = (b3-b4)/2 -> [0, 0, 1, -1]
    //   Re(zeta^6) = cos(135)  = -sqrt(2)/2 -> [0, -1, 0, 0]
    //   Re(zeta^7) = cos(157.5)= -cos(22.5) = -b3/2 -> [0, 0, -1, 0]
    re_decomp: [
        [2i64, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, -1, 1],
        [0, 0, 0, 0], [0, 0, 1, -1], [0, -1, 0, 0], [0, 0, -1, 0],
    ],
    // Im(zeta^k):
    //   Im(zeta^0) = 0
    //   Im(zeta^1) = sin(22.5)  = (b4-b3)/2 -> [0, 0, -1, 1]
    //   Im(zeta^2) = sin(45)    = sqrt(2)/2 -> [0, 1, 0, 0]
    //   Im(zeta^3) = sin(67.5)  = cos(22.5) = b3/2 -> [0, 0, 1, 0]
    //   Im(zeta^4) = sin(90)    = 1 -> [2, 0, 0, 0]
    //   Im(zeta^5) = sin(112.5) = sin(67.5) = b3/2 -> [0, 0, 1, 0]
    //   Im(zeta^6) = sin(135)   = sqrt(2)/2 -> [0, 1, 0, 0]
    //   Im(zeta^7) = sin(157.5) = sin(22.5) = (b4-b3)/2 -> [0, 0, -1, 1]
    im_decomp: [
        [0i64, 0, 0, 0], [0, 0, -1, 1], [0, 1, 0, 0], [0, 0, 1, 0],
        [2, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, -1, 1],
    ],
    cartesian: ZZ16_CARTESIAN,
    one_in_real_basis: [2i64, 0, 0, 0],
    display_fn: zz16_display,
    complex64_fn: zz16_complex64,
    has: [HasZZ4Impl, HasZZ8Impl],
}

impl From<(i64, i64)> for ZZ16 {
    /// `(re, im)` where `i = zeta^4`, so `(a, b) = a + b*i` maps to
    /// integer-basis coefficients `[a, 0, 0, 0, b, 0, 0, 0]`.
    #[inline]
    fn from((re, im): (i64, i64)) -> Self {
        Self::from_int_coeffs([re, 0, 0, 0, im, 0, 0, 0])
    }
}

crate::impl_integral_units_via_basis!(ZZ16, 16);
crate::impl_integral_mul_via_basis!(ZZ16, 8);
crate::impl_integral_conj_via_basis!(ZZ16, 8);
crate::impl_integral_re_im_sign_via_basis!(ZZ16, 8, 4, zz16_real_sign);
crate::impl_integral_intersect_unit_segments_via_basis!(ZZ16, 8, 4, zz16_real_sign);
crate::impl_integral_within_radius_via_norm_sq!(ZZ16);
impl_cell_floor_via_sign_verify!(ZZ16);
crate::zz_integral_ring_tests!(name: ZZ16);

// ----------------
// ZZ60 -- babylonian integers Z[zeta_60].
//
// `zeta = e^(2*pi*i/60) = cos(6) + i*sin(6)`. `Phi_60(x) = x^16 + x^14 -
// x^10 - x^8 - x^6 + x^2 + 1`, so `zeta^16 = -zeta^14 + zeta^10 + zeta^8
// + zeta^6 - zeta^2 - 1`. Storage: `[i64; 16]` over
// `{1, zeta, ..., zeta^15}`.
//
// The real subring is `Q(sqrt(3), sqrt(5), sqrt(10-2*sqrt(5)))`, dim 8
// over Q, basis:
//   {1, sqrt(3), sqrt(5), sqrt(y), sqrt(15), sqrt(3y), sqrt(5y), sqrt(15y)}
// where `y = 10 - 2*sqrt(5)`, with `/16` implicit denominator.
//
// Real-sign extraction is **exact** via `signum_sum_sqrt_expr_8_zz60`
// (closed-form reduction `Q(sqrt(3), sqrt(5), sqrt(y))` -> biquadratic
// `Q(sqrt(3), sqrt(5))`, where `signum_sum_sqrt_expr_4(_, 1, _, 3, _, 5,
// _, 15)` applies exactly since `m * n = l` for `m=3, n=5, l=15`).
//
// The `re_decomp` / `im_decomp` tables are hand-rolled from the
// half-angle / sum-of-arc identities and verified by the generic
// `complex64_unit_matches_exp` property test.

#[inline]
fn zz60_complex64(coeffs: &[i64; 16]) -> Complex64 {
    // Symbolic-projection: project the integer-basis vector to a
    // K-vector in the symbolic-roots basis (using `*_DECOMP`), evaluate
    // each component as `c * sqrt(N)` in f64, then divide by the
    // implicit `/16` denominator. Keeps the bit-exact f64 round-trip in
    // `cyclotomic::constants::tests::test_constants`.
    let sq3 = 3.0_f64.sqrt();
    let sq5 = 5.0_f64.sqrt();
    let sq15 = 15.0_f64.sqrt();
    let sqy = ZZ10_Y.sqrt();
    let sq3y = (3.0 * ZZ10_Y).sqrt();
    let sq5y = (5.0 * ZZ10_Y).sqrt();
    let sq15y = (15.0 * ZZ10_Y).sqrt();

    let proj = |table: &[[i64; 8]; 16]| -> f64 {
        let mut acc = [0i64; 8];
        for k in 0..16 {
            let ck = coeffs[k];
            if ck == 0 {
                continue;
            }
            for j in 0..8 {
                acc[j] += ck * table[k][j];
            }
        }
        (acc[0] as f64
            + (acc[1] as f64) * sq3
            + (acc[2] as f64) * sq5
            + (acc[3] as f64) * sqy
            + (acc[4] as f64) * sq15
            + (acc[5] as f64) * sq3y
            + (acc[6] as f64) * sq5y
            + (acc[7] as f64) * sq15y)
            / 16.0
    };
    let re = proj(&ZZ60_RE_DECOMP);
    let im = proj(&ZZ60_IM_DECOMP);
    Complex64::new(re, im)
}

const ZZ60_CARTESIAN: [Complex64; 16] = {
    // Cached f64 cos/sin pairs for zeta^k = exp(2*pi*i*k/60). Unused at
    // runtime (complex64_fn projects symbolically) but kept as the macro
    // requires a `[Complex64; PHI]` const.
    const fn placeholder() -> Complex64 {
        Complex64::new(0.0, 0.0)
    }
    let mut out = [placeholder(); 16];
    // We cannot call `.cos()` in const context, so leave all-zero. The
    // values are recomputed every call in zz60_complex64.
    out[0] = Complex64::new(1.0, 0.0);
    out
};

// `Re(zeta^k)` / `Im(zeta^k)` decomposition tables in the symbolic basis
// {1, sqrt(3), sqrt(5), sqrt(y), sqrt(15), sqrt(3y), sqrt(5y), sqrt(15y)},
// `/16` implicit. Correctness checked by `complex64_unit_matches_exp`.
const ZZ60_RE_DECOMP: [[i64; 8]; 16] = [
    [16, 0, 0, 0, 0, 0, 0, 0],
    [0, 2, 0, 2, 2, 0, 0, 0],
    [-2, 0, 2, 0, 0, 1, 0, 1],
    [0, 0, 0, 2, 0, 0, 2, 0],
    [2, 0, 2, 0, 0, 2, 0, 0],
    [0, 8, 0, 0, 0, 0, 0, 0],
    [4, 0, 4, 0, 0, 0, 0, 0],
    [0, -2, 0, 1, 2, 0, 1, 0],
    [2, 0, -2, 0, 0, 1, 0, 1],
    [0, 0, 0, 4, 0, 0, 0, 0],
    [8, 0, 0, 0, 0, 0, 0, 0],
    [0, 2, 0, -2, 2, 0, 0, 0],
    [-4, 0, 4, 0, 0, 0, 0, 0],
    [0, 2, 0, 1, -2, 0, 1, 0],
    [-2, 0, -2, 0, 0, 2, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0],
];

const ZZ60_IM_DECOMP: [[i64; 8]; 16] = [
    [0, 0, 0, 0, 0, 0, 0, 0],
    [-2, 0, -2, 0, 0, 2, 0, 0],
    [0, 2, 0, 1, -2, 0, 1, 0],
    [-4, 0, 4, 0, 0, 0, 0, 0],
    [0, 2, 0, -2, 2, 0, 0, 0],
    [8, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 4, 0, 0, 0, 0],
    [2, 0, -2, 0, 0, 1, 0, 1],
    [0, -2, 0, 1, 2, 0, 1, 0],
    [4, 0, 4, 0, 0, 0, 0, 0],
    [0, 8, 0, 0, 0, 0, 0, 0],
    [2, 0, 2, 0, 0, 2, 0, 0],
    [0, 0, 0, 2, 0, 0, 2, 0],
    [-2, 0, 2, 0, 0, 1, 0, 1],
    [0, 2, 0, 2, 2, 0, 0, 0],
    [16, 0, 0, 0, 0, 0, 0, 0],
];

fn zz60_display(coeffs: &[i64; 16], f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    let sixteenth = Ratio::<i64>::new_raw(1, 16);
    // Project to (Ratio, Ratio) coefficient pairs of the symbolic basis, each
    // with the implicit /16 folded in.
    let mut k_coeffs: [(Ratio<i64>, Ratio<i64>); 8] =
        [gpair(Ratio::<i64>::from_integer(0), Ratio::<i64>::from_integer(0)); 8];
    for j in 0..8 {
        let mut re_acc: i64 = 0;
        let mut im_acc: i64 = 0;
        for k in 0..16 {
            re_acc += coeffs[k] * ZZ60_RE_DECOMP[k][j];
            im_acc += coeffs[k] * ZZ60_IM_DECOMP[k][j];
        }
        k_coeffs[j] = gpair(
            Ratio::<i64>::from_integer(re_acc) * sixteenth,
            Ratio::<i64>::from_integer(im_acc) * sixteenth,
        );
    }
    format_symbolic(
        &k_coeffs,
        &[
            "1",
            "3",
            "5",
            "2(5-sqrt(5))",
            "15",
            "6(5-sqrt(5))",
            "10(5-sqrt(5))",
            "30(5-sqrt(5))",
        ],
        f,
    )
}

/// Sign of an 8-component K-vector in the ZZ60 real subring basis. Exact
/// via the closed-form `signum_sum_sqrt_expr_8_zz60`. i128 is mandatory
/// here: the 8-arg helper composes two levels of squaring, and i64
/// overflows on `within_radius` inputs (squared norm of generic
/// ring elements).
#[inline]
fn zz60_real_sign(x: &[i64; 8]) -> i8 {
    crate::cyclotomic::sign::signum_sum_sqrt_expr_8_zz60::<i128>(
        x[0] as i128,
        x[1] as i128,
        x[2] as i128,
        x[3] as i128,
        x[4] as i128,
        x[5] as i128,
        x[6] as i128,
        x[7] as i128,
    ) as i8
}

define_integral_zz! {
    name: ZZ60,
    n: 60,
    phi: 16,
    real_dim: 8,
    // Phi_60(x) = x^16 + x^14 - x^10 - x^8 - x^6 + x^2 + 1, so
    // zeta^16 = -zeta^14 + zeta^10 + zeta^8 + zeta^6 - zeta^2 - 1.
    reduction: [-1i64, 0, -1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, -1, 0],
    re_decomp: ZZ60_RE_DECOMP,
    im_decomp: ZZ60_IM_DECOMP,
    cartesian: ZZ60_CARTESIAN,
    one_in_real_basis: [16i64, 0, 0, 0, 0, 0, 0, 0],
    display_fn: zz60_display,
    complex64_fn: zz60_complex64,
    has: [HasZZ4Impl, HasZZ6Impl, HasZZ10Impl, HasZZ12Impl],
}

impl From<(i64, i64)> for ZZ60 {
    /// `(re, im)` where `i = zeta^15`, so `(a, b) = a + b*i` maps to
    /// integer-basis coefficients with `b` at position 15.
    #[inline]
    fn from((re, im): (i64, i64)) -> Self {
        let mut c = [0i64; 16];
        c[0] = re;
        c[15] = im;
        Self::from_int_coeffs(c)
    }
}

crate::impl_integral_units_via_basis!(ZZ60, 60);
crate::impl_integral_mul_via_basis!(ZZ60, 16);
crate::impl_integral_conj_via_basis!(ZZ60, 16);
crate::impl_integral_re_im_sign_via_basis!(ZZ60, 16, 8, zz60_real_sign);
crate::impl_integral_intersect_unit_segments_via_basis!(ZZ60, 16, 8, zz60_real_sign);
crate::impl_integral_within_radius_via_norm_sq!(ZZ60);
impl_cell_floor_via_sign_verify!(ZZ60);
crate::zz_integral_ring_tests!(name: ZZ60);

// ----------------
// ZZ32 -- Z[zeta_32].
//
// `zeta = e^(2*pi*i/32) = cos(11.25) + i*sin(11.25)`, `Phi_32(x) = x^16 + 1`,
// so `zeta^16 = -1`. Storage: `[i64; 16]` over `{1, zeta, ..., zeta^15}`.
//
// The real subring is `Q(sqrt(2), sqrt(2+sqrt(2)), sqrt(2+sqrt(2+sqrt(2))))`,
// dim 8, basis:
//   {1, sqrt(2), sqrt(2+sqrt(2)), sqrt(2+sqrt(2+sqrt(2))),
//    sqrt(2(2+sqrt(2))), sqrt(2(2+sqrt(2+sqrt(2)))),
//    sqrt((2+sqrt(2))(2+sqrt(2+sqrt(2)))),
//    sqrt(2(2+sqrt(2))(2+sqrt(2+sqrt(2))))}
// with `/2` implicit denominator.
//
// Real-sign extraction is **exact** via `signum_sum_sqrt_expr_8_zz32`
// (two-level recursive reduction `Q(sqrt(2), sqrt(2+sqrt(2)), sqrt(...))`
// -> `Q(sqrt(2), sqrt(2+sqrt(2)))` (the ZZ16 real subring, with its
// own exact sign helper) -> `Q(sqrt(2))`).
//
// Decomp tables generated via `src/bin/codegen_zz32.rs`.

#[inline]
fn zz32_complex64(coeffs: &[i64; 16]) -> Complex64 {
    let sq2 = std::f64::consts::SQRT_2;
    let sq_y = ZZ16_Y.sqrt(); // sqrt(2+sqrt(2))
    let sq_z = ZZ32_Z.sqrt(); // sqrt(2+sqrt(2+sqrt(2)))
    let sq_2y = (2.0 * ZZ16_Y).sqrt();
    let sq_2z = (2.0 * ZZ32_Z).sqrt();
    let sq_yz = (ZZ16_Y * ZZ32_Z).sqrt();
    let sq_2yz = (2.0 * ZZ16_Y * ZZ32_Z).sqrt();

    let proj = |table: &[[i64; 8]; 16]| -> f64 {
        let mut acc = [0i64; 8];
        for k in 0..16 {
            let ck = coeffs[k];
            if ck == 0 {
                continue;
            }
            for j in 0..8 {
                acc[j] += ck * table[k][j];
            }
        }
        (acc[0] as f64
            + (acc[1] as f64) * sq2
            + (acc[2] as f64) * sq_y
            + (acc[3] as f64) * sq_z
            + (acc[4] as f64) * sq_2y
            + (acc[5] as f64) * sq_2z
            + (acc[6] as f64) * sq_yz
            + (acc[7] as f64) * sq_2yz)
            * 0.5
    };
    let re = proj(&ZZ32_RE_DECOMP);
    let im = proj(&ZZ32_IM_DECOMP);
    Complex64::new(re, im)
}

const ZZ32_CARTESIAN: [Complex64; 16] = {
    // Placeholder (macro requires a const). Real values come from the
    // hand-rolled `complex64_fn` above.
    let mut out = [Complex64::new(0.0, 0.0); 16];
    out[0] = Complex64::new(1.0, 0.0);
    out
};

// Decomposition tables. Auto-generated via `src/bin/codegen_zz32.rs`.
const ZZ32_RE_DECOMP: [[i64; 8]; 16] = [
    [2, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 1, 0, 0, 0, 0],
    [0, 0, 1, 0, 0, 0, 0, 0],
    [0, 0, 0, -1, 0, 0, 1, 0],
    [0, 1, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 1, 0, 1, -1, 0],
    [0, 0, -1, 0, 1, 0, 0, 0],
    [0, 0, 0, -1, 0, -1, 0, 1],
    [0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 1, 0, 1, 0, -1],
    [0, 0, 1, 0, -1, 0, 0, 0],
    [0, 0, 0, -1, 0, -1, 1, 0],
    [0, -1, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 1, 0, 0, -1, 0],
    [0, 0, -1, 0, 0, 0, 0, 0],
    [0, 0, 0, -1, 0, 0, 0, 0],
];

const ZZ32_IM_DECOMP: [[i64; 8]; 16] = [
    [0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, -1, 0, -1, 0, 1],
    [0, 0, -1, 0, 1, 0, 0, 0],
    [0, 0, 0, 1, 0, 1, -1, 0],
    [0, 1, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, -1, 0, 0, 1, 0],
    [0, 0, 1, 0, 0, 0, 0, 0],
    [0, 0, 0, 1, 0, 0, 0, 0],
    [2, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 1, 0, 0, 0, 0],
    [0, 0, 1, 0, 0, 0, 0, 0],
    [0, 0, 0, -1, 0, 0, 1, 0],
    [0, 1, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 1, 0, 1, -1, 0],
    [0, 0, -1, 0, 1, 0, 0, 0],
    [0, 0, 0, -1, 0, -1, 0, 1],
];

fn zz32_display(coeffs: &[i64; 16], f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    let half = Ratio::<i64>::new_raw(1, 2);
    let mut k_coeffs: [(Ratio<i64>, Ratio<i64>); 8] =
        [gpair(Ratio::<i64>::from_integer(0), Ratio::<i64>::from_integer(0)); 8];
    for j in 0..8 {
        let mut re_acc: i64 = 0;
        let mut im_acc: i64 = 0;
        for k in 0..16 {
            re_acc += coeffs[k] * ZZ32_RE_DECOMP[k][j];
            im_acc += coeffs[k] * ZZ32_IM_DECOMP[k][j];
        }
        k_coeffs[j] = gpair(
            Ratio::<i64>::from_integer(re_acc) * half,
            Ratio::<i64>::from_integer(im_acc) * half,
        );
    }
    format_symbolic(
        &k_coeffs,
        &[
            "1",
            "2",
            "2+sqrt(2)",
            "2+sqrt(2+sqrt(2))",
            "2(2+sqrt(2))",
            "2(2+sqrt(2+sqrt(2)))",
            "(2+sqrt(2))(2+sqrt(2+sqrt(2)))",
            "2(2+sqrt(2))(2+sqrt(2+sqrt(2)))",
        ],
        f,
    )
}

#[inline]
fn zz32_real_sign(x: &[i64; 8]) -> i8 {
    // i128 is mandatory: the 8-arg helper composes two levels of
    // squaring, and i64 overflows on `within_radius` inputs (squared
    // norm of generic ring elements).
    crate::cyclotomic::sign::signum_sum_sqrt_expr_8_zz32::<i128>(
        x[0] as i128,
        x[1] as i128,
        x[2] as i128,
        x[3] as i128,
        x[4] as i128,
        x[5] as i128,
        x[6] as i128,
        x[7] as i128,
    ) as i8
}

define_integral_zz! {
    name: ZZ32,
    n: 32,
    phi: 16,
    real_dim: 8,
    // Phi_32(x) = x^16 + 1, so zeta^16 = -1.
    reduction: [-1i64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    re_decomp: ZZ32_RE_DECOMP,
    im_decomp: ZZ32_IM_DECOMP,
    cartesian: ZZ32_CARTESIAN,
    one_in_real_basis: [2i64, 0, 0, 0, 0, 0, 0, 0],
    display_fn: zz32_display,
    complex64_fn: zz32_complex64,
    has: [HasZZ4Impl, HasZZ8Impl],
}

impl From<(i64, i64)> for ZZ32 {
    /// `(re, im)` where `i = zeta^8`, so `(a, b) = a + b*i` maps with
    /// `b` at position 8.
    #[inline]
    fn from((re, im): (i64, i64)) -> Self {
        let mut c = [0i64; 16];
        c[0] = re;
        c[8] = im;
        Self::from_int_coeffs(c)
    }
}

crate::impl_integral_units_via_basis!(ZZ32, 32);
crate::impl_integral_mul_via_basis!(ZZ32, 16);
crate::impl_integral_conj_via_basis!(ZZ32, 16);
crate::impl_integral_re_im_sign_via_basis!(ZZ32, 16, 8, zz32_real_sign);
crate::impl_integral_intersect_unit_segments_via_basis!(ZZ32, 16, 8, zz32_real_sign);
crate::impl_integral_within_radius_via_norm_sq!(ZZ32);
impl_cell_floor_via_sign_verify!(ZZ32);
crate::zz_integral_ring_tests!(name: ZZ32);

// ----------------
// Cross-ring tests not covered by the generic `zz_integral_ring_tests!`
// suite per-ring above.
//
// The generic suite (defined in `integral_basis.rs` and invoked once per
// ring) covers algebra axioms, conjugation, Re/Im sign vs complex64,
// power-of-zeta cycles, intersect-unit-segments, and hashability. What
// remains here is:
//   * `test_display` -- assertions on the literal `format!()` output of
//     specific ring values. The per-ring `display_fn` is bespoke and
//     not exercised by the generic suite.
//   * a couple of ZZ12-specific identities (zeta^3 = i, zz_units_sum
//     classification) that don't lift naturally to a generic property.

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cyclotomic::constants::zz_units_sum;
    use crate::cyclotomic::traits::OneImag;
    use crate::cyclotomic::{Ccw, ZZComplex};
    use num_traits::{One, Pow, Zero};

    /// Exercises each per-ring `display_fn` end-to-end: zero, integer
    /// constants, a non-trivial sum, and the `zz_units_sum` of ZZ10
    /// (whose symbolic shape mixes positive and negative coefficients
    /// across all four basis labels).
    #[test]
    fn test_display() {
        let x = ZZ24::zero();
        assert_eq!(format!("{x}"), "0");

        let x = ZZ24::one();
        assert_eq!(format!("{x}"), "1");

        let x = ZZ24::one() + ZZ24::one();
        assert_eq!(format!("{x}"), "2");

        let x = -ZZ24::one();
        assert_eq!(format!("{x}"), "-1");

        let x = ZZ24::one() + (ZZ24::ccw()).pow(2i8);
        assert_eq!(format!("{x}"), "1+1/2i + (1/2)*sqrt(3)");

        let x: ZZ10 = zz_units_sum();
        assert_eq!(
            format!("{x}"),
            "-5 + (-15/4i)*sqrt(2(5-sqrt(5))) + (-5/4i)*sqrt(10(5-sqrt(5)))"
        );
    }

    /// `zeta_12^3 = i`. Exercises the `OneImag` blanket impl on a ring
    /// that contains `i` at a non-axis-aligned power of `zeta`.
    #[test]
    fn test_zz12_zeta_cubed_is_i() {
        let z = ZZ12::ccw();
        let i = z * z * z;
        assert_eq!(i, ZZ12::one_i());
        assert_eq!(i * i, -ZZ12::one());
    }

    /// `zz_units_sum` for ZZ12 lands at a strictly-complex point (i.e.
    /// neither real nor imaginary). Sanity check that the
    /// `ZZComplex::is_complex()` predicate fires correctly on a
    /// non-trivial value built from `Units::unit` + `scale`.
    #[test]
    fn test_zz12_units_sum_is_complex() {
        let p: ZZ12 = zz_units_sum();
        assert!(p.is_complex());
    }

    /// Independent cross-check of ZZ14's `cell_floor_exact`, the one
    /// blessed ring whose Re/Im decomposition coefficients (`m0..m2`,
    /// `n0..n2`) are hand-inlined rather than driven by the
    /// `RE_DECOMP`/`IM_DECOMP` tables, and which has no step-subset
    /// reduction to an OEIS-pinned ring. A miswired coefficient would
    /// make the exact refinement converge to the wrong cell.
    ///
    /// For random points that sit comfortably OFF a cell boundary the
    /// f64 floor of `complex64()` is exact and fully independent of
    /// the hand-derived integer path, so it pins the coefficients. We
    /// skip near-boundary points (where f64 is the unreliable one --
    /// that measure-zero set is exactly why ZZ14 overrides to exact).
    #[test]
    fn zz14_cell_floor_exact_matches_f64_off_boundary() {
        use crate::cyclotomic::{CellFloor, SymNum};
        let mut seed: u64 = 0x9E3779B97F4A7C15;
        let mut next = || {
            seed ^= seed << 13;
            seed ^= seed >> 7;
            seed ^= seed << 17;
            seed
        };
        let mut checked = 0u32;
        for _ in 0..6_000 {
            // Modest coefficients (range comparable to enumeration
            // lattice points); large enough to exercise all six basis
            // components in the m/n combinations.
            let coeffs: [i64; 6] = std::array::from_fn(|_| (next() % 41) as i64 - 20);
            let z = ZZ14::from_int_coeffs(coeffs);
            let c = z.complex64();
            let re_frac = c.re - c.re.floor();
            let im_frac = c.im - c.im.floor();
            // f64 is only trustworthy away from the half-open cell edges.
            let near_edge = |f: f64| !(1e-6..=1.0 - 1e-6).contains(&f);
            if near_edge(re_frac) || near_edge(im_frac) {
                continue;
            }
            assert_eq!(
                z.cell_floor_exact(),
                (c.re.floor() as i64, c.im.floor() as i64),
                "ZZ14 cell_floor_exact disagrees with f64 off-boundary for coeffs {coeffs:?} \
                 -- a miswired Re/Im decomposition coefficient",
            );
            checked += 1;
        }
        assert!(checked > 2_000, "too few off-boundary samples ({checked})");
    }
}