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
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
// Copyright 2015 The Ramp Developers
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//
//        http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.

//! This module holds `Int` and related types.

use rand::Rng;
use std;
use std::cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd};
use std::error::Error;
use std::ops::{
    Add, AddAssign, BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Div, DivAssign,
    Mul, MulAssign, Neg, Rem, RemAssign, Shl, ShlAssign, Shr, ShrAssign, Sub, SubAssign,
};
use std::ptr::Unique;
use std::str::FromStr;
use std::{fmt, hash, io};

use hamming;
use num_integer::Integer;
use num_traits::{Num, One, Zero};

use ll;
use ll::limb::{BaseInt, Limb};
use ll::limb_ptr::{Limbs, LimbsMut};

use alloc::raw_vec::RawVec;

use traits::DivRem;

///
/// An arbitrary-precision signed integer.
///
/// This type grows to the size it needs to in order to store the result of any operation.
///
/// ## Creation
///
/// An `Int` can be constructed in a number of ways:
///
/// - `Int::zero` and `Int::one` construct a zero- and one-valued `Int` respectively.
///
/// - `Int::from` will convert from any primitive integer type to an `Int` of the same value
///
///   ```
///   # use ramp::Int;
///   let four = Int::from(4);
///   ```
///
/// - `Int::from_str` (or `str::parse`) will attempt to convert from a string to an `Int`
///
///   ```
///   # use ramp::Int;
///   # use std::str::FromStr;
///   let i = Int::from_str("123456789").unwrap();
///   ```
///
/// ## Output
///
/// `Int` supports all the formatting traits, allowing it to be used just like a regular integer
/// when used in `format!` and similar macros. `Int` also supports conversion to primitive integer
/// types, truncating if the `Int` cannot fit into the target type. Conversion to primtive integers
/// is done with the `From` trait:
///
///   ```
///   # use ramp::Int;
///   let big_i   = Int::from(123456789);
///   let i = i32::from(&big_i);
///   assert_eq!(123456789, i);
///   ```
///
/// ## Usage
///
/// `Int` has a number of operator overloads to make working with them as painless as possible.
///
/// The most basic usage is simply `a + b` or similar. Assuming `a` and `b` are of type `Int`, this
/// operation will consume both operands, reusing the storage from one of them. If you do not wish
/// your operands to be moved, one or both of them can be references: `&a + &b` works as well, but
/// requires an entire new `Int` to be allocated for the return value.
///
/// There are also a overloads for a small number of primitive integer types, namely `i32` and
/// `usize`. While automatic type widening isn't done in Rust in general, many operations are much
/// more efficient when working with a single integer. This means you can do `a + 1` knowing that it
/// will be performed as efficiently as possible. Comparison with these integer types is also
/// possible, allowing checks for small constant values to be done easily:
///
///   ```
///   # use ramp::Int;
///   let big_i   = Int::from(123456789);
///   assert!(big_i == 123456789);
///   ```
///
/// ### Semantics
///
/// Addition, subtraction and multiplication follow the expected rules for integers. Division of two
/// integers, `N / D` is defined as producing two values: a quotient, `Q`, and a remainder, `R`,
/// such that the following equation holds: `N = Q*D + R`. The division operator itself returns `Q`
/// while the remainder/modulo operator returns `R`. The sign of `R` is the same as the sign of `Q`.
///
/// The "bit-shift" operations are defined as being multiplication and division by a power-of-two for
/// shift-left and shift-right respectively. The sign of the number is unaffected.
///
/// The remaining bitwise operands act as if the numbers are stored in two's complement format and as
/// if the two inputs have the same number of bits.
pub struct Int {
    ptr: Unique<Limb>,
    size: i32,
    cap: u32,
}

impl Int {
    /// Creates the `Int` that represents zero.
    pub fn zero() -> Int {
        <Int as Zero>::zero()
    }

    /// Creates the `Int` that represents one.
    pub fn one() -> Int {
        <Int as One>::one()
    }

    /// Creates an `Int` from a single [`Limb`]
    ///
    /// [`Limb`]: ../ll/limb/struct.Limb.html
    pub fn from_single_limb(limb: Limb) -> Int {
        let mut i = Int::with_capacity(1);
        unsafe {
            *i.ptr.as_mut() = limb;
        }
        i.size = 1;

        i
    }

    /// Passes a `RawVec` version of this `Int`, which can be manipulated to alter this `Int`'s
    /// allocation.
    fn with_raw_vec<F: FnOnce(&mut RawVec<Limb>)>(&mut self, f: F) {
        unsafe {
            let old_cap = self.cap as usize;
            let mut vec = RawVec::from_raw_parts(self.ptr.as_mut(), old_cap);
            // if `f` panics, let `vec` do the cleaning up, not self.
            self.cap = 0;

            f(&mut vec);

            // update `self` for any changes that happened
            // vec.ptr() can't be null, so we can safely unwrap
            self.ptr = Unique::new(vec.ptr()).unwrap();
            let new_cap = vec.capacity();
            assert!(new_cap <= std::u32::MAX as usize);
            self.cap = new_cap as u32;
            // ownership has transferred back into `self`, so make
            // sure that allocation isn't freed by `vec`.
            std::mem::forget(vec);

            if old_cap < new_cap {
                // the allocation got larger, new Limbs should be
                // zero.
                let self_ptr = self.limbs_uninit();
                std::ptr::write_bytes(
                    &mut *self_ptr.offset(old_cap as isize) as *mut _ as *mut u8,
                    0,
                    (new_cap - old_cap) * std::mem::size_of::<Limb>(),
                );
            }
        }
    }

    /// Creates an `Int` with the given capacity.
    fn with_capacity(cap: u32) -> Int {
        let mut ret = Int::zero();
        if cap != 0 {
            ret.with_raw_vec(|v| v.reserve_exact(0, cap as usize))
        }
        ret
    }

    /// Returns the sign of this `Int` as either -1, 0 or 1 depending on whether it is negative,
    /// zero, or positive, respectively.
    #[inline(always)]
    pub fn sign(&self) -> i32 {
        if self.size == 0 {
            0
        } else if self.size < 0 {
            -1
        } else {
            1
        }
    }

    /// Consumes this `Int` and returns its absolute value.
    #[inline]
    pub fn abs(mut self) -> Int {
        self.size = self.size.abs();
        self
    }

    /// Returns the least-significant [`Limb`] of this `Int`.
    ///
    /// [`Limb`]: ../ll/limb/struct.Limb.html
    #[inline]
    pub fn to_single_limb(&self) -> Limb {
        if self.sign() == 0 {
            return Limb(0);
        } else {
            return unsafe { *self.ptr.as_ref() };
        }
    }

    /// Gets the absolute value of this `Int`'s size.
    #[inline(always)]
    fn abs_size(&self) -> i32 {
        self.size.abs()
    }

    /// Compares the absolute value of this `Int` with the absolute value of another.
    pub fn abs_cmp(&self, other: &Int) -> Ordering {
        if self.abs_size() > other.abs_size() {
            Ordering::Greater
        } else if self.abs_size() < other.abs_size() {
            Ordering::Less
        } else {
            unsafe { ll::cmp(self.limbs(), other.limbs(), self.abs_size()) }
        }
    }

    /// Returns whether this `Int` has the same absolute value as another.
    pub fn abs_eq(&self, other: &Int) -> bool {
        self.abs_cmp(other) == Ordering::Equal
    }

    /// Hashes the value without including the sign.
    ///
    /// This is useful for when the sign is handled elsewhere and making a copy just to change the
    /// sign is wasteful.
    pub fn abs_hash<H>(&self, state: &mut H)
    where
        H: hash::Hasher,
    {
        use std::hash::Hash;
        let mut size = self.abs_size();
        unsafe {
            let mut ptr = self.limbs();
            while size > 0 {
                let l = *ptr;
                l.hash(state);

                ptr = ptr.offset(1);
                size -= 1;
            }
        }
    }

    /// Shrinks the allocated data for this `Int`, attempting to remove excess capacity.
    pub fn shrink_to_fit(&mut self) {
        let mut size = self.abs_size() as usize;

        if (self.cap as usize) == size {
            return;
        } // already as small as possible

        if size == 0 {
            size = 1;
        } // Keep space for at least one limb around

        self.with_raw_vec(|v| {
            v.shrink_to_fit(size);
        })
    }

    /// Creates a string containing the value of this `Int` in base `base`.
    ///
    /// For bases greater than ten, if `upper` is true, upper-case letters are used; otherwise,
    /// lower-case letters are used.
    ///
    /// # Panics
    ///
    /// Panics if `base` is less than two or greater than 36.
    pub fn to_str_radix(&self, base: u8, upper: bool) -> String {
        if self.size == 0 {
            return "0".to_string();
        }

        if base < 2 || base > 36 {
            panic!("Invalid base: {}", base);
        }

        let size = self.abs_size();
        let mut num_digits =
            unsafe { ll::base::num_base_digits(self.limbs(), size - 1, base as u32) };

        if self.sign() == -1 {
            num_digits += 1;
        }

        let mut buf: Vec<u8> = Vec::with_capacity(num_digits);

        self.write_radix(&mut buf, base, upper).unwrap();

        unsafe { String::from_utf8_unchecked(buf) }
    }

    /// Similar to `to_str_radix`, writing to something that implements `io::Write` instead.
    pub fn write_radix<W: io::Write>(&self, w: &mut W, base: u8, upper: bool) -> io::Result<()> {
        debug_assert!(self.well_formed());

        if self.sign() == -1 {
            w.write_all(b"-")?;
        }

        let letter = if upper { b'A' } else { b'a' };
        let size = self.abs_size();

        unsafe {
            ll::base::to_base(base as u32, self.limbs(), size, |b| {
                if b < 10 {
                    w.write_all(&[b + b'0']).unwrap();
                } else {
                    w.write_all(&[(b - 10) + letter]).unwrap();
                }
            });
        }

        Ok(())
    }

    /// Creates a new Int from the given string in base `base`.
    pub fn from_str_radix(mut src: &str, base: u8) -> Result<Int, ParseIntError> {
        if base < 2 || base > 36 {
            panic!("Invalid base: {}", base);
        }

        let mut sign = 1;
        if src.starts_with('-') {
            sign = -1;
            src = &src[1..];
        }

        if src.len() == 0 {
            return Err(ParseIntError {
                kind: ErrorKind::Empty,
            });
        }

        // Strip leading zeros
        let zeros = src.chars().take_while(|&digit| digit == '0').count();
        src = &src[zeros..];
        if src.len() == 0 {
            return Ok(Int::zero());
        }

        let mut buf = Vec::with_capacity(src.len());
        for c in src.bytes() {
            let b = match c {
                b'0'..=b'9' => c - b'0',
                b'A'..=b'Z' => (c - b'A') + 10,
                b'a'..=b'z' => (c - b'a') + 10,
                _ => {
                    return Err(ParseIntError {
                        kind: ErrorKind::InvalidDigit,
                    });
                }
            };

            if b >= base {
                return Err(ParseIntError {
                    kind: ErrorKind::InvalidDigit,
                });
            }

            buf.push(b);
        }

        let num_digits = ll::base::base_digits_to_len(src.len(), base as u32);

        let mut i = Int::with_capacity(num_digits as u32);

        unsafe {
            let size = ll::base::from_base(
                i.limbs_uninit(),
                buf.as_ptr(),
                buf.len() as i32,
                base as u32,
            );
            i.size = (size as i32) * sign;
        }

        Ok(i)
    }

    /// Divides this `Int` by `other`, returning the quotient `q` and the remainder `r` as `(q, r)`.
    ///
    /// This satisfies `self = q * other + r`, ensuring that `q` and `r` have the same sign.
    ///
    /// # Panics
    ///
    /// Panics if `other` is zero.
    pub fn divmod(&self, other: &Int) -> (Int, Int) {
        debug_assert!(self.well_formed());
        debug_assert!(other.well_formed());
        if other.sign() == 0 {
            ll::divide_by_zero();
        }
        if self.sign() == 0 {
            return (self.clone(), Int::zero());
        }

        let out_size = if self.abs_size() < other.abs_size() {
            1
        } else {
            (self.abs_size() - other.abs_size()) + 1
        };

        let out_sign = self.sign() * other.sign();
        let mut q = Int::with_capacity(out_size as u32);
        q.size = out_size * out_sign;

        let mut r = Int::with_capacity(other.abs_size() as u32);
        r.size = other.abs_size() * self.sign();

        unsafe {
            ll::divrem(
                q.limbs_mut(),
                r.limbs_mut(),
                self.limbs(),
                self.abs_size(),
                other.limbs(),
                other.abs_size(),
            );
        }

        q.normalize();
        r.normalize();

        (q, r)
    }

    /// Raises this `Int` to the power of `exp`. `0^0 = 1`.
    pub fn pow(&self, exp: usize) -> Int {
        debug_assert!(self.well_formed());
        match exp {
            0 => Int::one(),
            1 => self.clone(),
            2 => self.square(),
            _ => {
                let mut signum = self.sign();
                if signum == 0 {
                    return Int::zero();
                }
                if exp & 1 == 0 {
                    signum = 1
                }

                let ret_sz =
                    unsafe { ll::pow::num_pow_limbs(self.limbs(), self.abs_size(), exp as u32) };
                let mut ret = Int::with_capacity(ret_sz as u32);
                ret.size = ret_sz * signum;

                unsafe {
                    ll::pow::pow(ret.limbs_mut(), self.limbs(), self.abs_size(), exp as u32);
                }

                ret.normalize();

                ret
            }
        }
    }

    /// Raises this `Int` to the power `exp`, all modulo `modulus`. `0^0 mod m = 1 mod m`
    ///
    /// # Panics
    ///
    /// Panics if `exp` is negative or `modulus` is zero.
    pub fn pow_mod(&self, exp: &Int, modulus: &Int) -> Int {
        // Take care of invalid modulus
        if modulus.sign() == 0 {
            panic!("Got a zero modulus");
        }
        // Early return for non-positive exponents
        match exp.sign() {
            -1 => panic!("Got a negative exponent: {}", exp),
            0 => return Int::one() % modulus, // this ends up being 0 iff modulus == 1
            _ => (),
        }

        let base = self % modulus;
        if base.sign() == 0 {
            return Int::zero();
        }
        let mut result = Int::one();

        for i in (0..exp.bit_length()).rev() {
            result = result.dsquare() % modulus;

            // Accumulate current base if current exponent bit is 1
            if exp.bit(i) {
                result = (result * &base) % modulus;
            }
        }

        result
    }

    /// Squares this `Int`.
    pub fn square(&self) -> Int {
        debug_assert!(self.well_formed());
        let s = self.sign();
        if s == 0 {
            Int::zero()
        } else if self.abs_size() == 1 {
            let a = self.clone() * self.to_single_limb();
            if s == -1 {
                a.abs()
            } else if s == 1 {
                a
            } else {
                unreachable!()
            }
        } else {
            let sz = self.abs_size() * 2;
            let mut ret = Int::with_capacity(sz as u32);
            ret.size = sz;
            unsafe {
                ll::sqr(ret.limbs_mut(), self.limbs(), self.abs_size());
            }
            ret.normalize();

            ret
        }
    }

    /// Consumes this `Int` and returns its square.
    ///
    /// TODO: Is there a more idiomatic way of doing this?
    pub fn dsquare(mut self) -> Int {
        debug_assert!(self.well_formed());
        let s = self.sign();
        if s == 0 {
            Int::zero()
        } else if self.abs_size() == 1 {
            let l = self.to_single_limb();
            self = self * l;
            if s == -1 {
                self.abs()
            } else if s == 1 {
                self
            } else {
                unreachable!()
            }
        } else {
            self.square()
        }
    }

    /// Computes the nearest square root `s` of this number and its remainder `r` as
    /// `Some((s, r))`, or `None` if this `Int` is negative.
    ///
    /// `s` and `r` are both positive and satisfy `self = s * s + r`.
    pub fn sqrt_rem(mut self) -> Option<(Int, Int)> {
        debug_assert!(self.well_formed());

        if self.sign() < 0 {
            return None;
        }

        // the floor of a (correctly rounded) f64 sqrt gives the right
        // answer, until this number (it is 67108865**2 - 1, but
        // f64::sqrt is rounded *up* to 67108865 precisely).
        if self < 4_503_599_761_588_224_u64 {
            let this = u64::from(&self);
            let sqrt = (this as f64).sqrt().floor() as u64;
            let rem = this - sqrt * sqrt;

            // reuse the memory
            self.size = 0;
            self.push(Limb(sqrt as BaseInt));
            self.normalize();

            Some((self, Int::from(rem)))
        } else {
            let n = self.bit_length();
            let l = (n as usize - 1) / 4;
            assert!(l > 0);

            let mask = (Int::from(1) << l) - 1;
            let low = &self & &mask;
            self >>= l;
            let mut middle = &self & mask;
            self >>= l;
            let (high_sqrt, mut high_rem) = self.sqrt_rem().unwrap();

            high_rem <<= l;
            middle |= high_rem;
            let (q, u) = middle.divmod(&(&high_sqrt << 1));

            let mut s = (high_sqrt << l) + &q;
            let mut r = (u << l) + low - q.dsquare();

            if r < 0 {
                r += &s << 1;
                r -= 1;
                s -= 1;
            }
            debug_assert!(r >= 0);
            Some((s, r))
        }
    }

    /// Negates this `Int` in place.
    pub fn negate(&mut self) {
        self.size *= -1;
    }

    /// Returns whether this `Int` is even.
    #[inline]
    pub fn is_even(&self) -> bool {
        debug_assert!(self.well_formed());
        (self.to_single_limb().0 & 1) == 0
    }

    /// Returns the number of trailing zero bits for this `Int`, or zero if this `Int` is zero.
    #[inline]
    pub fn trailing_zeros(&self) -> u32 {
        debug_assert!(self.well_formed());
        if self.sign() == 0 {
            0
        } else {
            unsafe { ll::scan_1(self.limbs(), self.abs_size()) }
        }
    }

    /// Returns the number of trailing one bits (i.e. the population count) for this `Int`
    ///
    /// If this number is negative, it has infinitely many ones (in two's complement). Therefore,
    /// this method returns `usize::MAX` for negative numbers.
    pub fn count_ones(&self) -> usize {
        debug_assert!(self.well_formed());
        if self.sign() < 0 {
            std::usize::MAX
        } else {
            let bytes = unsafe {
                std::slice::from_raw_parts(
                    self.ptr.as_ref() as *const _ as *const u8,
                    self.abs_size() as usize * std::mem::size_of::<Limb>(),
                )
            };
            hamming::weight(bytes) as usize
        }
    }

    /// Returns the number of bits required to represent the absolute value of this `Int`, i.e.,
    /// `floor(log2(abs(self))) + 1`.
    ///
    /// Returns one if this number is zero.
    #[inline]
    pub fn bit_length(&self) -> u32 {
        if *self == 0 {
            1
        } else {
            unsafe { ll::base::num_base_digits(self.limbs(), self.abs_size(), 2) as u32 }
        }
    }

    /// Returns the value of the `bit`th bit in this `Int`, as if it were represented in two's
    /// complement.
    #[inline]
    pub fn bit(&self, bit: u32) -> bool {
        let word = (bit / Limb::BITS as u32) as isize;
        let subbit = bit % Limb::BITS as u32;
        if word < self.abs_size() as isize {
            let b = unsafe {
                let w: Limb = *self.limbs().offset(word);
                w.0 & (1 << subbit) != 0
            };
            if self.sign() >= 0 {
                b
            } else {
                let first_one = self.trailing_zeros();
                // the number is negative, so, in two's complement,
                // bits up to and including the first one are the same
                // as their sign-magnitude values (... ^ false), while
                // bits beyond that are complemented (... ^ true)
                b ^ (bit > first_one)
            }
        } else {
            // we're beyond the in-memory limbs, so the bits are
            // either all zeros (positive) or all ones (negative)
            self.sign() < 0
        }
    }

    /// Sets the `bit`th bit of this number to `bit_val`, treating negative numbers as if they're
    /// stored in two's complement.
    pub fn set_bit(&mut self, bit: u32, bit_val: bool) {
        debug_assert!(self.well_formed());
        let word = bit / Limb::BITS as u32;
        let subbit = bit % Limb::BITS as u32;
        let flag = Limb(1 << subbit);

        let sign = self.sign();

        unsafe {
            if word >= self.abs_size() as u32 {
                // the bit is beyond the end, so more space is needed,
                // and we need to be careful to ensure it's all zero
                // because they'll all be part of the number itself
                // used once the bit is set
                self.ensure_capacity(word + 1);

                let size = self.abs_size();
                ll::zero(
                    self.limbs_uninit().offset(size as isize),
                    word as i32 - size + 1,
                );

                self.size = word as i32 + 1;
                if sign < 0 {
                    self.size = -self.size
                }
            }

            if sign < 0 {
                // this could probably be replaced by something
                // similar to what `bit` does
                self.negate_twos_complement();
            }

            let mut ptr = self.limbs_mut().offset(word as isize);
            let val = if bit_val { *ptr | flag } else { *ptr & !flag };
            *ptr = val;

            if sign < 0 {
                // put self back to normal
                self.negate_twos_complement();
            }
        }
        self.normalize()
    }

    /// Gets the `Limbs` currently initialised or in use.
    fn limbs(&self) -> Limbs {
        unsafe { Limbs::new(self.ptr.as_ref(), 0, self.abs_size()) }
    }

    /// Gets the `LimbsMut` currently initialised or in use.
    fn limbs_mut(&mut self) -> LimbsMut {
        unsafe { LimbsMut::new(self.ptr.as_mut(), 0, self.abs_size()) }
    }

    /// Gets the `LimbsMut` to all allocated limbs.
    unsafe fn limbs_uninit(&mut self) -> LimbsMut {
        LimbsMut::new(self.ptr.as_mut(), 0, self.cap as i32)
    }

    /// Ensures that the `Int` has at least the given capacity.
    fn ensure_capacity(&mut self, cap: u32) {
        if cap > self.cap {
            let old_cap = self.cap as usize;
            self.with_raw_vec(|v| v.reserve_exact(old_cap, cap as usize - old_cap))
        }
    }

    /// Pushes a `Limb` onto this `Int`.
    fn push(&mut self, limb: Limb) {
        let new_size = (self.abs_size() + 1) as u32;
        self.ensure_capacity(new_size);
        unsafe {
            let pos = self.abs_size();
            *self.limbs_uninit().offset(pos as isize) = limb;
            // If it was previously empty, then just make it positive,
            // otherwise maintain the signedness
            if self.size == 0 {
                self.size = 1;
            } else {
                self.size += self.sign();
            }
        }
    }

    /// Adjusts the size field so that the most-significant `Limb` is non-zero.
    fn normalize(&mut self) {
        if self.size == 0 {
            return;
        }
        let sign = self.sign();
        unsafe {
            while self.size != 0 && *self.ptr.as_ptr().offset((self.abs_size() - 1) as isize) == 0 {
                self.size -= sign;
            }
        }
        debug_assert!(self.well_formed());
    }

    /// Returns whether the `Int` is well-formed, i.e. that the size doesn't exceed the capacity and
    /// that the most significant `Limb` is non-zero.
    fn well_formed(&self) -> bool {
        if self.size == 0 {
            return true;
        }

        if (self.abs_size() as u32) > self.cap {
            return false;
        }

        let high_limb = unsafe { *self.ptr.as_ptr().offset((self.abs_size() - 1) as isize) };

        return high_limb != 0;
    }

    /// Negates this `Int` using two's complement, i.e. `!self + 1`.
    fn negate_twos_complement(&mut self) {
        unsafe {
            let self_ptr = self.limbs_mut();
            let carry = ll::twos_complement(self_ptr, self_ptr.as_const(), self.abs_size());
            if carry != 0 {
                self.push(carry)
            }
        }
        self.size = -self.size;
    }

    /// Computes the greates common divisor (GCD) of this `Int` and `other`.
    ///
    /// The result is always positive.
    #[inline]
    pub fn gcd(&self, other: &Int) -> Int {
        debug_assert!(self.well_formed());
        debug_assert!(other.well_formed());

        let (mut a, mut b) = if self.abs_size() >= other.abs_size() {
            ((*self).clone(), (*other).clone())
        } else {
            ((*other).clone(), (*self).clone())
        };

        if a == Int::zero() {
            return b;
        }

        if b == Int::zero() {
            return a;
        }

        let out_size = a.abs_size();
        let mut r = Int::with_capacity(out_size as u32);
        r.size = out_size;

        unsafe {
            ll::gcd(
                r.limbs_mut(),
                a.limbs_mut(),
                a.abs_size(),
                b.limbs_mut(),
                b.abs_size(),
            );
            r.normalize();
            r
        }
    }

    /// Computes the lowest common multiple (LCM) of this `Int` and `other`.
    #[inline]
    pub fn lcm(&self, other: &Int) -> Int {
        (self * other).abs() / self.gcd(other)
    }

    /// Converts this `Int` into an `f64`.
    ///
    /// This is not an exact conversion, because this `Int` may be more precise than an `f64` can
    /// account for.
    pub fn to_f64(&self) -> f64 {
        let sz = self.abs_size();
        if sz == 0 {
            return 0.0;
        }

        let mut highest_limb = unsafe { *self.limbs().offset((sz - 1) as isize) };
        let leading_zeros = highest_limb.leading_zeros();
        let mut shifted = 0;
        if leading_zeros > 11 && sz > 1 {
            highest_limb = highest_limb << leading_zeros;
            let next_limb = unsafe { *self.limbs().offset((sz - 2) as isize) };

            highest_limb = highest_limb | (next_limb >> (Limb::BITS - leading_zeros as usize));
            shifted = leading_zeros;
        }

        let exp = ((sz - 1) * Limb::BITS as i32) - shifted as i32;

        let f = highest_limb.0 as f64;
        let exp = (2.0f64).powi(exp);
        f * exp
    }
}

impl Clone for Int {
    fn clone(&self) -> Int {
        debug_assert!(self.well_formed());

        if self.sign() == 0 {
            return Int::zero();
        }

        let mut new = Int::with_capacity(self.abs_size() as u32);
        unsafe {
            ll::copy_incr(self.limbs(), new.limbs_uninit(), self.abs_size());
        }
        new.size = self.size;
        new
    }

    fn clone_from(&mut self, other: &Int) {
        debug_assert!(self.well_formed());
        debug_assert!(other.well_formed());

        if other.sign() == 0 {
            self.size = 0;
            return;
        }
        self.ensure_capacity(other.abs_size() as u32);
        unsafe {
            ll::copy_incr(other.limbs(), self.limbs_uninit(), other.abs_size());
            self.size = other.size;
        }
    }
}

impl std::default::Default for Int {
    #[inline]
    fn default() -> Int {
        Int::zero()
    }
}

impl Drop for Int {
    fn drop(&mut self) {
        if self.cap > 0 {
            unsafe {
                drop(RawVec::from_raw_parts(self.ptr.as_mut(), self.cap as usize));
            }
            self.cap = 0;
            self.size = 0;
        }
    }
}

impl PartialEq<Int> for Int {
    #[inline]
    fn eq(&self, other: &Int) -> bool {
        debug_assert!(self.well_formed());
        debug_assert!(other.well_formed());
        if self.size == other.size {
            unsafe { ll::cmp(self.limbs(), other.limbs(), self.abs_size()) == Ordering::Equal }
        } else {
            false
        }
    }
}

impl PartialEq<Limb> for Int {
    #[inline]
    fn eq(&self, other: &Limb) -> bool {
        if *other == 0 && self.size == 0 {
            return true;
        }

        self.size == 1 && *self.limbs() == *other
    }
}

impl PartialEq<Int> for Limb {
    #[inline]
    fn eq(&self, other: &Int) -> bool {
        other.eq(self)
    }
}

impl Eq for Int {}

impl Ord for Int {
    #[inline]
    fn cmp(&self, other: &Int) -> Ordering {
        if self.size < other.size {
            Ordering::Less
        } else if self.size > other.size {
            Ordering::Greater
        } else {
            // Same number of digits and same sign
            // Check for zero
            if self.size == 0 {
                return Ordering::Equal;
            }
            unsafe {
                // If both are positive, do `self cmp other`, if both are
                // negative, do `other cmp self`
                if self.sign() == 1 {
                    ll::cmp(self.limbs(), other.limbs(), self.abs_size())
                } else {
                    ll::cmp(other.limbs(), self.limbs(), self.abs_size())
                }
            }
        }
    }
}

impl PartialOrd<Int> for Int {
    #[inline]
    fn partial_cmp(&self, other: &Int) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl PartialOrd<Limb> for Int {
    #[inline]
    fn partial_cmp(&self, other: &Limb) -> Option<Ordering> {
        if self.eq(other) {
            return Some(Ordering::Equal);
        }

        if self.size < 1 {
            Some(Ordering::Less)
        } else if self.size > 1 {
            Some(Ordering::Greater)
        } else {
            (*self.limbs()).partial_cmp(other)
        }
    }
}

impl PartialOrd<Int> for Limb {
    #[inline]
    fn partial_cmp(&self, other: &Int) -> Option<Ordering> {
        other.partial_cmp(self).map(|o| o.reverse())
    }
}

impl hash::Hash for Int {
    fn hash<H>(&self, state: &mut H)
    where
        H: hash::Hasher,
    {
        debug_assert!(self.well_formed());

        // Normalize the Int so we get consistent hashing (since there are multiple limb
        // representations for the same numeric value)
        let mut n = self.clone();
        n.normalize();
        n.sign().hash(state);
        n.abs_hash(state);
    }
}

impl AddAssign<Limb> for Int {
    fn add_assign(&mut self, other: Limb) {
        debug_assert!(self.well_formed());
        if other == 0 {
            return;
        }

        // No capacity means `self` is zero. Just push `other` into it
        if self.cap == 0 {
            self.push(other);
            return;
        }
        // This is zero, but has allocated space, so just store `other`
        if self.size == 0 {
            unsafe {
                *self.limbs_uninit() = other;
                self.size = 1;
                return;
            }
        }
        // `self` is non-zero, reuse the storage for the result.
        unsafe {
            let sign = self.sign();
            let size = self.abs_size();
            let mut ptr = self.limbs_mut();

            // Self is positive, just add `other`
            if sign == 1 {
                let carry = ll::add_1(ptr, ptr.as_const(), size, other);
                if carry != 0 {
                    self.push(carry);
                }
            } else {
                // Self is negative, "subtract" other from self, basically doing:
                // -(-self - other) == self + other
                let borrow = ll::sub_1(ptr, ptr.as_const(), size, other);
                if borrow != 0 {
                    // There was a borrow, this means that abs(other) > abs(self), i.e., we are a
                    // single limb and self - other has overflowed. So flip the result across MAX
                    // and keep it positive. Example: Int(-14) += Limb(15) becomes -(Int(14) - 15).
                    // But the -1 overflows. So make the -1 into +1 and return.
                    *ptr = BaseInt::max_value() - *ptr + 1;
                    self.size = self.abs_size();
                }
                self.normalize();
            }
        }
    }
}

impl Add<Limb> for Int {
    type Output = Int;

    #[inline]
    fn add(mut self, other: Limb) -> Int {
        self += other;
        self
    }
}

impl<'a> AddAssign<&'a Int> for Int {
    fn add_assign(&mut self, other: &'a Int) {
        debug_assert!(self.well_formed());
        debug_assert!(other.well_formed());

        if self.sign() == 0 {
            // Try to reuse the allocation from `self`
            self.clone_from(other);
            return;
        }
        if other.sign() == 0 {
            return;
        }

        if self.sign() == other.sign() {
            // Signs are the same, add the two numbers together and re-apply
            // the sign after.
            let sign = self.sign();

            unsafe {
                // There's a restriction that x-size >= y-size, we can swap the operands
                // no problem, but we'd like to re-use `self`s memory if possible, so
                // if `self` is the smaller of the two we make sure it has enough space
                // for the result
                let (xp, xs, yp, ys) = if self.abs_size() >= other.abs_size() {
                    (
                        self.limbs(),
                        self.abs_size(),
                        other.limbs(),
                        other.abs_size(),
                    )
                } else {
                    self.ensure_capacity(other.abs_size() as u32);
                    (
                        other.limbs(),
                        other.abs_size(),
                        self.limbs(),
                        self.abs_size(),
                    )
                };

                // Fetch the pointer first to make completely sure the compiler
                // won't make bogus claims about nonaliasing due to the &mut
                let ptr = self.limbs_uninit();

                let carry = ll::add(ptr, xp, xs, yp, ys);
                self.size = xs * sign;
                if carry != 0 {
                    self.push(carry);
                }
                self.normalize();
            }
        } else {
            // Signs are different, use the sign from the bigger (absolute value)
            // of the two numbers and subtract the smaller one.

            unsafe {
                let (xp, xs, yp, ys) = if self.abs_size() > other.abs_size() {
                    (self.limbs(), self.size, other.limbs(), other.size)
                } else if self.abs_size() < other.abs_size() {
                    self.ensure_capacity(other.abs_size() as u32);
                    (other.limbs(), other.size, self.limbs(), self.size)
                } else {
                    match self.abs_cmp(other) {
                        Ordering::Equal => {
                            // They're equal, but opposite signs, so the result
                            // will be zero, clear `self` and return
                            self.size = 0;
                            return;
                        }
                        Ordering::Greater => (self.limbs(), self.size, other.limbs(), other.size),
                        Ordering::Less => (other.limbs(), other.size, self.limbs(), self.size),
                    }
                };

                // Fetch the pointer first to make completely sure the compiler
                // won't make bogus claims about nonaliasing due to the &mut
                let ptr = self.limbs_uninit();

                let _borrow = ll::sub(ptr, xp, xs.abs(), yp, ys.abs());
                // There shouldn't be any borrow
                debug_assert!(_borrow == 0);

                self.size = xs;
                self.normalize();
                debug_assert!(self.abs_size() > 0);
            }
        }
    }
}

impl<'a> Add<&'a Int> for Int {
    type Output = Int;

    #[inline]
    fn add(mut self, other: &'a Int) -> Int {
        self += other;
        self
    }
}

impl<'a> Add<Int> for &'a Int {
    type Output = Int;

    #[inline]
    fn add(self, other: Int) -> Int {
        // Forward to other + self
        other.add(self)
    }
}

impl Add<Int> for Int {
    type Output = Int;

    #[inline]
    fn add(self, other: Int) -> Int {
        // Check for self or other being zero.
        if self.sign() == 0 {
            return other;
        }
        if other.sign() == 0 {
            return self;
        }

        let (x, y) = if self.abs_size() >= other.abs_size() {
            (self, &other)
        } else {
            (other, &self)
        };

        return x.add(y);
    }
}

impl AddAssign<Int> for Int {
    #[inline]
    fn add_assign(&mut self, mut other: Int) {
        // Use the allocation of the larger of the two inputs.
        // Doing the obvious and simply swapping self and other
        // when other.size > self.size results in poor codegen.
        if other.abs_size() > self.abs_size() {
            // Instead we doing the addition in-place, then overwrite
            // self with other. This results in better codegen and better
            // memory allocation behaviour.
            other += &*self;
            *self = other;
        } else {
            *self += &other;
        }
    }
}

impl<'a, 'b> Add<&'a Int> for &'b Int {
    type Output = Int;

    #[inline]
    fn add(self, other: &'a Int) -> Int {
        if self.sign() == 0 {
            return other.clone();
        }
        if other.sign() == 0 {
            return self.clone();
        }

        // Clone the bigger of the two
        if self.abs_size() >= other.abs_size() {
            self.clone().add(other)
        } else {
            other.clone().add(self)
        }
    }
}

impl SubAssign<Limb> for Int {
    fn sub_assign(&mut self, other: Limb) {
        debug_assert!(self.well_formed());
        if other == 0 {
            return;
        }

        // No capacity means `self` is zero. Just push the limb.
        if self.cap == 0 {
            self.push(other);
            self.size = -1;
            return;
        }
        // This is zero, but has allocated space, so just store `other`
        if self.size == 0 {
            unsafe {
                *self.limbs_uninit() = other;
                self.size = -1;
            }
            return;
        }
        // `self` is non-zero, reuse the storage for the result.
        unsafe {
            let sign = self.sign();
            let size = self.abs_size();
            let ptr = self.limbs_mut();

            // Self is negative, just "add" `other`
            if sign == -1 {
                let carry = ll::add_1(ptr, ptr.as_const(), size, other);
                if carry != 0 {
                    self.push(carry);
                }
            } else {
                // Self is positive, subtract other from self
                let carry = ll::sub_1(ptr, ptr.as_const(), size, other);
                self.normalize();
                if carry != 0 {
                    // There was a carry, and the native operations
                    // work with two's complement, so we need to get
                    // everything back into sign-magnitude form
                    self.negate_twos_complement()
                }
            }
        }

        debug_assert!(self.well_formed());
    }
}

impl Sub<Limb> for Int {
    type Output = Int;

    #[inline]
    fn sub(mut self, other: Limb) -> Int {
        self -= other;
        self
    }
}

impl<'a> SubAssign<&'a Int> for Int {
    fn sub_assign(&mut self, other: &'a Int) {
        debug_assert!(self.well_formed());
        debug_assert!(other.well_formed());

        // LHS is zero, set self to the negation of the RHS
        if self.sign() == 0 {
            self.clone_from(other);
            self.size *= -1;
            return;
        }
        // RHS is zero, do nothing
        if other.sign() == 0 {
            return;
        }

        if self.sign() == other.sign() {
            unsafe {
                // Signs are the same, subtract the smaller one from
                // the bigger one and adjust the sign as appropriate
                let (xp, xs, yp, ys, flip) = match self.abs_cmp(other) {
                    Ordering::Equal => {
                        // x - x, just return zero
                        self.size = 0;
                        return;
                    }
                    Ordering::Less => {
                        self.ensure_capacity(other.abs_size() as u32);
                        (other.limbs(), other.size, self.limbs(), self.size, true)
                    }
                    Ordering::Greater => {
                        (self.limbs(), self.size, other.limbs(), other.size, false)
                    }
                };

                // Fetch the pointer first to make completely sure the compiler
                // won't make bogus claims about nonaliasing due to the &mut
                let ptr = self.limbs_uninit();

                let _borrow = ll::sub(ptr, xp, xs.abs(), yp, ys.abs());
                debug_assert!(_borrow == 0);
                self.size = if flip { xs * -1 } else { xs };
            }

            self.normalize();
        } else {
            // Different signs
            if self.sign() == -1 {
                // self is negative, use addition and negation
                self.size *= -1;
                *self += other;
                self.size *= -1;
            } else {
                unsafe {
                    // Other is negative, handle as addition
                    let (xp, xs, yp, ys) = if self.abs_size() >= other.abs_size() {
                        (
                            self.limbs(),
                            self.abs_size(),
                            other.limbs(),
                            other.abs_size(),
                        )
                    } else {
                        self.ensure_capacity(other.abs_size() as u32);
                        (
                            other.limbs(),
                            other.abs_size(),
                            self.limbs(),
                            self.abs_size(),
                        )
                    };

                    // Fetch the pointer first to make completely sure the compiler
                    // won't make bogus claims about nonaliasing due to the &mut
                    let ptr = self.limbs_uninit();

                    let carry = ll::add(ptr, xp, xs, yp, ys);
                    self.size = xs;
                    if carry != 0 {
                        self.push(carry);
                    }
                    self.normalize();
                }
            }
        }
    }
}

impl<'a> Sub<&'a Int> for Int {
    type Output = Int;

    #[inline]
    fn sub(mut self, other: &'a Int) -> Int {
        self -= other;
        self
    }
}

impl<'a> Sub<Int> for &'a Int {
    type Output = Int;

    #[inline]
    fn sub(self, mut other: Int) -> Int {
        if self.sign() == 0 {
            return -other;
        }
        if other.sign() == 0 {
            other.clone_from(self);
            return other;
        }

        -(other.sub(self))
    }
}

impl Sub<Int> for Int {
    type Output = Int;

    #[inline]
    fn sub(self, other: Int) -> Int {
        if self.sign() == 0 {
            return -other;
        }
        if other.sign() == 0 {
            return self;
        }

        self.sub(&other)
    }
}

impl SubAssign<Int> for Int {
    #[inline]
    fn sub_assign(&mut self, other: Int) {
        if other.sign() == 0 {
            return;
        }
        if self.sign() == 0 {
            *self = -other;
            return;
        }
        *self -= &other;
    }
}

impl<'a, 'b> Sub<&'a Int> for &'b Int {
    type Output = Int;

    #[inline]
    fn sub(self, other: &'a Int) -> Int {
        if self.sign() == 0 {
            return -other;
        }
        if other.sign() == 0 {
            return self.clone();
        }

        self.clone().sub(other)
    }
}

impl MulAssign<Limb> for Int {
    fn mul_assign(&mut self, other: Limb) {
        debug_assert!(self.well_formed());
        if other == 0 || self.sign() == 0 {
            self.size = 0;
            return;
        }

        if other == 1 {
            return;
        }

        unsafe {
            // Fetch the pointer first to make completely sure the compiler
            // won't make bogus claims about nonaliasing due to the &mut

            let carry = ll::mul_1(self.limbs_mut(), self.limbs(), self.abs_size(), other);
            if carry != 0 {
                self.push(carry);
            }
        }
    }
}

impl Mul<Limb> for Int {
    type Output = Int;

    #[inline]
    fn mul(mut self, other: Limb) -> Int {
        self *= other;
        self
    }
}

impl<'a, 'b> Mul<&'a Int> for &'b Int {
    type Output = Int;

    fn mul(self, other: &'a Int) -> Int {
        debug_assert!(self.well_formed());
        debug_assert!(other.well_formed());
        // This is the main function, since in the general case
        // we need to allocate space for the return. Special cases
        // where this isn't necessary are handled in the other impls

        // 0 * x = 0
        if self.sign() == 0 || other.sign() == 0 {
            return Int::zero();
        }

        let out_sign = self.sign() * other.sign();

        if self.abs_size() == 1 {
            let mut ret = other.clone() * *self.limbs();
            let size = ret.abs_size();
            ret.size = size * out_sign;
            return ret;
        }
        if other.abs_size() == 1 {
            let mut ret = self.clone() * *other.limbs();
            let size = ret.abs_size();
            ret.size = size * out_sign;
            return ret;
        }

        let out_size = self.abs_size() + other.abs_size();

        let mut out = Int::with_capacity(out_size as u32);
        out.size = out_size * out_sign;

        unsafe {
            let (xp, xs, yp, ys) = if self.abs_size() >= other.abs_size() {
                (
                    self.limbs(),
                    self.abs_size(),
                    other.limbs(),
                    other.abs_size(),
                )
            } else {
                (
                    other.limbs(),
                    other.abs_size(),
                    self.limbs(),
                    self.abs_size(),
                )
            };
            ll::mul(out.limbs_mut(), xp, xs, yp, ys);

            // Top limb may be zero
            out.normalize();
            return out;
        }
    }
}

impl<'a> Mul<&'a Int> for Int {
    type Output = Int;

    #[inline]
    fn mul(mut self, other: &'a Int) -> Int {
        // `other` is zero
        if other.sign() == 0 {
            self.size = 0;
            return self;
        }

        // `other` is a single limb, reuse the allocation of self
        if other.abs_size() == 1 {
            let mut out = self * *other.limbs();
            out.size *= other.sign();
            return out;
        }

        // Forward to the by-reference impl
        (&self) * other
    }
}

impl<'a> Mul<Int> for &'a Int {
    type Output = Int;

    #[inline]
    fn mul(self, other: Int) -> Int {
        // Swap arguments
        other * self
    }
}

impl Mul<Int> for Int {
    type Output = Int;

    fn mul(mut self, other: Int) -> Int {
        if self.sign() == 0 || other.sign() == 0 {
            self.size = 0;
            return self;
        }

        // One of them is a single limb big, so we can re-use the
        // allocation of the other
        if self.abs_size() == 1 {
            let val = *self.limbs();
            let mut out = other * val;
            out.size *= self.sign();
            return out;
        }
        if other.abs_size() == 1 {
            let val = *other.limbs();
            let mut out = self * val;
            out.size *= other.sign();
            return out;
        }

        // Still need to allocate for the result, just forward to
        // the by-reference impl
        (&self) * (&other)
    }
}

impl<'a> MulAssign<&'a Int> for Int {
    #[inline]
    fn mul_assign(&mut self, other: &'a Int) {
        if self.sign() == 0 {
            return;
        }
        if other.sign() == 0 {
            self.size = 0;
            return;
        }
        let res = &*self * other;
        *self = res;
    }
}

impl MulAssign<Int> for Int {
    #[inline]
    fn mul_assign(&mut self, other: Int) {
        if self.sign() == 0 {
            return;
        }
        if other.sign() == 0 {
            self.size = 0;
            return;
        }
        let res = &*self * other;
        *self = res;
    }
}

impl DivAssign<Limb> for Int {
    fn div_assign(&mut self, other: Limb) {
        debug_assert!(self.well_formed());
        if other == 0 {
            ll::divide_by_zero();
        }
        if other == 1 || self.sign() == 0 {
            return;
        }

        unsafe {
            // Ignore the remainder
            ll::divrem_1(self.limbs_mut(), 0, self.limbs(), self.abs_size(), other);
            // Adjust the size if necessary
            self.normalize();
        }
    }
}

impl Div<Limb> for Int {
    type Output = Int;

    #[inline]
    fn div(mut self, other: Limb) -> Int {
        self /= other;
        self
    }
}

impl<'a, 'b> Div<&'a Int> for &'b Int {
    type Output = Int;

    fn div(self, other: &'a Int) -> Int {
        debug_assert!(self.well_formed());
        debug_assert!(other.well_formed());
        if other.sign() == 0 {
            ll::divide_by_zero();
        }
        if other.abs_size() == 1 {
            let l = *other.limbs();
            let out_sign = self.sign() * other.sign();
            let mut out = self.clone() / l;
            out.size = out.abs_size() * out_sign;
            return out;
        }

        self.divmod(other).0
    }
}

impl<'a> Div<&'a Int> for Int {
    type Output = Int;

    #[inline]
    fn div(self, other: &'a Int) -> Int {
        (&self) / other
    }
}

impl<'a> Div<Int> for &'a Int {
    type Output = Int;

    #[inline]
    fn div(self, other: Int) -> Int {
        self / (&other)
    }
}

impl Div<Int> for Int {
    type Output = Int;

    #[inline]
    fn div(self, other: Int) -> Int {
        (&self) / (&other)
    }
}

impl<'a> DivAssign<&'a Int> for Int {
    #[inline]
    fn div_assign(&mut self, other: &'a Int) {
        let res = &*self / other;
        *self = res;
    }
}

impl DivAssign<Int> for Int {
    #[inline]
    fn div_assign(&mut self, other: Int) {
        let res = &*self / other;
        *self = res;
    }
}

impl Rem<Limb> for Int {
    type Output = Int;

    #[inline]
    fn rem(mut self, other: Limb) -> Int {
        self %= other;
        self
    }
}

impl RemAssign<Limb> for Int {
    fn rem_assign(&mut self, other: Limb) {
        debug_assert!(self.well_formed());
        if other == 0 {
            ll::divide_by_zero();
        }
        // x % 1 == 0, 0 % n == 0
        if other == 1 || self.sign() == 0 {
            self.size = 0;
            return;
        }

        unsafe {
            let rem = ll::divrem_1(self.limbs_mut(), 0, self.limbs(), self.abs_size(), other);
            // Reuse the space from `self`, taking the sign from the numerator
            // Since `rem` has to satisfy `N = QD + R` and D is always positive,
            // `R` will always be the same sign as the numerator.
            *self.limbs_mut() = rem;
            let sign = self.sign();
            self.size = sign;

            self.normalize();

            if self.cap > 8 {
                // Shrink self, since it's at least 8 times bigger than necessary
                self.shrink_to_fit();
            }
        }
    }
}

impl DivRem<Limb> for Int {
    type Output = (Int, Limb);

    fn divrem(mut self, other: Limb) -> Self::Output {
        debug_assert!(self.well_formed());
        if other == 0 {
            ll::divide_by_zero();
        }
        // x % 1 == 0, 0 % n == 0
        if other == 1 || self.sign() == 0 {
            self.size = 0;
            return (self, Limb(0));
        }

        let rem =
            unsafe { ll::divrem_1(self.limbs_mut(), 0, self.limbs(), self.abs_size(), other) };
        self.normalize();
        return (self, rem);
    }
}

// TODO: There's probably too much cloning happening here, need to figure out
// the best way of avoiding over-copying.

impl<'a, 'b> Rem<&'a Int> for &'b Int {
    type Output = Int;

    fn rem(self, other: &'a Int) -> Int {
        debug_assert!(self.well_formed());
        debug_assert!(other.well_formed());
        if other.sign() == 0 {
            ll::divide_by_zero();
        }
        if other.abs_size() == 1 {
            let l = *other.limbs();
            return self.clone() % l;
        }

        self.divmod(other).1
    }
}

impl<'a> Rem<&'a Int> for Int {
    type Output = Int;

    #[inline]
    fn rem(self, other: &'a Int) -> Int {
        (&self) % other
    }
}

impl<'a> Rem<Int> for &'a Int {
    type Output = Int;

    #[inline]
    fn rem(self, other: Int) -> Int {
        self % (&other)
    }
}

impl Rem<Int> for Int {
    type Output = Int;

    #[inline]
    fn rem(self, other: Int) -> Int {
        (&self) % (&other)
    }
}

impl<'a, 'b> DivRem<&'a Int> for &'b Int {
    type Output = (Int, Int);

    #[inline]
    fn divrem(self, other: &'a Int) -> (Int, Int) {
        self.divmod(other)
    }
}

impl RemAssign<Int> for Int {
    #[inline]
    fn rem_assign(&mut self, other: Int) {
        let res = &*self % other;
        *self = res;
    }
}
impl<'a> RemAssign<&'a Int> for Int {
    #[inline]
    fn rem_assign(&mut self, other: &'a Int) {
        let res = &*self % other;
        *self = res;
    }
}

impl Neg for Int {
    type Output = Int;

    #[inline]
    fn neg(mut self) -> Int {
        debug_assert!(self.well_formed());
        self.size *= -1;
        self
    }
}

impl<'a> Neg for &'a Int {
    type Output = Int;

    #[inline]
    fn neg(self) -> Int {
        self.clone().neg()
    }
}

impl ShlAssign<usize> for Int {
    #[inline]
    fn shl_assign(&mut self, mut cnt: usize) {
        debug_assert!(self.well_formed());
        if self.sign() == 0 {
            return;
        }

        if cnt >= Limb::BITS as usize {
            let extra_limbs = (cnt / Limb::BITS as usize) as u32;
            debug_assert!(extra_limbs >= 1);
            cnt = cnt % Limb::BITS as usize;

            let size = self.abs_size() as u32;
            // Extend for the extra limbs, then another one for any potential extra limbs
            self.ensure_capacity(extra_limbs + size + 1);

            unsafe {
                let ptr = self.limbs_uninit();
                let shift = ptr.offset(extra_limbs as isize);
                ll::copy_decr(ptr.as_const(), shift, self.abs_size());
                ll::zero(ptr, extra_limbs as i32);
            }

            self.size += (extra_limbs as i32) * self.sign();
        }

        debug_assert!(cnt < Limb::BITS as usize);

        if cnt == 0 {
            return;
        }

        let size = self.abs_size();

        unsafe {
            let ptr = self.limbs_mut();
            let c = ll::shl(ptr, ptr.as_const(), size, cnt as u32);
            if c > 0 {
                self.push(c);
            }
        }
    }
}

impl<'a> Shl<usize> for &'a Int {
    type Output = Int;

    #[inline]
    fn shl(self, cnt: usize) -> Int {
        let mut new = self.clone();
        new <<= cnt;
        new
    }
}

impl Shl<usize> for Int {
    type Output = Int;

    #[inline]
    fn shl(mut self, other: usize) -> Int {
        self <<= other;
        self
    }
}

impl ShrAssign<usize> for Int {
    #[inline]
    fn shr_assign(&mut self, mut cnt: usize) {
        debug_assert!(self.well_formed());
        if self.sign() == 0 {
            return;
        }

        if cnt >= Limb::BITS as usize {
            let removed_limbs = (cnt / Limb::BITS as usize) as u32;
            let size = self.abs_size();
            if removed_limbs as i32 >= size {
                *self = Int::zero();
                return;
            }
            debug_assert!(removed_limbs > 0);
            cnt = cnt % Limb::BITS as usize;

            unsafe {
                let ptr = self.limbs_mut();
                let shift = ptr.offset(removed_limbs as isize);
                let new_size = size - removed_limbs as i32;

                // Shift down a whole number of limbs
                ll::copy_incr(shift.as_const(), ptr, new_size);
                // Zero out the high limbs
                ll::zero(ptr.offset(new_size as isize), removed_limbs as i32);

                self.size = new_size * self.sign();
            }
        }

        debug_assert!(cnt < Limb::BITS as usize);
        if cnt == 0 {
            return;
        }

        let size = self.abs_size();

        unsafe {
            let ptr = self.limbs_mut();
            ll::shr(ptr, ptr.as_const(), size, cnt as u32);
            self.normalize();
        }
    }
}

impl<'a> Shr<usize> for &'a Int {
    type Output = Int;

    #[inline]
    fn shr(self, other: usize) -> Int {
        let mut new = self.clone();
        new >>= other;
        new
    }
}

impl Shr<usize> for Int {
    type Output = Int;

    #[inline]
    fn shr(mut self, other: usize) -> Int {
        self >>= other;
        self
    }
}

#[derive(Copy, Clone)]
enum BitOp {
    And,
    Or,
    Xor,
}

fn bitop_ref(this: &mut Int, other: &Int, op: BitOp) -> Result<(), ()> {
    let this_sign = this.sign();
    let other_sign = other.sign();

    // if other is small, we can fall back to something that'll be
    // more efficient (especially if other is negative)
    if other.abs_size() <= 1 {
        // the magnitude of the limb
        let mut limb = other.to_single_limb();
        if other_sign < 0 {
            if limb.high_bit_set() {
                // the limb is too large to be put into two's
                // complement form (NB. that if other is positive, we
                // don't need to worry about two's complement, since
                // bitop_limb can handle unsigned Limbs)
                return Err(());
            } else {
                limb = -limb;
            }
        }

        // as mentioned above, we only have to say that `limb` is
        // signed when it is actually negative
        bitop_limb(this, limb, other_sign < 0, op);
        return Ok(());
    }

    if this_sign < 0 || other_sign < 0 {
        return Err(());
    }

    unsafe {
        let other_ptr = other.limbs();
        let min_size = std::cmp::min(this.abs_size(), other.abs_size());
        let max_size = std::cmp::max(this.abs_size(), other.abs_size());
        match op {
            BitOp::And => {
                let this_ptr = this.limbs_mut();
                ll::and_n(this_ptr, this_ptr.as_const(), other_ptr, min_size);
                this.size = min_size;
            }
            BitOp::Or => {
                this.ensure_capacity(max_size as u32);
                let this_ptr = this.limbs_uninit();
                ll::or_n(this_ptr, this_ptr.as_const(), other_ptr, min_size);
                if this.abs_size() < max_size {
                    ll::copy_rest(other_ptr, this_ptr, max_size, min_size);
                }
                this.size = max_size;
            }
            BitOp::Xor => {
                this.ensure_capacity(max_size as u32);
                let this_ptr = this.limbs_uninit();
                ll::xor_n(this_ptr, this_ptr.as_const(), other_ptr, min_size);
                if this.abs_size() < max_size {
                    ll::copy_rest(other_ptr, this_ptr, max_size, min_size);
                }
                this.size = max_size;
            }
        }
    }
    this.normalize();
    Ok(())
}

// one of the inputs is negative. The answer is as if `Int` was stored
// in two's complement (in infinite precision), which means converting
// to that format, doing the operation, and then converting back out
// of it, if necessary.
fn bitop_neg(mut a: Int, mut b: Int, op: BitOp) -> Int {
    debug_assert!(a.sign() < 0 || b.sign() < 0);
    let a_sign = a.sign();
    let b_sign = b.sign();

    if a_sign < 0 {
        a.negate_twos_complement();
    }
    if b_sign < 0 {
        b.negate_twos_complement();
    }
    let (mut a, b, a_sign, b_sign) = if a.abs_size() < b.abs_size() {
        (b, a, b_sign, a_sign)
    } else {
        (a, b, a_sign, b_sign)
    };

    unsafe {
        let a_ptr = a.limbs_mut();
        let b_ptr = b.limbs();
        let min_size = b.abs_size();
        let max_size = a.abs_size();

        let (neg_result, use_max_size) = match op {
            BitOp::And => {
                ll::and_n(a_ptr, a_ptr.as_const(), b_ptr, min_size);

                (a_sign < 0 && b_sign < 0, b_sign < 0)
            }
            BitOp::Or => {
                ll::or_n(a_ptr, a_ptr.as_const(), b_ptr, min_size);
                // (no need to copy trailing, a is longer than b)

                (a_sign < 0 || b_sign < 0, b_sign >= 0)
            }
            BitOp::Xor => {
                ll::xor_n(a_ptr, a_ptr.as_const(), b_ptr, min_size);
                if b_sign < 0 {
                    let ptr = a_ptr.offset(min_size as isize);
                    ll::not(ptr, ptr.as_const(), max_size - min_size);
                }
                ((a_sign < 0) ^ (b_sign < 0), true)
            }
        };

        a.size = if use_max_size { max_size } else { min_size };
        if neg_result {
            a.negate_twos_complement();
        }
    }
    a.normalize();
    return a;
}

// do a bit operation on `a` and `b`.
//
// If `signed` only indicates whether to interpret `b` as two's
// complement or not (i.e. if it is true, then `1` is still `1`, and
// `-1` is `!0`)
fn bitop_limb(a: &mut Int, b: Limb, signed: bool, op: BitOp) {
    let a_sign = a.sign();
    let b_negative = signed && b.high_bit_set();
    let b_sign = if b_negative {
        -1
    } else if b == 0 {
        0
    } else {
        1
    };

    if a_sign < 0 {
        a.negate_twos_complement();
    }
    // b is already in two's complement if it is negative

    if a_sign == 0 {
        match op {
            // 0 ^ x == 0 | x == x
            BitOp::Or | BitOp::Xor => {
                if b_sign < 0 {
                    a.push(-b);
                    a.negate();
                } else {
                    a.push(b)
                }
            }
            // 0 & x == 0
            BitOp::And => {}
        }
    } else {
        unsafe {
            let mut a_ptr = a.limbs_mut();
            let min_size = if b == 0 { 0 } else { 1 };
            let max_size = a.abs_size();
            // we've got to have space to write data to this pointer
            debug_assert!(max_size >= 1);

            let (neg_result, use_max_size) = match op {
                BitOp::And => {
                    *a_ptr = *a_ptr & b;
                    (a_sign < 0 && b_sign < 0, b_sign < 0)
                }
                BitOp::Or => {
                    *a_ptr = *a_ptr | b;
                    (a_sign < 0 || b_sign < 0, b_sign >= 0)
                }
                BitOp::Xor => {
                    *a_ptr = *a_ptr ^ b;
                    if b_sign < 0 {
                        let ptr = a_ptr.offset(min_size as isize);
                        ll::not(ptr, ptr.as_const(), max_size - min_size);
                    }
                    ((a_sign < 0) ^ (b_sign < 0), true)
                }
            };
            a.size = if use_max_size { max_size } else { min_size };
            if neg_result {
                a.negate_twos_complement();
            }
        }
    }
    a.normalize();
}

impl<'a> BitAnd<Limb> for Int {
    type Output = Int;

    fn bitand(mut self, other: Limb) -> Int {
        self &= other;
        self
    }
}

impl BitAndAssign<Limb> for Int {
    fn bitand_assign(&mut self, other: Limb) {
        bitop_limb(self, other, false, BitOp::And)
    }
}

impl<'a> BitAnd<&'a Int> for Int {
    type Output = Int;

    fn bitand(mut self, other: &'a Int) -> Int {
        if let Ok(_) = bitop_ref(&mut self, other, BitOp::And) {
            self
        } else {
            bitop_neg(self, other.clone(), BitOp::And)
        }
    }
}

impl<'a> BitAnd<Int> for &'a Int {
    type Output = Int;

    #[inline]
    fn bitand(self, other: Int) -> Int {
        other.bitand(self)
    }
}

impl<'a, 'b> BitAnd<&'a Int> for &'b Int {
    type Output = Int;

    #[inline]
    fn bitand(self, other: &'a Int) -> Int {
        self.clone().bitand(other)
    }
}

impl BitAnd<Int> for Int {
    type Output = Int;

    fn bitand(mut self, other: Int) -> Int {
        if let Ok(_) = bitop_ref(&mut self, &other, BitOp::And) {
            self
        } else {
            bitop_neg(self, other, BitOp::And)
        }
    }
}

impl BitAndAssign<Int> for Int {
    #[inline]
    fn bitand_assign(&mut self, other: Int) {
        if let Err(_) = bitop_ref(self, &other, BitOp::And) {
            let res = &*self & other;
            *self = res;
        }
    }
}
impl<'a> BitAndAssign<&'a Int> for Int {
    #[inline]
    fn bitand_assign(&mut self, other: &'a Int) {
        if let Err(_) = bitop_ref(self, other, BitOp::And) {
            let res = &*self & other;
            *self = res;
        }
    }
}

impl BitOr<Limb> for Int {
    type Output = Int;

    fn bitor(mut self, other: Limb) -> Int {
        self |= other;
        self
    }
}

impl BitOrAssign<Limb> for Int {
    fn bitor_assign(&mut self, other: Limb) {
        bitop_limb(self, other, false, BitOp::Or)
    }
}

impl<'a> BitOr<&'a Int> for Int {
    type Output = Int;

    fn bitor(mut self, other: &'a Int) -> Int {
        if let Ok(_) = bitop_ref(&mut self, other, BitOp::Or) {
            self
        } else {
            bitop_neg(self, other.clone(), BitOp::Or)
        }
    }
}

impl<'a> BitOr<Int> for &'a Int {
    type Output = Int;

    #[inline]
    fn bitor(self, other: Int) -> Int {
        other.bitor(self)
    }
}

impl<'a, 'b> BitOr<&'a Int> for &'b Int {
    type Output = Int;

    #[inline]
    fn bitor(self, other: &'a Int) -> Int {
        self.clone().bitor(other)
    }
}

impl BitOr<Int> for Int {
    type Output = Int;

    #[inline]
    fn bitor(mut self, other: Int) -> Int {
        if let Ok(_) = bitop_ref(&mut self, &other, BitOp::Or) {
            self
        } else {
            bitop_neg(self, other, BitOp::Or)
        }
    }
}

impl BitOrAssign<Int> for Int {
    #[inline]
    fn bitor_assign(&mut self, other: Int) {
        if let Err(_) = bitop_ref(self, &other, BitOp::Or) {
            let res = &*self | other;
            *self = res;
        }
    }
}
impl<'a> BitOrAssign<&'a Int> for Int {
    #[inline]
    fn bitor_assign(&mut self, other: &'a Int) {
        if let Err(_) = bitop_ref(self, &other, BitOp::Or) {
            let res = &*self | other;
            *self = res;
        }
    }
}

impl<'a> BitXor<Limb> for Int {
    type Output = Int;

    fn bitxor(mut self, other: Limb) -> Int {
        self ^= other;
        self
    }
}

impl BitXorAssign<Limb> for Int {
    fn bitxor_assign(&mut self, other: Limb) {
        bitop_limb(self, other, false, BitOp::Xor)
    }
}

impl<'a> BitXor<&'a Int> for Int {
    type Output = Int;

    fn bitxor(mut self, other: &'a Int) -> Int {
        if let Ok(_) = bitop_ref(&mut self, other, BitOp::Xor) {
            self
        } else {
            bitop_neg(self, other.clone(), BitOp::Xor)
        }
    }
}

impl<'a> BitXor<Int> for &'a Int {
    type Output = Int;

    #[inline]
    fn bitxor(self, other: Int) -> Int {
        other.bitxor(self)
    }
}

impl<'a, 'b> BitXor<&'a Int> for &'b Int {
    type Output = Int;

    #[inline]
    fn bitxor(self, other: &'a Int) -> Int {
        self.clone().bitxor(other)
    }
}

impl BitXor<Int> for Int {
    type Output = Int;

    #[inline]
    fn bitxor(mut self, other: Int) -> Int {
        if let Ok(_) = bitop_ref(&mut self, &other, BitOp::Xor) {
            self
        } else {
            bitop_neg(self, other, BitOp::Xor)
        }
    }
}

impl BitXorAssign<Int> for Int {
    #[inline]
    fn bitxor_assign(&mut self, other: Int) {
        if let Err(_) = bitop_ref(self, &other, BitOp::Xor) {
            let res = &*self ^ other;
            *self = res;
        }
    }
}
impl<'a> BitXorAssign<&'a Int> for Int {
    #[inline]
    fn bitxor_assign(&mut self, other: &'a Int) {
        if let Err(_) = bitop_ref(self, &other, BitOp::Xor) {
            let res = &*self ^ other;
            *self = res;
        }
    }
}

macro_rules! impl_arith_prim (
    (signed $t:ty) => (
        // Limbs are unsigned, so make sure we account for the sign
        // when $t is signed
        impl Add<$t> for Int {
            type Output = Int;

            #[inline]
            fn add(self, other: $t) -> Int {
                if other == 0 {
                    return self;
                }
                if other < 0 {
                    return self - Limb(other.abs() as BaseInt);
                }
                return self + Limb(other as BaseInt);
            }
        }

        impl AddAssign<$t> for Int {
            #[inline]
            fn add_assign(&mut self, other: $t) {
                if other < 0 {
                    *self -= Limb(other.abs() as BaseInt);
                } else if other > 0 {
                    *self += Limb(other as BaseInt);
                }
            }
        }

        impl Sub<$t> for Int {
            type Output = Int;

            #[inline]
            fn sub(self, other: $t) -> Int {
                if other == 0 {
                    return self;
                }
                if other < 0 {
                    return self + Limb(other.abs() as BaseInt);
                }
                return self - Limb(other as BaseInt);
            }
        }

        impl SubAssign<$t> for Int {
            #[inline]
            fn sub_assign(&mut self, other: $t) {
                if other < 0 {
                    *self += Limb(other.abs() as BaseInt);
                } else if other > 0 {
                    *self -= Limb(other as BaseInt);
                }
            }
        }

        impl Mul<$t> for Int {
            type Output = Int;

            #[inline]
            fn mul(mut self, other: $t) -> Int {
                self *= other;
                self
            }
        }

        impl MulAssign<$t> for Int {
            #[inline]
            fn mul_assign(&mut self, other: $t) {
                if other == 0 {
                    self.size = 0;
                } else if other == -1 {
                    self.negate();
                } else if other < 0 {
                    self.negate();
                    *self *= Limb(other.abs() as BaseInt);
                } else {
                    *self *= Limb(other as BaseInt);
                }
            }
        }

        impl DivAssign<$t> for Int {
            #[inline]
            fn div_assign(&mut self, other: $t) {
                if other == 0 {
                    ll::divide_by_zero();
                }
                if other == 1 || self.sign() == 0 {
                    return;
                }
                if other == -1 {
                    self.negate();
                } else if other < 0 {
                    self.negate();
                    *self /= Limb(other.abs() as BaseInt);
                } else {
                    *self /= Limb(other as BaseInt);
                }
            }
        }

        impl Div<$t> for Int {
            type Output = Int;

            #[inline]
            fn div(mut self, other: $t) -> Int {
                self /= other;
                self
            }
        }

        impl RemAssign<$t> for Int {
            #[inline]
            fn rem_assign(&mut self, other: $t) {
                let res = &*self % other;
                *self = res;
            }
        }

        impl Rem<$t> for Int {
            type Output = Int;

            #[inline]
            fn rem(mut self, other: $t) -> Int {
                if other == 0 {
                    ll::divide_by_zero();
                }

                if other == 1 ||other == -1 || self.sign() == 0 {
                    self.size = 0;
                    return self;
                }

                return self % Limb(other.abs() as BaseInt);
            }
        }

        impl DivRem<$t> for Int {
            type Output = (Int, $t);

            #[inline]
            fn divrem(mut self, other: $t) -> Self::Output {
                if other == 0 {
                    ll::divide_by_zero();
                }
                let sign = self.sign();
                let (q, r) = {
                    if other == 1 || sign == 0 {
                        return (self, 0);
                    } else if other == -1 {
                        self.negate();
                        return (self, 0);
                    } else if other < 0 {
                        self.negate();
                        self.divrem(Limb(other.abs() as BaseInt))
                    } else {
                        self.divrem(Limb(other as BaseInt))
                    }
                };
                let r = (r.0 as $t).checked_mul(sign).unwrap();
                debug_assert!(sign > 0 || r <= 0);
                debug_assert!(sign < 0 || r >= 0);
                debug_assert!(r.abs() < other.abs());
                (q, r)
            }
        }

        impl BitAndAssign<$t> for Int {
            #[inline]
            fn bitand_assign(&mut self, other: $t) {
                bitop_limb(self, Limb(other as BaseInt), true, BitOp::And)
            }
        }

        impl BitOrAssign<$t> for Int {
            #[inline]
            fn bitor_assign(&mut self, other: $t) {
                bitop_limb(self, Limb(other as BaseInt), true, BitOp::Or)
            }
        }

        impl BitXorAssign<$t> for Int {
            #[inline]
            fn bitxor_assign(&mut self, other: $t) {
                bitop_limb(self, Limb(other as BaseInt), true, BitOp::Xor)
            }
        }

        impl_arith_prim!(common $t);
    );
    (unsigned $t:ty) => (
        impl Add<$t> for Int {
            type Output = Int;

            #[inline]
            fn add(self, other: $t) -> Int {
                if other == 0 {
                    return self;
                }
                return self + Limb(other as BaseInt);
            }
        }

        impl AddAssign<$t> for Int {
            #[inline]
            fn add_assign(&mut self, other: $t) {
                if other != 0 {
                    *self += Limb(other as BaseInt);
                }
            }
        }

        impl Sub<$t> for Int {
            type Output = Int;

            #[inline]
            fn sub(self, other: $t) -> Int {
                if other == 0 {
                    return self;
                }
                return self - Limb(other as BaseInt);
            }
        }

        impl SubAssign<$t> for Int {
            #[inline]
            fn sub_assign(&mut self, other: $t) {
                if other != 0 {
                    *self -= Limb(other as BaseInt);
                }
            }
        }

        impl Mul<$t> for Int {
            type Output = Int;

            #[inline]
            fn mul(mut self, other: $t) -> Int {
                if other == 0 {
                    self.size = 0;
                    return self;
                }
                if other == 1 || self.sign() == 0 {
                    return self;
                }
                return self * Limb(other as BaseInt);
            }
        }

        impl MulAssign<$t> for Int {
            #[inline]
            fn mul_assign(&mut self, other: $t) {
                if other == 0 {
                    self.size = 0;
                } else if other > 1 && self.sign() != 0 {
                    *self *= Limb(other as BaseInt);
                }
            }
        }

        impl Div<$t> for Int {
            type Output = Int;

            #[inline]
            fn div(self, other: $t) -> Int {
                if other == 0 {
                    ll::divide_by_zero();
                }
                if other == 1 || self.sign() == 0 {
                    return self;
                }
                return self / Limb(other as BaseInt);
            }
        }

        impl DivAssign<$t> for Int {
            #[inline]
            fn div_assign(&mut self, other: $t) {
                if other == 0 {
                    ll::divide_by_zero();
                } else if other > 1 && self.sign() != 0 {
                    *self /= Limb(other as BaseInt);
                }
            }
        }

        impl Rem<$t> for Int {
            type Output = Int;

            #[inline]
            fn rem(mut self, other: $t) -> Int {
                if other == 0 {
                    ll::divide_by_zero();
                }

                if other == 1 || self.sign() == 0 {
                    self.size = 0;
                    return self;
                }

                return self % Limb(other as BaseInt);
            }
        }
        impl RemAssign<$t> for Int {
            #[inline]
            fn rem_assign(&mut self, other: $t) {
                *self %= Limb(other as BaseInt);
            }
        }

        impl DivRem<$t> for Int {
            type Output = (Int, $t);

            #[inline]
            fn divrem(self, other: $t) -> Self::Output {
                let other = other as BaseInt;
                let (q, r) = self.divrem(Limb(other));
                debug_assert!(r < other);
                (q, r.0 as $t)
            }
        }

        impl BitAndAssign<$t> for Int {
            #[inline]
            fn bitand_assign(&mut self, other: $t) {
                bitop_limb(self, Limb(other as BaseInt), false, BitOp::And)
            }
        }

        impl BitOrAssign<$t> for Int {
            #[inline]
            fn bitor_assign(&mut self, other: $t) {
                bitop_limb(self, Limb(other as BaseInt), false, BitOp::Or)
            }
        }

        impl BitXorAssign<$t> for Int {
            #[inline]
            fn bitxor_assign(&mut self, other: $t) {
                bitop_limb(self, Limb(other as BaseInt), false, BitOp::Xor)
            }
        }

        impl_arith_prim!(common $t);
    );
    (common $t:ty) => (
        // Common impls, these should just forward to the above
        // impls
        impl<'a> Add<$t> for &'a Int {
            type Output = Int;

            #[inline]
            fn add(self, other: $t) -> Int {
                self.clone() + other
            }
        }

        impl Add<Int> for $t {
            type Output = Int;

            #[inline]
            fn add(self, other: Int) -> Int {
                return other + self;
            }
        }

        impl<'a> Add<&'a Int> for $t {
            type Output = Int;

            #[inline]
            fn add(self, other: &'a Int) -> Int {
                other.clone() + self
            }
        }

        impl<'a> Sub<$t> for &'a Int {
            type Output = Int;

            #[inline]
            fn sub(self, other: $t) -> Int {
                self.clone() - other
            }
        }

        impl Sub<Int> for $t {
            type Output = Int;

            #[inline]
            fn sub(self, other: Int) -> Int {
                -other + self
            }
        }

        impl<'a> Sub<&'a Int> for $t {
            type Output = Int;

            #[inline]
            fn sub(self, other: &'a Int) -> Int {
                -(other - self)
            }
        }

        impl<'a> Mul<$t> for &'a Int {
            type Output = Int;

            #[inline]
            fn mul(self, other: $t) -> Int {
                return self.clone() * other;
            }
        }

        impl Mul<Int> for $t {
            type Output = Int;

            #[inline]
            fn mul(self, other: Int) -> Int {
                other * self
            }
        }

        impl<'a> Mul<&'a Int> for $t {
            type Output = Int;

            #[inline]
            fn mul(self, other: &'a Int) -> Int {
                // Check for zero here to avoid cloning unnecessarily
                if self == 0 { return Int::zero() };
                other.clone() * self
            }
        }

        impl<'a> Div<$t> for &'a Int {
            type Output = Int;

            #[inline]
            fn div(self, other: $t) -> Int {
                if other == 0 {
                    ll::divide_by_zero();
                }
                return self.clone() / other;
            }
        }

        impl Div<Int> for $t {
            type Output = Int;

            #[inline]
            fn div(self, mut other: Int) -> Int {
                if self == 0 {
                    other.size = 0;
                    return other;
                }
                if other.sign() == 0 {
                    ll::divide_by_zero();
                }
                // There's probably a better way of doing this, but
                // I don't see n / <bigint> being common in code
                Int::from(self) / other
            }
        }

        impl<'a> Div<&'a Int> for $t {
            type Output = Int;

            #[inline]
            fn div(self, other: &'a Int) -> Int {
                if self == 0 { return Int::zero() };
                if other.sign() == 0 {
                    ll::divide_by_zero();
                }

                self / other.clone()
            }
        }

        impl<'a> Rem<$t> for &'a Int {
            type Output = Int;

            #[inline]
            fn rem(self, other: $t) -> Int {
                if other == 0 {
                    ll::divide_by_zero();
                }
                if self.sign() == 0 || other == 1 {
                    return Int::zero()
                };
                return self.clone() % other;
            }
        }

        impl Rem<Int> for $t {
            type Output = Int;

            #[inline]
            fn rem(self, mut other: Int) -> Int {
                if self == 0 || other == 1 {
                    other.size = 0;
                    return other;
                }
                if other.sign() == 0 {
                    ll::divide_by_zero();
                }
                // There's probably a better way of doing this, but
                // I don't see n % <bigint> being common in code
                Int::from(self) % other
            }
        }

        impl<'a> Rem<&'a Int> for $t {
            type Output = Int;

            #[inline]
            fn rem(self, other: &'a Int) -> Int {
                if self == 0 { return Int::zero() };
                if other.sign() == 0 {
                    ll::divide_by_zero();
                }

                self % other.clone()
            }
        }

        impl BitAnd<$t> for Int {
            type Output = Int;

            #[inline]
            fn bitand(mut self, other: $t) -> Int {
                self &= other;
                self
            }
        }

        impl<'a> BitAnd<$t> for &'a Int {
            type Output = Int;

            #[inline]
            fn bitand(self, other: $t) -> Int {
                self.clone() & other
            }
        }

        impl BitAnd<Int> for $t {
            type Output = Int;

            #[inline]
            fn bitand(self, other: Int) -> Int {
                other & self
            }
        }

        impl<'a> BitAnd<&'a Int> for $t {
            type Output = Int;

            #[inline]
            fn bitand(self, other: &'a Int) -> Int {
                other & self
            }
        }

        impl BitOr<$t> for Int {
            type Output = Int;

            #[inline]
            fn bitor(mut self, other: $t) -> Int {
                self |= other;
                self
            }
        }

        impl<'a> BitOr<$t> for &'a Int {
            type Output = Int;

            #[inline]
            fn bitor(self, other: $t) -> Int {
                self.clone() | other
            }
        }

        impl BitOr<Int> for $t {
            type Output = Int;

            #[inline]
            fn bitor(self, other: Int) -> Int {
                other | self
            }
        }

        impl<'a> BitOr<&'a Int> for $t {
            type Output = Int;

            #[inline]
            fn bitor(self, other: &'a Int) -> Int {
                other | self
            }
        }

        impl BitXor<$t> for Int {
            type Output = Int;

            #[inline]
            fn bitxor(mut self, other: $t) -> Int {
                self ^= other;
                self
            }
        }

        impl<'a> BitXor<$t> for &'a Int {
            type Output = Int;

            #[inline]
            fn bitxor(self, other: $t) -> Int {
                self.clone() ^ other
            }
        }

        impl BitXor<Int> for $t {
            type Output = Int;

            #[inline]
            fn bitxor(self, other: Int) -> Int {
                other ^ self
            }
        }

        impl<'a> BitXor<&'a Int> for $t {
            type Output = Int;

            #[inline]
            fn bitxor(self, other: &'a Int) -> Int {
                other ^ self
            }
        }
    )
);

// Implement for `i32` which is the fallback type, usize and the base integer type.
// No more than this because the rest of Rust doesn't much coercion for integer types,
// but allocating an entire multiple-precision `Int` to do `+ 1` seems silly.
impl_arith_prim!(signed i32);
impl_arith_prim!(unsigned usize);
impl_arith_prim!(unsigned BaseInt);

impl PartialEq<i32> for Int {
    #[inline]
    fn eq(&self, &other: &i32) -> bool {
        let sign = self.sign();
        // equals zero
        if sign == 0 || other == 0 {
            return other == sign;
        }
        // Differing signs
        if sign < 0 && other > 0 || sign > 0 && other < 0 {
            return false;
        }

        // We can't fall back to the `== Limb` impl when self is negative
        // since it'll fail because of signs
        if sign < 0 {
            if self.abs_size() > 1 {
                return false;
            }
            return *self.limbs() == (other.abs() as BaseInt);
        }

        self.eq(&Limb(other.abs() as BaseInt))
    }
}

impl PartialEq<Int> for i32 {
    #[inline]
    fn eq(&self, other: &Int) -> bool {
        other.eq(self)
    }
}

impl PartialOrd<i32> for Int {
    #[inline]
    fn partial_cmp(&self, &other: &i32) -> Option<Ordering> {
        let self_sign = self.sign();
        let other_sign = if other < 0 {
            -1
        } else if other > 0 {
            1
        } else {
            0
        };

        // Both are equal
        if self_sign == 0 && other_sign == 0 {
            return Some(Ordering::Equal);
        }

        let ord = if self_sign > other_sign {
            Ordering::Greater
        } else if self_sign < other_sign {
            Ordering::Less
        } else {
            // Now both signs are the same, and non-zero

            if self_sign < 0 {
                if self.abs_size() > 1 {
                    Ordering::Less
                } else {
                    self.to_single_limb()
                        .cmp(&Limb(other.abs() as BaseInt))
                        .reverse()
                }
            } else {
                return self.partial_cmp(&Limb(other.abs() as BaseInt));
            }
        };

        Some(ord)
    }
}

impl PartialOrd<Int> for i32 {
    #[inline]
    fn partial_cmp(&self, other: &Int) -> Option<Ordering> {
        other.partial_cmp(self).map(|o| o.reverse())
    }
}

impl PartialEq<usize> for Int {
    #[inline]
    fn eq(&self, &other: &usize) -> bool {
        return self.eq(&Limb(other as BaseInt));
    }
}

impl PartialEq<Int> for usize {
    #[inline]
    fn eq(&self, other: &Int) -> bool {
        other.eq(self)
    }
}

impl PartialOrd<usize> for Int {
    #[inline]
    fn partial_cmp(&self, &other: &usize) -> Option<Ordering> {
        self.partial_cmp(&Limb(other as BaseInt))
    }
}

impl PartialOrd<Int> for usize {
    #[inline]
    fn partial_cmp(&self, other: &Int) -> Option<Ordering> {
        Limb(*self as BaseInt).partial_cmp(other)
    }
}

const MAX_LIMB: u64 = !0 >> (64 - Limb::BITS);

// do a sign-magnitude comparison
fn eq_64(x: &Int, mag: u64, neg: bool) -> bool {
    let sign = if mag == 0 {
        0
    } else if neg {
        -1
    } else {
        1
    };
    if x.sign() != sign {
        return false;
    } else if mag == 0 {
        // we're guaranteed to have x == 0 since the signs match
        return true;
    }

    let abs_size = x.abs_size();
    debug_assert!(abs_size >= 1);
    let ptr = x.limbs();
    let lo_limb = *ptr;

    if mag < MAX_LIMB {
        abs_size == 1 && lo_limb.0 == mag as BaseInt
    } else {
        // we can only get here when Limbs are small, and the Int
        // is large
        assert_eq!(Limb::BITS, 32);

        if abs_size == 2 {
            let hi_limb = unsafe { *ptr.offset(1) };
            hi_limb.0 == (mag >> 32) as BaseInt && lo_limb.0 == mag as BaseInt
        } else {
            false
        }
    }
}

fn cmp_64(x: &Int, mag: u64, neg: bool) -> Ordering {
    if mag == 0 {
        return x.sign().cmp(&0);
    }

    let size = x.size;
    if (size < 0) != neg || size == 0 {
        // they have different signs
        return size.cmp(&if neg { -1 } else { 1 });
    }
    let ptr = x.limbs();
    let lo_limb = *ptr;

    let mag_ord = if mag < MAX_LIMB {
        (size.abs(), lo_limb.0).cmp(&(1, mag as BaseInt))
    } else {
        assert_eq!(Limb::BITS, 32);
        debug_assert!(size.abs() >= 1);
        let hi_limb = if size.abs() == 1 {
            Limb(0)
        } else {
            unsafe { *ptr.offset(1) }
        };

        (size.abs(), hi_limb.0, lo_limb.0).cmp(&(2, (mag >> 32) as BaseInt, mag as BaseInt))
    };
    if size < 0 && neg {
        // both negative, so the magnitude orderings need to be
        // flipped
        mag_ord.reverse()
    } else {
        mag_ord
    }
}

impl PartialEq<u64> for Int {
    fn eq(&self, &other: &u64) -> bool {
        eq_64(self, other, false)
    }
}

impl PartialEq<Int> for u64 {
    fn eq(&self, other: &Int) -> bool {
        eq_64(other, *self, false)
    }
}

impl PartialOrd<u64> for Int {
    fn partial_cmp(&self, &other: &u64) -> Option<Ordering> {
        Some(cmp_64(self, other, false))
    }
}

impl PartialOrd<Int> for u64 {
    fn partial_cmp(&self, other: &Int) -> Option<Ordering> {
        Some(cmp_64(other, *self, false).reverse())
    }
}

impl PartialEq<i64> for Int {
    fn eq(&self, &other: &i64) -> bool {
        eq_64(self, other.abs() as u64, other < 0)
    }
}

impl PartialEq<Int> for i64 {
    fn eq(&self, other: &Int) -> bool {
        eq_64(other, self.abs() as u64, *self < 0)
    }
}

impl PartialOrd<i64> for Int {
    fn partial_cmp(&self, &other: &i64) -> Option<Ordering> {
        Some(cmp_64(self, other.abs() as u64, other < 0))
    }
}

impl PartialOrd<Int> for i64 {
    fn partial_cmp(&self, other: &Int) -> Option<Ordering> {
        Some(cmp_64(other, self.abs() as u64, *self < 0).reverse())
    }
}

macro_rules! impl_from_prim (
    (signed $($t:ty),*) => {
        $(impl ::std::convert::From<$t> for Int {
            fn from(val: $t) -> Int {
                if val == 0 {
                    return Int::zero();
                } if val == <$t>::min_value() {
                    let shift = val.trailing_zeros() as usize;
                    let mut i = Int::one();
                    i = i << shift;
                    return -i;
                }

                let sizeof_t = std::mem::size_of::<$t>();
                let sizeof_baseint = std::mem::size_of::<BaseInt>();

                // Handle conversion where BaseInt is smaller than $t
                if sizeof_baseint < sizeof_t {
                    let val_abs = val.abs();
                    let mask : BaseInt = !0;
                    let size_factor = sizeof_t / sizeof_baseint;
                    let limb_bits = Limb::BITS as u32;

                    let mut i = Int::zero();
                    for j in 0..size_factor {
                        // This won't wrap, since sizeof($t) = size_factor * sizeof(BaseInt)
                        let vlimb = val_abs.wrapping_shr(limb_bits * (j as u32)) & (mask as $t);
                        i.push(Limb(vlimb as BaseInt));
                    }

                    if val < 0 {
                        i.size *= -1;
                    }

                    i.normalize();
                    return i;
                } else {
                    let limb = Limb(val.abs() as BaseInt);
                    let mut i = Int::from_single_limb(limb);
                    if val < 0 {
                        i.size *= -1;
                    }

                    return i;
                }
            }
        })*
    };
    (unsigned $($t:ty),*) => {
        $(impl ::std::convert::From<$t> for Int {
            fn from(val: $t) -> Int {
                if val == 0 {
                    return Int::zero();
                }

                let sizeof_t = std::mem::size_of::<$t>();
                let sizeof_baseint = std::mem::size_of::<BaseInt>();

                // Handle conversion where BaseInt is smaller than $t
                if sizeof_baseint < sizeof_t {
                    let mask : BaseInt = !0;
                    let size_factor = sizeof_t / sizeof_baseint;
                    let limb_bits = Limb::BITS as u32;

                    let mut i = Int::zero();
                    for j in 0..size_factor {
                        // This won't wrap, since sizeof($t) = size_factor * sizeof(BaseInt)
                        let vlimb = val.wrapping_shr(limb_bits * (j as u32)) & (mask as $t);
                        i.push(Limb(vlimb as BaseInt));
                    }
                    i.normalize();
                    return i;
                } else {
                    let limb = Limb(val as BaseInt);
                    return Int::from_single_limb(limb);
                }
            }
        })*
    }
);

impl_from_prim!(signed   i8, i16, i32, i64, i128, isize);
impl_from_prim!(unsigned u8, u16, u32, u64, u128, usize);

// Number formatting - There's not much difference between the impls,
// hence the macro

macro_rules! impl_fmt (
    ($t:path, $radix:expr, $upper:expr, $prefix:expr) => {
        impl $t for Int {
            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
                let mut s : &str = &self.to_str_radix($radix, $upper);
                let is_positive = self.sign() >= 0;
                // to_str_radix adds the sign if `self` is negative, but
                // pad_integral adds it's own sign, so slice the sign off
                if !is_positive {
                    s = &s[1..];
                }

                f.pad_integral(is_positive, $prefix, s)
            }
        }
    };

    ($t:path, $radix:expr, $prefix:expr) => {
        impl_fmt!($t, $radix, false, $prefix);
    }
);

impl_fmt!(fmt::Binary, 2, "0b");
impl_fmt!(fmt::Octal, 8, "0o");
impl_fmt!(fmt::Display, 10, "");
impl_fmt!(fmt::Debug, 10, "");
impl_fmt!(fmt::LowerHex, 16, false, "0x");
impl_fmt!(fmt::UpperHex, 16, true, "0x");

/// Error that arises when parsing an [`Int`].
///
/// [`Int`]: struct.Int.html
#[derive(Debug, Clone, PartialEq)]
pub struct ParseIntError {
    kind: ErrorKind,
}

#[derive(Debug, Clone, PartialEq)]
enum ErrorKind {
    Empty,
    InvalidDigit,
}

impl fmt::Display for ParseIntError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self.kind {
            ErrorKind::Empty => f.write_str("cannot parse empty string"),
            ErrorKind::InvalidDigit => f.write_str("invalid digit found in string"),
        }
    }
}

impl Error for ParseIntError {}

impl FromStr for Int {
    type Err = ParseIntError;

    fn from_str(src: &str) -> Result<Int, ParseIntError> {
        Int::from_str_radix(src, 10)
    }
}

// Conversion *to* primitives via the From trait.

macro_rules! impl_from_for_prim (
    (signed $($t:ty),*) => (
        $(impl<'a> std::convert::From<&'a Int> for $t {
            fn from(i: &'a Int) -> $t {
                let sign = i.sign() as $t;
                if sign == 0 {
                    return 0;
                }

                let sizeof_t = std::mem::size_of::<$t>();
                let sizeof_baseint = std::mem::size_of::<BaseInt>();

                // Handle conversion where BaseInt is smaller than $t
                if sizeof_baseint < sizeof_t {
                    // Fallthrough if there's only one limb
                    if i.abs_size() >= 2 {
                        // The number of limbs that fit in $t
                        let size_factor = sizeof_t / sizeof_baseint;
                        // We can't copy more limbs than we have
                        let num_limbs_to_copy = std::cmp::min(size_factor, i.abs_size() as usize);

                        // Accumulate the limbs into $t
                        let limb_size = Limb::BITS as u32;
                        let mut acc: $t = 0;
                        for j in 0..num_limbs_to_copy {
                            let limb = unsafe { (*i.ptr.as_ptr().offset(j as isize)).0 } as $t;
                            acc |= limb.wrapping_shl(limb_size * (j as u32));
                        }

                        // Apply the sign
                        return acc.wrapping_mul(sign);
                    }
                }
                let n = i.to_single_limb().0;
                // Using wrapping_mul to account for when the binary
                // representation of n == $t::MIN
                return (n as $t).wrapping_mul(sign);
            }
        })*
    );
    (unsigned $($t:ty),*) => (
        $(impl<'a> std::convert::From<&'a Int> for $t {
            fn from(i: &'a Int) -> $t {
                if i.sign() == 0 {
                    return 0;
                }

                let sizeof_t = std::mem::size_of::<$t>();
                let sizeof_baseint = std::mem::size_of::<BaseInt>();

                // Handle conversion where BaseInt is smaller than $t
                if sizeof_baseint < sizeof_t {
                    // Fallthrough if there's only one limb
                    if i.abs_size() >= 2 {
                        // The number of limbs that fit in $t
                        let size_factor = sizeof_t / sizeof_baseint;
                        // We can't copy more limbs than we have
                        let num_limbs_to_copy = std::cmp::min(size_factor, i.abs_size() as usize);

                        // Accumulate the limbs into $t
                        let limb_size = Limb::BITS as u32;
                        let mut acc: $t = 0;
                        for j in 0..num_limbs_to_copy {
                            let limb = unsafe { (*i.ptr.as_ptr().offset(j as isize)).0 } as $t;
                            acc |= limb.wrapping_shl(limb_size * (j as u32));
                        }

                        return acc;
                    }
                }

                let n = i.to_single_limb().0;
                return n as $t;
            }
        })*
    )
);

impl_from_for_prim!(signed   i8, i16, i32, i64, i128, isize);
impl_from_for_prim!(unsigned u8, u16, u32, u64, u128, usize);

impl Zero for Int {
    fn zero() -> Int {
        Int {
            ptr: Unique::dangling(),
            size: 0,
            cap: 0,
        }
    }

    fn is_zero(&self) -> bool {
        self.sign() == 0
    }
}

impl One for Int {
    fn one() -> Int {
        Int::from(1)
    }
}

impl Num for Int {
    type FromStrRadixErr = ParseIntError;

    #[inline]
    fn from_str_radix(src: &str, radix: u32) -> Result<Int, ParseIntError> {
        Int::from_str_radix(src, radix as u8)
    }
}

impl Integer for Int {
    #[inline]
    fn div_floor(&self, other: &Int) -> Int {
        self / other
    }

    #[inline]
    fn mod_floor(&self, other: &Int) -> Int {
        self % other
    }

    #[inline]
    fn gcd(&self, other: &Int) -> Int {
        self.gcd(other)
    }

    #[inline]
    fn lcm(&self, other: &Int) -> Int {
        self.lcm(other)
    }

    #[inline]
    fn divides(&self, other: &Int) -> bool {
        other.is_multiple_of(self)
    }

    #[inline]
    fn is_multiple_of(&self, other: &Int) -> bool {
        (self % other).is_zero()
    }

    #[inline]
    fn is_even(&self) -> bool {
        self.is_even()
    }

    #[inline]
    fn is_odd(&self) -> bool {
        !self.is_even()
    }

    #[inline]
    fn div_rem(&self, other: &Int) -> (Int, Int) {
        self.divrem(other)
    }
}

unsafe impl std::iter::Step for Int {
    fn steps_between(start: &Int, end: &Int) -> Option<usize> {
        let diff = (start - end).abs();

        // Check to see if result fits in a usize
        if diff > !0usize {
            None
        } else {
            Some(usize::from(&diff))
        }
    }

    fn forward_checked(start: Int, n: usize) -> Option<Self> {
        Some(start + Int::from(n))
    }

    fn backward_checked(start: Int, n: usize) -> Option<Self> {
        Some(start - Int::from(n))
    }
}

/// Trait for generating random `Int`s.
///
/// # Example
///
/// Generate a random `Int` of size `256` bits:
///
/// ```
/// extern crate rand;
/// extern crate ramp;
///
/// use ramp::RandomInt;
///
/// fn main() {
///     let mut rng = rand::thread_rng();
///     let big_i = rng.gen_int(256);
/// }
/// ```
pub trait RandomInt {
    /// Generate a random unsigned `Int` of given bit size.
    fn gen_uint(&mut self, bits: usize) -> Int;

    /// Generate a random `Int` of given bit size.
    fn gen_int(&mut self, bits: usize) -> Int;

    /// Generate a random unsigned `Int` less than the given bound.
    /// Fails when the bound is zero or negative.
    fn gen_uint_below(&mut self, bound: &Int) -> Int;

    /// Generate a random `Int` within the given range.
    /// The lower bound is inclusive; the upper bound is exclusive.
    /// Fails when the upper bound is not greater than the lower bound.
    fn gen_int_range(&mut self, lbound: &Int, ubound: &Int) -> Int;
}

impl<R: Rng> RandomInt for R {
    fn gen_uint(&mut self, bits: usize) -> Int {
        assert!(bits > 0);

        let limbs = (bits / &Limb::BITS) as u32;
        let rem = bits % &Limb::BITS;

        let mut i = Int::with_capacity(limbs + 1);

        for _ in 0..limbs {
            let limb = Limb(self.gen());
            i.push(limb);
        }

        if rem > 0 {
            let final_limb = Limb(self.gen());
            i.push(final_limb >> (&Limb::BITS - rem));
        }

        i.normalize();

        i
    }

    fn gen_int(&mut self, bits: usize) -> Int {
        let i = self.gen_uint(bits);

        let r = if i == Int::zero() {
            // ...except that if the BigUint is zero, we need to try
            // again with probability 0.5. This is because otherwise,
            // the probability of generating a zero BigInt would be
            // double that of any other number.
            if self.gen() {
                return self.gen_uint(bits);
            } else {
                i
            }
        } else if self.gen() {
            -i
        } else {
            i
        };

        r
    }

    fn gen_uint_below(&mut self, bound: &Int) -> Int {
        assert!(*bound > Int::zero());
        // If we haven't got a valid number after 10,000 tries, then something
        // has probably gone wrong, as there is a 1 in 10^3000 chance of this
        // happening, in the worst case.
        const ITER_LIMIT: usize = 10000;

        let bits = bound.bit_length() as usize;

        // Since it uses a number of bits, gen_uint may return a number too large,
        // loop until we generate a valid number.
        // Since the greatest gap between the bound and the largest number produced
        // is when bound = 2^n (bit string [100000....]), we have, at worst, a 50/50
        // chance of producing an invalid number each iteration.
        let mut count = 0;
        while count < ITER_LIMIT {
            let n = self.gen_uint(bits);
            if n < *bound {
                return n;
            }
            count += 1;
        }

        panic!(
            "No valid number generated in {} iterations.\n\
             Please open an issue at https://github.com/Aatch/ramp",
            ITER_LIMIT
        );
    }

    fn gen_int_range(&mut self, lbound: &Int, ubound: &Int) -> Int {
        assert!(*lbound < *ubound);
        lbound + self.gen_uint_below(&(ubound - lbound))
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use ll::limb::Limb;
    use rand::{self, Rng};
    use std;
    use std::hash::{Hash, Hasher};
    use std::str::FromStr;
    use test::{self, Bencher};
    use traits::DivRem;

    macro_rules! assert_mp_eq (
        ($l:expr, $r:expr) => (
            {
                let l : &Int = &$l;
                let r : &Int = &$r;
                if l != r {
                    println!("assertion failed: {} == {}", stringify!($l), stringify!($r));
                    panic!("{:} != {:}", l, r);
                }
            }
        )
    );

    #[test]
    fn from_string_10() {
        let cases = [
            ("0", 0i32),
            ("123456", 123456),
            ("0123", 123),
            ("000000", 0),
            ("-0", 0),
            ("-1", -1),
            ("-123456", -123456),
            ("-0123", -123),
        ];

        for &(s, n) in cases.iter() {
            let i: Int = s.parse().unwrap();
            assert_eq!(i, n);
        }
    }

    #[test]
    fn from_string_16() {
        let cases = [
            ("0", 0i32),
            ("abcde", 0xabcde),
            ("0ABC", 0xabc),
            ("12AB34cd", 0x12ab34cd),
            ("-ABC", -0xabc),
            ("-0def", -0xdef),
            ("00000000000000000", 0),
        ];

        for &(s, n) in cases.iter() {
            let i: Int = Int::from_str_radix(s, 16).unwrap();
            assert_eq!(i, n, "Assertion failed: {:#x} != {:#x}", i, n);
        }
    }

    #[test]
    fn to_string_10() {
        let cases = [
            ("0", Int::zero()),
            ("1", Int::from(1)),
            ("123", Int::from(123)),
            ("-456", Int::from(-456)),
            (
                "987654321012345678910111213",
                Int::from_str("987654321012345678910111213").unwrap(),
            ),
        ];

        for &(s, ref n) in cases.iter() {
            assert_eq!(s, &n.to_string());
        }
    }

    #[test]
    fn to_string_16() {
        let cases = [
            ("0", Int::zero()),
            ("1", Int::from(1)),
            ("-1", Int::from(-1)),
            ("abc", Int::from(0xabc)),
            ("-456", Int::from(-0x456)),
            (
                "987654321012345678910111213",
                Int::from_str_radix("987654321012345678910111213", 16).unwrap(),
            ),
        ];

        for &(s, ref n) in cases.iter() {
            assert_eq!(s, &n.to_str_radix(16, false));
        }
    }

    #[test]
    fn num_base_digits_pow2() {
        use ll::base::num_base_digits;
        let cases = [
            ("10", 2, 4), // 0b 1010
            ("15", 2, 4), // 0b 1111
            ("16", 2, 5), // 0b10000
            ("1023", 2, 10), // 0b 1111111111
            ("1024", 2, 11), // 0b10000000000
            ("341", 4, 5), // 4»11111
            ("5461", 4, 7), // 4»1111111
            ("16383", 4, 7), // 4» 3333333
            ("16384", 4, 8), // 4»10000000
            ("65535", 4, 8), // 4»33333333
            ("299593", 8, 7), // 8»1111111 // 8**0 + 8**1 + 8**2 + 8**3 + 8**4 + 8**5 + 8**6
            ("299594", 8, 7), // 8»1111112
            ("2097151", 8, 7), // 8» 7777777
            ("2097152", 8, 8), // 8»10000000
            ("268435455", 16, 7), // 0x fffffff
            ("268435456", 16, 8), // 0x10000000
            ("13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084095", 2, 512), // 512 bits with value 1 -> 1 Limb
            ("13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084096", 2, 513), // 513 bits -> 2 Limbs
        ];
        for &(s, base, digits) in cases.iter() {
            let i: Int = s.parse().unwrap();
            unsafe {
                assert_eq!(digits, num_base_digits(i.limbs(), i.abs_size(), base));
            }
        }
    }

    #[test]
    fn num_base_digits() {
        use ll::base::num_base_digits;
        let cases = [
            ("0", 15, 1),
            ("0", 58, 1),
            ("49172", 10, 5),
            ("49172", 57, 3),  // [15, 7, 38], 38 + 7*57 + 15*57**2 = 49172
            ("185192", 57, 3), // [56, 56, 56], 56 + 56*57 + 56*57**2 = 185192
            ("185193", 57, 4), // [1, 0, 0, 0], 1*57**3 = 185193
            ("250046", 63, 3), // [62, 62, 62], 62 + 62*63 + 62*63**2 = 250046
            ("250047", 63, 4), // [1, 0, 0, 0], 1*63**3 = 250047
            ("274624", 65, 3), // [64, 64, 64], 64 + 64*65 + 64*65**2 = 274624
            ("274625", 65, 4), // [1, 0, 0, 0], 1*65**3 = 274625
        ];
        for &(s, base, digits) in cases.iter() {
            let i: Int = s.parse().unwrap();
            unsafe {
                let estimate = num_base_digits(i.limbs(), i.abs_size(), base);
                assert!(digits == estimate || digits == estimate - 1);
            }
        }
    }

    #[test]
    fn pow() {
        let bases = [
            "0",
            "1",
            "190000000000000",
            "192834857324591531",
            "340282366920938463463374607431768211456", // 2**128
            "100000000",
            "-1",
            "-100",
            "-200",
            "-192834857324591531",
            "-431343873217510631841",
            "-340282366920938463463374607431768211456",
        ];

        for b in bases.iter() {
            let b: Int = b.parse().unwrap();
            let mut x = Int::one();
            for e in 0..512 {
                let a = &b.pow(e);
                // println!("b={}, e={}, a={}, x={}", &b, &e, &a, &x);
                assert_mp_eq!(a.clone(), x.clone());
                x = &x * &b
            }
        }
    }

    /// The `bigresults` testcases were generated by the following Python code
    ///
    /// ```python
    /// bases = [
    ///     "0", "1", "190000000000000", "192834857324591531",
    ///     "340282366920938463463374607431768211456", "100000000", "-1", "-100", "-200",
    ///     "-192834857324591531", "-431343873217510631841",
    ///     "-340282366920938463463374607431768211456"
    /// ]
    ///
    /// moduli = [
    ///     "1", "2", "77", "102847", "923847928374928374928098123", "-1", "-2", "-77", "-102847",
    ///     "-923847928374928374928098123"
    /// ]
    ///
    /// # Pick one of the exponents below
    /// e = int("983459824098102")
    /// #e = int("30297523982304983")
    ///
    /// for b in map(int, bases):
    ///     for m in map(int, moduli):
    ///         x = pow(b, e, m)
    ///
    ///         # Skip the manipulation below
    ///         if x == 0:
    ///             print(x)
    ///             continue
    ///
    ///         # True iff the sign of b^e is negative
    ///         powneg = (b < 0) and (e % 2 == 1)
    ///
    ///         # If b^e is negative XOR the modulus is positive, print the result as-is
    ///         if powneg ^ (m >= 0):
    ///             print(x)
    ///         # Otherwise, flip it
    ///         else:
    ///             print(x - m)
    /// ```
    #[test]
    fn pow_mod() {
        let bases = [
            "0",
            "1",
            "190000000000000",
            "192834857324591531",
            "340282366920938463463374607431768211456",
            "100000000",
            "-1",
            "-100",
            "-200",
            "-192834857324591531",
            "-431343873217510631841",
            "-340282366920938463463374607431768211456",
        ];
        let moduli = [
            "1",
            "2",
            "77",
            "102847",
            "923847928374928374928098123",
            "-1",
            "-2",
            "-77",
            "-102847",
            "-923847928374928374928098123",
        ];

        let big_expt1: Int = "983459824098102".parse().unwrap();
        let big_results1 = [
            "0",
            "0",
            "0",
            "0",
            "0",
            "0",
            "0",
            "0",
            "0",
            "0",
            "0",
            "1",
            "1",
            "1",
            "1",
            "0",
            "1",
            "1",
            "1",
            "1",
            "0",
            "0",
            "64",
            "81700",
            "650397494965841282553028378",
            "0",
            "0",
            "64",
            "81700",
            "650397494965841282553028378",
            "0",
            "1",
            "14",
            "2984",
            "293908402213598797808604757",
            "0",
            "1",
            "14",
            "2984",
            "293908402213598797808604757",
            "0",
            "0",
            "64",
            "79782",
            "294430149849779620413037114",
            "0",
            "0",
            "64",
            "79782",
            "294430149849779620413037114",
            "0",
            "0",
            "1",
            "45620",
            "410140929051586324284535549",
            "0",
            "0",
            "1",
            "45620",
            "410140929051586324284535549",
            "0",
            "1",
            "1",
            "1",
            "1",
            "0",
            "1",
            "1",
            "1",
            "1",
            "0",
            "0",
            "1",
            "64031",
            "36844801842501039220835119",
            "0",
            "0",
            "1",
            "64031",
            "36844801842501039220835119",
            "0",
            "0",
            "15",
            "2604",
            "177460521562747360312778824",
            "0",
            "0",
            "15",
            "2604",
            "177460521562747360312778824",
            "0",
            "1",
            "14",
            "2984",
            "293908402213598797808604757",
            "0",
            "1",
            "14",
            "2984",
            "293908402213598797808604757",
            "0",
            "1",
            "1",
            "18906",
            "873601645071303646536712038",
            "0",
            "1",
            "1",
            "18906",
            "873601645071303646536712038",
            "0",
            "0",
            "64",
            "79782",
            "294430149849779620413037114",
            "0",
            "0",
            "64",
            "79782",
            "294430149849779620413037114",
        ];

        let big_expt2: Int = "30297523982304983".parse().unwrap();
        let big_results2 = [
            "0",
            "0",
            "0",
            "0",
            "0",
            "0",
            "0",
            "0",
            "0",
            "0",
            "0",
            "1",
            "1",
            "1",
            "1",
            "0",
            "1",
            "1",
            "1",
            "1",
            "0",
            "0",
            "71",
            "95361",
            "176018964989535053333805796",
            "0",
            "0",
            "71",
            "95361",
            "176018964989535053333805796",
            "0",
            "1",
            "70",
            "97130",
            "379622449400387577033857765",
            "0",
            "1",
            "70",
            "97130",
            "379622449400387577033857765",
            "0",
            "0",
            "16",
            "22931",
            "923257520141185284248663506",
            "0",
            "0",
            "16",
            "22931",
            "923257520141185284248663506",
            "0",
            "0",
            "67",
            "61927",
            "735007863677635702331962114",
            "0",
            "0",
            "67",
            "61927",
            "735007863677635702331962114",
            "0",
            "-1",
            "-1",
            "-1",
            "-1",
            "0",
            "-1",
            "-1",
            "-1",
            "-1",
            "0",
            "0",
            "-67",
            "-50340",
            "-639061946068491056215087558",
            "0",
            "0",
            "-67",
            "-50340",
            "-639061946068491056215087558",
            "0",
            "0",
            "-30",
            "-48472",
            "-783769839004928514409300748",
            "0",
            "0",
            "-30",
            "-48472",
            "-783769839004928514409300748",
            "0",
            "-1",
            "-70",
            "-97130",
            "-379622449400387577033857765",
            "0",
            "-1",
            "-70",
            "-97130",
            "-379622449400387577033857765",
            "0",
            "-1",
            "-1",
            "-55833",
            "-913941961265646087594551688",
            "0",
            "-1",
            "-1",
            "-55833",
            "-913941961265646087594551688",
            "0",
            "0",
            "-16",
            "-22931",
            "-923257520141185284248663506",
            "0",
            "0",
            "-16",
            "-22931",
            "-923257520141185284248663506",
        ];

        // Do the calculations for small expts first. Just do up to 80
        for b in bases.iter() {
            for m in moduli.iter() {
                for i in 0..80 {
                    let b: Int = b.parse().unwrap();
                    let e: Int = Int::from(i);
                    let m: Int = m.parse().unwrap();

                    let a = b.pow_mod(&e, &m);
                    assert_mp_eq!(a, b.pow(i as usize) % m)
                }
            }
        }

        // Now do the big expts
        for (big_expt, big_results) in [big_expt1, big_expt2]
            .iter()
            .zip([big_results1, big_results2].iter())
        {
            for (b_i, b) in bases.iter().enumerate() {
                for (m_i, m) in moduli.iter().enumerate() {
                    let b: Int = b.parse().unwrap();
                    let m: Int = m.parse().unwrap();
                    let a = b.pow_mod(&big_expt, &m);

                    let expected: Int = big_results[b_i * moduli.len() + m_i].parse().unwrap();
                    assert_mp_eq!(a, expected);
                }
            }
        }
    }

    #[should_panic]
    #[test]
    fn pow_mod_zeromod() {
        let b = Int::from(10);
        let e = Int::from(2);
        let m = Int::zero();
        b.pow_mod(&e, &m);
    }

    #[should_panic]
    #[test]
    fn pow_mod_negexp() {
        let b = Int::from(10);
        let e = Int::from(-2);
        let m = Int::from(50);
        b.pow_mod(&e, &m);
    }

    #[test]
    fn add() {
        let cases = [
            ("0", "0", "0"),
            ("1", "0", "1"),
            ("1", "1", "2"),
            ("190000000000000", "1", "190000000000001"),
            (
                "192834857324591531",
                "431343873217510631841",
                "431536708074835223372",
            ),
            ("0", "-1", "-1"),
            ("1", "-1", "0"),
            ("100000000", "-1", "99999999"),
            ("-100", "-100", "-200"),
            (
                "-192834857324591531",
                "-431343873217510631841",
                "-431536708074835223372",
            ),
            // (2**64 - 1) * 2**64 + 2**64 == 2**128
            (
                "340282366920938463444927863358058659840",
                "18446744073709551616",
                "340282366920938463463374607431768211456",
            ),
        ];

        for &(l, r, a) in cases.iter() {
            let l: Int = l.parse().unwrap();
            let r: Int = r.parse().unwrap();
            let a: Int = a.parse().unwrap();

            assert_mp_eq!(l + r, a);
        }
    }

    #[test]
    fn sub() {
        let cases = [
            ("0", "0", "0"),
            ("1", "0", "1"),
            ("1", "1", "0"),
            ("0", "1", "-1"),
            ("190000000000000", "1", "189999999999999"),
            (
                "192834857324591531",
                "431343873217510631841",
                "-431151038360186040310",
            ),
            ("0", "-1", "1"),
            ("1", "-1", "2"),
            ("100000000", "-1", "100000001"),
            ("-100", "-100", "0"),
            ("-100", "100", "-200"),
            ("237", "236", "1"),
            (
                "-192834857324591531",
                "-431343873217510631841",
                "431151038360186040310",
            ),
            // (2**64 - 1) * 2**64 - -2**64 == 2**128
            (
                "340282366920938463444927863358058659840",
                "-18446744073709551616",
                "340282366920938463463374607431768211456",
            ),
        ];

        for &(l, r, a) in cases.iter() {
            let l: Int = l.parse().unwrap();
            let r: Int = r.parse().unwrap();
            let a: Int = a.parse().unwrap();

            assert_mp_eq!(&l - &r, a.clone());
            assert_mp_eq!(&l - r.clone(), a.clone());
            assert_mp_eq!(l.clone() - &r, a.clone());
            assert_mp_eq!(l - r, a);
        }
    }

    #[test]
    fn mul() {
        let cases = [
            ("0", "0", "0"),
            ("1", "0", "0"),
            ("1", "1", "1"),
            ("1234", "-1", "-1234"),
            ("8", "9", "72"),
            ("-8", "-9", "72"),
            ("8", "-9", "-72"),
            (
                "1234567891011",
                "9876543210123",
                "12193263121400563935904353",
            ),
            (
                "-1234567891011",
                "9876543210123",
                "-12193263121400563935904353",
            ),
        ];

        for &(l, r, a) in cases.iter() {
            let l: Int = l.parse().unwrap();
            let r: Int = r.parse().unwrap();
            let a: Int = a.parse().unwrap();

            assert_mp_eq!(l * r, a);
        }
    }

    #[test]
    fn div() {
        let cases = [
            ("1", "1", "1"),
            ("1234", "-1", "-1234"),
            ("8", "9", "0"),
            ("-9", "-3", "3"),
            ("1234567891011121314151617", "95123654789852856006", "12978"),
            ("-1234567891011121314151617", "95123654789852856006", "-12978"),
            ("-1198775410753307067346230628764044530011323809665206377243907561641040294348297309637331525393593945901384203950086960228531308793518800829453656715578105987032036211272103322425770761458186593",
             "979504192721382235629958845425279521512826176107035761459344386626944187481828320416870752582555",
             "-1223859397092234843008309150569447886995823751180958876260102037121722431272801092547910923059616")
        ];

        for &(l, r, a) in cases.iter() {
            let l: Int = l.parse().unwrap();
            let r: Int = r.parse().unwrap();
            let a: Int = a.parse().unwrap();

            let val = &l / &r;
            assert_mp_eq!(val, a);
        }
    }

    #[test]
    #[should_panic(expected = "divide by zero")]
    #[cfg(debug_assertions)] // only a panic in this mode
    fn divmod_zero() {
        Int::from(1).divmod(&Int::zero());
    }

    #[test]
    fn rem() {
        let cases = [
            ("2", "1", "0"),
            ("1", "2", "1"),
            ("100", "2", "0"),
            ("100", "3", "1"),
            (
                "234129835798275032157029375235",
                "4382109473241242142341234",
                "2490861941946976021925083",
            ),
            ("-2", "1", "0"),
            ("-1", "2", "-1"),
            ("-100", "2", "0"),
            ("-100", "3", "-1"),
            (
                "-234129835798275032157029375235",
                "4382109473241242142341234",
                "-2490861941946976021925083",
            ),
            ("2", "-1", "0"),
            ("1", "-2", "1"),
            ("100", "-2", "0"),
            ("100", "-3", "1"),
            (
                "234129835798275032157029375235",
                "-4382109473241242142341234",
                "2490861941946976021925083",
            ),
            ("-2", "-1", "0"),
            ("-1", "-2", "-1"),
            ("-100", "-2", "0"),
            ("-100", "-3", "-1"),
            (
                "-234129835798275032157029375235",
                "-4382109473241242142341234",
                "-2490861941946976021925083",
            ),
        ];

        for &(l, r, a) in cases.iter() {
            let l: Int = l.parse().unwrap();
            let r: Int = r.parse().unwrap();
            let a: Int = a.parse().unwrap();

            let val = &l % &r;
            assert_mp_eq!(val, a);
        }
    }

    #[test]
    fn divrem() {
        let cases = [
            ("20000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000001",
             "100000000000000000000000000000000000000000000001",
             "200000000000000000000000000000000000000000000001",
             "100000000000000000000000000000000000000000000000"),
        ];

        for t in cases.iter() {
            let dividend: Int = t.0.parse().unwrap();
            let divisor: Int = t.1.parse().unwrap();
            let expected_quotient: Int = t.2.parse().unwrap();
            let expected_remainder: Int = t.3.parse().unwrap();

            let (actual_quotient, actual_remainder) = (&dividend).divrem(&divisor);
            assert_mp_eq!(actual_quotient, expected_quotient);
            assert_mp_eq!(actual_remainder, expected_remainder);
        }
    }

    #[test]
    fn sqrt_rem() {
        let cases = [
            ("0", "0", "0"),
            ("1", "1", "0"),
            ("2", "1", "1"),
            ("3", "1", "2"),
            ("4", "2", "0"),
            ("1000", "31", "39"),
            (
                "15241578753238836750495351562536198787501905199875019052100",
                "123456789012345678901234567890",
                "0",
            ),
            (
                "15241578753238836750495351562536198787501905199875019052099",
                "123456789012345678901234567889",
                "246913578024691357802469135778",
            ),
            (
                "15241578753238836750495351562536198787501905199875019052101",
                "123456789012345678901234567890",
                "1",
            ),
        ];

        for &(x, sqrt, rem) in &cases {
            let x: Int = x.parse().unwrap();
            let sqrt: Int = sqrt.parse().unwrap();
            let rem: Int = rem.parse().unwrap();

            if x != 0 {
                assert!((-&x).sqrt_rem().is_none());
            }

            let (s, r) = x.sqrt_rem().unwrap();
            assert_mp_eq!(s, sqrt);
            assert_mp_eq!(r, rem);
        }
    }

    #[test]
    fn bitand() {
        let cases = [
            ("0", "1", "0"),
            ("17", "65", "1"),
            ("-17", "65", "65"),
            ("17", "-65", "17"),
            ("-17", "-65", "-81"),
            ("0", "543253451643657932075830214751263521", "0"),
            (
                "-1",
                "543253451643657932075830214751263521",
                "543253451643657932075830214751263521",
            ),
            (
                "47398217493274092174042109472",
                "9843271092740214732017421",
                "152974816756326460458496",
            ),
            (
                "87641324986400000000000",
                "31470973247490321000000000000000",
                "2398658832415825854464",
            ),
            (
                "-87641324986400000000000",
                "31470973247490321000000000000000",
                "31470973245091662167584174145536",
            ),
            (
                "87641324986400000000000",
                "-31470973247490321000000000000000",
                "85242666153984174129152",
            ),
            (
                "-87641324986400000000000",
                "-31470973247490321000000000000000",
                "-31470973332732987153984174129152",
            ),
        ];

        for &(l_, r_, a) in cases.iter() {
            let l: Int = l_.parse().unwrap();
            let r: Int = r_.parse().unwrap();
            let a: Int = a.parse().unwrap();

            let val = &l & &r;
            assert_mp_eq!(val, a);

            if l.bit_length() <= 31 {
                let l: i32 = l_.parse().unwrap();
                let val = l & &r;
                assert_mp_eq!(val, a);
            }
            if r.bit_length() <= 31 {
                let r: i32 = r_.parse().unwrap();
                let val = &l & r;
                assert_mp_eq!(val, a);
            }
        }
    }

    #[test]
    fn bitor() {
        let cases = [
            ("0", "1", "1"),
            ("17", "65", "81"),
            ("-17", "65", "-17"),
            ("17", "-65", "-65"),
            ("-17", "-65", "-1"),
            (
                "0",
                "543253451643657932075830214751263521",
                "543253451643657932075830214751263521",
            ),
            ("-1", "543253451643657932075830214751263521", "-1"),
            (
                "47398217493274092174042109472",
                "9843271092740214732017421",
                "47407907789550076062313668397",
            ),
            (
                "87641324986400000000000",
                "31470973247490321000000000000000",
                "31470973332732987153984174145536",
            ),
            (
                "-87641324986400000000000",
                "31470973247490321000000000000000",
                "-85242666153984174145536",
            ),
            (
                "87641324986400000000000",
                "-31470973247490321000000000000000",
                "-31470973245091662167584174129152",
            ),
            (
                "-87641324986400000000000",
                "-31470973247490321000000000000000",
                "-2398658832415825870848",
            ),
        ];

        for &(l_, r_, a) in cases.iter() {
            let l: Int = l_.parse().unwrap();
            let r: Int = r_.parse().unwrap();
            let a: Int = a.parse().unwrap();

            let val = &l | &r;
            assert_mp_eq!(val, a);

            if l.bit_length() <= 31 {
                let l: i32 = l_.parse().unwrap();
                let val = l | &r;
                assert_mp_eq!(val, a);
            }
            if r.bit_length() <= 31 {
                let r: i32 = r_.parse().unwrap();
                let val = &l | r;
                assert_mp_eq!(val, a);
            }
        }
    }

    #[test]
    fn bitxor() {
        let cases = [
            ("0", "1", "1"),
            ("17", "65", "80"),
            ("-17", "65", "-82"),
            ("17", "-65", "-82"),
            ("-17", "-65", "80"),
            (
                "0",
                "543253451643657932075830214751263521",
                "543253451643657932075830214751263521",
            ),
            (
                "-1",
                "543253451643657932075830214751263521",
                "-543253451643657932075830214751263522",
            ),
            (
                "47398217493274092174042109472",
                "9843271092740214732017421",
                "47407754814733319735853209901",
            ),
            (
                "87641324986400000000000",
                "31470973247490321000000000000000",
                "31470973330334328321568348291072",
            ),
            (
                "-87641324986400000000000",
                "31470973247490321000000000000000",
                "-31470973330334328321568348291072",
            ),
            (
                "87641324986400000000000",
                "-31470973247490321000000000000000",
                "-31470973330334328321568348258304",
            ),
            (
                "-87641324986400000000000",
                "-31470973247490321000000000000000",
                "31470973330334328321568348258304",
            ),
        ];

        for &(l_, r_, a) in cases.iter() {
            let l: Int = l_.parse().unwrap();
            let r: Int = r_.parse().unwrap();
            let a: Int = a.parse().unwrap();

            let val = &l ^ &r;
            assert_mp_eq!(val, a);

            if l.bit_length() <= 31 {
                let l: i32 = l_.parse().unwrap();
                let val = l ^ &r;
                assert_mp_eq!(val, a);
            }
            if r.bit_length() <= 31 {
                let r: i32 = r_.parse().unwrap();
                let val = &l ^ r;
                assert_mp_eq!(val, a);
            }
        }
    }

    #[test]
    fn is_even() {
        let cases = [
            ("0", true),
            ("1", false),
            ("47398217493274092174042109472", true),
            ("47398217493274092174042109471", false),
        ];

        for &(v, even) in cases.iter() {
            let val: Int = v.parse().unwrap();

            assert_eq!(val.is_even(), even);

            let val = -val;
            assert_eq!(val.is_even(), even);
        }
    }

    #[test]
    fn trailing_zeros() {
        let cases = [
            ("0", 0),
            ("1", 0),
            ("16", 4),
            (
                "3036937844145311324764506857395738547330878864826266812416",
                100,
            ),
        ];

        for &(v, count) in cases.iter() {
            let val: Int = v.parse().unwrap();

            assert_eq!(val.trailing_zeros(), count);
        }
    }

    #[test]
    fn arith_prim() {
        // Test that the Int/prim overloads are working as expected

        let x: Int = "100".parse().unwrap();

        // Int op prim
        assert_mp_eq!(&x + 1usize, "101".parse().unwrap());
        assert_mp_eq!(&x - 1usize, "99".parse().unwrap());

        assert_mp_eq!(&x + 1i32, "101".parse().unwrap());
        assert_mp_eq!(&x - 1i32, "99".parse().unwrap());

        assert_mp_eq!(&x + (-1i32), "99".parse().unwrap());
        assert_mp_eq!(&x - (-1i32), "101".parse().unwrap());
        assert_mp_eq!(&x + (-101i32), "-1".parse().unwrap());
        assert_mp_eq!(&x - 101i32, "-1".parse().unwrap());

        assert_mp_eq!(&x - 100usize, Int::zero());
        assert_mp_eq!(-&x + 100usize, Int::zero());
        assert_mp_eq!(&x - 100i32, Int::zero());
        assert_mp_eq!(&x + (-100i32), Int::zero());
        assert_mp_eq!(-&x + 100i32, Int::zero());
        assert_mp_eq!(-&x - (-100i32), Int::zero());

        assert_mp_eq!(&x * 2usize, "200".parse().unwrap());

        assert_mp_eq!(&x * 2i32, "200".parse().unwrap());
        assert_mp_eq!(&x * (-2i32), "-200".parse().unwrap());

        assert_mp_eq!(&x / 2usize, "50".parse().unwrap());
        assert_mp_eq!(&x / 2i32, "50".parse().unwrap());
        assert_mp_eq!(&x / (-2i32), "-50".parse().unwrap());

        assert_mp_eq!(&x % 2usize, "0".parse().unwrap());
        assert_mp_eq!(&x % 2i32, "0".parse().unwrap());
        assert_mp_eq!(&x % (-2i32), "0".parse().unwrap());

        let x: Int = "5".parse().unwrap();

        // prim op Int
        assert_mp_eq!(1usize + &x, "6".parse().unwrap());
        assert_mp_eq!(1usize - &x, "-4".parse().unwrap());

        assert_mp_eq!(1i32 + &x, "6".parse().unwrap());
        assert_mp_eq!(1i32 - &x, "-4".parse().unwrap());

        assert_mp_eq!((-1i32) + &x, "4".parse().unwrap());
        assert_mp_eq!((-1i32) - &x, "-6".parse().unwrap());

        assert_mp_eq!(2usize * &x, "10".parse().unwrap());

        assert_mp_eq!(2i32 * &x, "10".parse().unwrap());
        assert_mp_eq!((-2i32) * &x, "-10".parse().unwrap());

        assert_mp_eq!(20usize / &x, "4".parse().unwrap());
        assert_mp_eq!(20i32 / &x, "4".parse().unwrap());
        assert_mp_eq!((-20i32) / &x, "-4".parse().unwrap());
    }

    #[test]
    fn int_from() {
        let i = Int::from(::std::i64::MIN);
        assert_eq!(i64::from(&i), ::std::i64::MIN);

        let i = Int::from(::std::i32::MIN);
        assert_eq!(i32::from(&i), ::std::i32::MIN);

        let i = Int::from(::std::i128::MIN);
        assert_eq!(i128::from(&i), ::std::i128::MIN);

        let i = Int::from(::std::u128::MAX);
        assert_eq!(u128::from(&i), ::std::u128::MAX);

        let i = Int::from(::std::usize::MAX);
        assert_eq!(usize::from(&i), ::std::usize::MAX);
    }

    #[test]
    fn step() {
        use std::iter::Step;

        let a = Int::from(897235032);
        let b = Int::from(98345);

        assert_eq!(Int::steps_between(&a, &b), Some(897136687));
        assert_eq!(Int::steps_between(&a, &b), Int::steps_between(&b, &a));
        assert_eq!(
            Int::forward_checked(a.clone(), 232184),
            Some(Int::from(897467216))
        );
        assert_eq!(
            Int::backward_checked(a.clone(), 897467216),
            Some(Int::from(-232184))
        );
    }

    const RAND_ITER: usize = 1000;

    #[test]
    fn div_rand() {
        let mut rng = rand::thread_rng();
        for _ in 0..RAND_ITER {
            let x = rng.gen_int(640);
            let y = rng.gen_int(320);

            let (q, r) = x.divmod(&y);
            let val = (q * &y) + r;

            assert_mp_eq!(val, x);
        }
    }

    #[test]
    fn sqr_rand() {
        let mut rng = rand::thread_rng();
        for _ in 0..RAND_ITER {
            let x = rng.gen_int(640);

            let xs = x.square();
            let xm = &x * &x;

            assert_mp_eq!(xm, xs);
        }
    }

    #[test]
    fn shl_rand() {
        let mut rng = rand::thread_rng();
        for _ in 0..RAND_ITER {
            let x = rng.gen_int(640);

            let shift_1 = &x << 1;
            let mul_2 = &x * 2;

            assert_mp_eq!(shift_1, mul_2);

            let shift_3 = &x << 3;
            let mul_8 = &x * 8;

            assert_mp_eq!(shift_3, mul_8);
        }
    }

    #[test]
    fn shl_rand_large() {
        let mut rng = rand::thread_rng();
        for _ in 0..RAND_ITER {
            let pow: usize = rng.gen_range(64, 8196);
            let mul_by = Int::from(2).pow(pow);

            let x = rng.gen_int(640);

            let shift = &x << pow;
            let mul = x * mul_by;

            assert_mp_eq!(shift, mul);
        }
    }

    #[test]
    fn shr_rand() {
        let mut rng = rand::thread_rng();
        for _ in 0..RAND_ITER {
            let pow: usize = rng.gen_range(64, 8196);
            let x = rng.gen_int(640);

            let shift_up = &x << pow;
            let shift_down = shift_up >> pow;

            assert_mp_eq!(shift_down, x);
        }
    }

    #[test]
    fn bitand_rand() {
        let mut rng = rand::thread_rng();
        for _ in 0..RAND_ITER {
            let x = rng.gen_int(640);
            let y = rng.gen_int(640);

            let _ = x & y;
        }
    }

    #[test]
    fn hash_rand() {
        let mut rng = rand::thread_rng();
        for _ in 0..RAND_ITER {
            let x1 = rng.gen_int(640);
            let x2 = x1.clone();

            assert_eq!(x1, x2);

            let x1_hash = {
                let mut hasher = std::collections::hash_map::DefaultHasher::new();
                x1.hash(&mut hasher);
                hasher.finish()
            };

            let x2_hash = {
                let mut hasher = std::collections::hash_map::DefaultHasher::new();
                x2.hash(&mut hasher);
                hasher.finish()
            };

            assert_eq!(x1_hash, x2_hash);
        }
    }

    #[test]
    #[should_panic]
    fn gen_uint_with_zero_bits() {
        let mut rng = rand::thread_rng();
        rng.gen_uint(0);
    }

    #[test]
    #[should_panic]
    fn gen_int_with_zero_bits() {
        let mut rng = rand::thread_rng();
        rng.gen_int(0);
    }

    #[test]
    #[should_panic]
    fn gen_uint_below_zero_or_negative() {
        let mut rng = rand::thread_rng();

        let i = Int::from(0);
        rng.gen_uint_below(&i);

        let j = Int::from(-1);
        rng.gen_uint_below(&j);
    }

    #[test]
    #[should_panic]
    fn gen_int_range_zero() {
        let mut rng = rand::thread_rng();

        let b = Int::from(123);
        rng.gen_int_range(&b, &b);
    }

    #[test]
    #[should_panic]
    fn gen_int_range_negative() {
        let mut rng = rand::thread_rng();

        let lb = Int::from(123);
        let ub = Int::from(321);

        rng.gen_int_range(&ub, &lb);
    }

    #[test]
    fn gen_int_range() {
        let mut rng = rand::thread_rng();

        for _ in 0..10 {
            let i = rng.gen_int_range(&Int::from(236), &Int::from(237));
            assert_eq!(i, Int::from(236));
        }

        let l = Int::from(403469000 + 2352);
        let u = Int::from(403469000 + 3513);
        for _ in 0..1000 {
            let n: Int = rng.gen_uint_below(&u);
            assert!(n < u);

            let n: Int = rng.gen_int_range(&l, &u);
            assert!(n >= l);
            assert!(n < u);
        }
    }

    #[test]
    fn gen_uint_below_all_ones() {
        static N: &'static str = "000001FFFFFFFFFFFFFFFFFFFFFFFFFFF\
                                  FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF\
                                  FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF";

        let mut rng = rand::thread_rng();

        let bound = Int::from_str_radix(N, 16).unwrap();

        for _ in 0..10 {
            let n: Int = rng.gen_uint_below(&bound);
            assert!(n < bound);
        }
    }

    #[test]
    fn add_larger_limb() {
        let a = Int::from(-14);
        let b = Limb(15 as BaseInt);
        assert_eq!(a + b, Int::one());
    }

    #[test]
    fn gcd() {
        let cases = [
            ("3", "0","3"), // special
            ("0", "3", "3"),
            ("0", "0", "0"),
            ("13", "13", "13"),
            ("37", "600", "1"), // prime numbers
            ("2567", "997", "1"),
            ("624129", "2061517", "18913"), // normal
            ("18446744073709551616", "18446744073709551616", "18446744073709551616"),
            ("184467440737095516201234", "493882992939324", "6"),
            ("493882992939324", "184467440737095516201234", "6"),
            ("18446744073709551620", "18446744073709551615", "5"),
            ("-9223372036854775808", "-9223372036854775808", "9223372036854775808"),
            ("-9223372036854775811", "-9223372036854775808", "1"),
            ("-23465475685232342344366756745345", "-23423545489322535345", "5"),
            ("-23423545489322535345", "-23465475685232342344366756745345", "5"),
            ("-170141183460469231731687303715884105728", "-170141183460469231731687303715884105729", "1"),
            ("-170141183460469231731687303715884105731", "-170141183460469231731687303715884105728", "1"),
            ("170141183460469231731687303715884105731234234363462345234345547232443500000000000000000000000", "17014118346046923173168730371588410572836362453452345000000000000000000", "5000000000000000000")
        ];

        for &(l, r, a) in cases.iter() {
            let l: Int = l.parse().unwrap();
            let r: Int = r.parse().unwrap();
            let a: Int = a.parse().unwrap();

            let val = l.gcd(&r);
            assert_mp_eq!(val, a);
        }
    }

    #[test]
    fn lcm() {
        let cases = [
            ("1", "0", "0"),
            ("0", "1", "0"),
            ("1", "1", "1"),
            ("-1", "0", "0"),
            ("0", "-1", "0"),
            ("-1", "-1", "1"),
            ("8", "9", "72"),
            ("11", "5", "55"),
            ("99", "17", "1683"),
            (
                "18446744073709551616",
                "18446744073709551616",
                "18446744073709551616",
            ),
            (
                "18446744073709551620",
                "18446744073709551615",
                "68056473384187692703742967930579373260",
            ),
            (
                "-9223372036854775808",
                "-9223372036854775808",
                "9223372036854775808",
            ),
            (
                "-9223372036854775811",
                "-9223372036854775808",
                "85070591730234615893513767968506380288",
            ),
            (
                "-92233720368547758112345",
                "-235777694355",
                "4349330786055998253486590232462495",
            ),
        ];

        for &(l, r, a) in cases.iter() {
            let l: Int = l.parse().unwrap();
            let r: Int = r.parse().unwrap();
            let a: Int = a.parse().unwrap();

            let val = l.lcm(&r);
            assert_mp_eq!(val.clone(), a.clone());
        }
    }

    fn bench_add(b: &mut Bencher, xs: usize, ys: usize) {
        let mut rng = rand::thread_rng();

        let x = rng.gen_int(xs * Limb::BITS);
        let y = rng.gen_int(ys * Limb::BITS);

        b.iter(|| {
            let z = &x + &y;
            test::black_box(z);
        });
    }

    #[bench]
    fn bench_add_1_1(b: &mut Bencher) {
        bench_add(b, 1, 1);
    }

    #[bench]
    fn bench_add_10_10(b: &mut Bencher) {
        bench_add(b, 10, 10);
    }

    #[bench]
    fn bench_add_100_100(b: &mut Bencher) {
        bench_add(b, 100, 100);
    }

    #[bench]
    fn bench_add_1000_1000(b: &mut Bencher) {
        bench_add(b, 1000, 1000);
    }

    #[bench]
    fn bench_add_1000_10(b: &mut Bencher) {
        bench_add(b, 1000, 10);
    }

    fn bench_mul(b: &mut Bencher, xs: usize, ys: usize) {
        let mut rng = rand::thread_rng();

        let x = rng.gen_int(xs * Limb::BITS);
        let y = rng.gen_int(ys * Limb::BITS);

        b.iter(|| {
            let z = &x * &y;
            test::black_box(z);
        });
    }

    fn bench_pow(b: &mut Bencher, xs: usize, ys: usize) {
        let mut rng = rand::thread_rng();

        let x = rng.gen_int(xs * Limb::BITS);
        let y: usize = rng.gen_range(0, ys);

        b.iter(|| {
            let z = &x.pow(y);
            test::black_box(z);
        });
    }

    fn bench_pow_mod(b: &mut Bencher, gs: usize, es: usize, ms: usize) {
        let mut rng = rand::thread_rng();

        let g = rng.gen_int(gs * Limb::BITS);
        let e = rng.gen_uint(es * Limb::BITS);
        let m = rng.gen_uint(ms * Limb::BITS);

        b.iter(|| {
            let z = g.pow_mod(&e, &m);
            test::black_box(z);
        });
    }

    #[bench]
    fn bench_mul_1_1(b: &mut Bencher) {
        bench_mul(b, 1, 1);
    }

    #[bench]
    fn bench_mul_10_10(b: &mut Bencher) {
        bench_mul(b, 10, 10);
    }

    #[bench]
    fn bench_mul_2_20(b: &mut Bencher) {
        bench_mul(b, 2, 20);
    }

    #[bench]
    fn bench_mul_50_50(b: &mut Bencher) {
        bench_mul(b, 50, 50);
    }

    #[bench]
    fn bench_mul_5_50(b: &mut Bencher) {
        bench_mul(b, 5, 50);
    }

    #[bench]
    fn bench_mul_250_250(b: &mut Bencher) {
        bench_mul(b, 250, 250);
    }

    #[bench]
    fn bench_mul_1000_1000(b: &mut Bencher) {
        bench_mul(b, 1000, 1000);
    }

    #[bench]
    fn bench_mul_50_1500(b: &mut Bencher) {
        bench_mul(b, 50, 1500);
    }

    fn bench_sqr(b: &mut Bencher, xs: usize) {
        let mut rng = rand::thread_rng();

        let x = rng.gen_int(xs * Limb::BITS);

        b.iter(|| {
            let z = x.square();
            test::black_box(z);
        });
    }

    #[bench]
    fn bench_sqr_1(b: &mut Bencher) {
        bench_sqr(b, 1);
    }

    #[bench]
    fn bench_sqr_10(b: &mut Bencher) {
        bench_sqr(b, 10);
    }

    #[bench]
    fn bench_sqr_50(b: &mut Bencher) {
        bench_sqr(b, 50);
    }

    #[bench]
    fn bench_sqr_250(b: &mut Bencher) {
        bench_sqr(b, 250);
    }

    #[bench]
    fn bench_sqr_1000(b: &mut Bencher) {
        bench_sqr(b, 1000);
    }

    #[bench]
    fn bench_pow_1_1(b: &mut Bencher) {
        bench_pow(b, 1, 1);
    }

    #[bench]
    fn bench_pow_10_10(b: &mut Bencher) {
        bench_pow(b, 10, 10);
    }

    #[bench]
    fn bench_pow_2_20(b: &mut Bencher) {
        bench_pow(b, 2, 20);
    }

    #[bench]
    fn bench_pow_50_50(b: &mut Bencher) {
        bench_pow(b, 50, 50);
    }

    #[bench]
    fn bench_pow_5_50(b: &mut Bencher) {
        bench_pow(b, 5, 50);
    }

    #[bench]
    fn bench_pow_250_250(b: &mut Bencher) {
        bench_pow(b, 250, 250);
    }

    #[bench]
    fn bench_pow_50_1500(b: &mut Bencher) {
        bench_pow(b, 50, 1500);
    }

    #[bench]
    fn bench_pow_mod_50_50_50(b: &mut Bencher) {
        bench_pow_mod(b, 50, 50, 50);
    }

    #[bench]
    fn bench_factorial_100(b: &mut Bencher) {
        b.iter(|| {
            let mut i = Int::from(1);

            for j in 2..100 {
                i = i * j;
            }

            i = i * 100;
            test::black_box(i);
        });
    }

    #[bench]
    fn bench_factorial_1000(b: &mut Bencher) {
        b.iter(|| {
            let mut i = Int::from(1);

            for j in 2..1000 {
                i = i * j;
            }

            i = i * 1000;

            test::black_box(i);
        });
    }

    fn bench_div(b: &mut Bencher, xs: usize, ys: usize) {
        let mut rng = rand::thread_rng();

        let x = rng.gen_int(xs * Limb::BITS);
        let y = rng.gen_int(ys * Limb::BITS);

        b.iter(|| {
            let z = &x / &y;
            test::black_box(z);
        });
    }

    #[bench]
    fn bench_div_1_1(b: &mut Bencher) {
        bench_div(b, 1, 1);
    }

    #[bench]
    fn bench_div_10_10(b: &mut Bencher) {
        bench_div(b, 10, 10);
    }

    #[bench]
    fn bench_div_20_2(b: &mut Bencher) {
        bench_div(b, 20, 2);
    }

    #[bench]
    fn bench_div_50_50(b: &mut Bencher) {
        bench_div(b, 50, 50);
    }

    #[bench]
    fn bench_div_50_5(b: &mut Bencher) {
        bench_div(b, 50, 5);
    }

    #[bench]
    fn bench_div_250_250(b: &mut Bencher) {
        bench_div(b, 250, 250);
    }

    #[bench]
    fn bench_div_1000_1000(b: &mut Bencher) {
        bench_div(b, 1000, 1000);
    }

    fn bench_gcd(b: &mut Bencher, xs: usize, ys: usize) {
        let mut rng = rand::thread_rng();

        let x = rng.gen_int(xs * Limb::BITS);
        let y = rng.gen_int(ys * Limb::BITS);

        b.iter(|| {
            let z = x.gcd(&y);
            test::black_box(z);
        });
    }

    #[bench]
    fn bench_gcd_1_1(b: &mut Bencher) {
        bench_gcd(b, 1, 1);
    }

    #[bench]
    fn bench_gcd_10_10(b: &mut Bencher) {
        bench_gcd(b, 10, 10);
    }

    #[bench]
    fn bench_gcd_20_2(b: &mut Bencher) {
        bench_gcd(b, 20, 2);
    }

    #[bench]
    fn bench_gcd_50_50(b: &mut Bencher) {
        bench_gcd(b, 50, 50);
    }

    #[bench]
    fn bench_gcd_50_5(b: &mut Bencher) {
        bench_gcd(b, 50, 5);
    }

    #[bench]
    fn bench_gcd_250_150(b: &mut Bencher) {
        bench_gcd(b, 250, 150);
    }

    #[bench]
    fn bench_gcd_100_100(b: &mut Bencher) {
        bench_gcd(b, 100, 100);
    }

    #[bench]
    fn bench_gcd_100_10(b: &mut Bencher) {
        bench_gcd(b, 100, 10);
    }

    #[bench]
    fn bench_gcd_100_50(b: &mut Bencher) {
        bench_gcd(b, 100, 50);
    }

    #[bench]
    fn bench_rng_all_ones(b: &mut Bencher) {
        let mut rng = rand::thread_rng();

        let num_bits: usize = rng.gen_range(512, 1024);

        let mut bound = Int::from(1) << num_bits;
        bound -= 1;

        b.iter(|| {
            let n = rng.gen_uint_below(&bound);
            test::black_box(n);
        });
    }
}