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
// Copyright © 2024 Mikhail Hogrefe
//
// Uses code adopted from the GNU MP Library.
//
// `mpn_dcpi1_divappr_q`, `mpn_dcpi1_divappr_q_n`, `mpn_div_q`, `mpn_mu_divappr_q`,
// `mpn_mu_divappr_q_choose_in`, `mpn_mu_divappr_q_itch`, `mpn_preinv_mu_divappr_q`,
// `mpn_sbpi1_div_q`, and `mpn_sbpi1_divappr_q` contributed to the GNU project by Torbjörn
// Granlund.
//
// `mpn_dcpi1_div_q`, `mpn_mu_div_q`, and `mpn_mu_div_q_itch` contributed to the GNU project by
// Torbjörn Granlund and Marco Bodrato.
//
// `mpn_div_qr_1` contributed to the GNU project by Niels Möller and Torbjörn Granlund.
//
// Copyright © 1991-2018 Free Software Foundation, Inc.
//
// This file is part of Malachite.
//
// Malachite is free software: you can redistribute it and/or modify it under the terms of the GNU
// Lesser General Public License (LGPL) as published by the Free Software Foundation; either version
// 3 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>.
use crate::natural::arithmetic::add::{
limbs_add_limb_to_out, limbs_add_same_length_to_out, limbs_slice_add_limb_in_place,
limbs_slice_add_same_length_in_place_left,
};
use crate::natural::arithmetic::div_mod::{
div_mod_by_preinversion, limbs_div_barrett_large_product, limbs_div_mod_by_two_limb_normalized,
limbs_div_mod_divide_and_conquer_helper, limbs_div_mod_schoolbook,
limbs_div_mod_three_limb_by_two_limb, limbs_invert_approx, limbs_invert_approx_scratch_len,
limbs_invert_limb, limbs_two_limb_inverse_helper, MUL_TO_MULMOD_BNM1_FOR_2NXN_THRESHOLD,
MUPI_DIV_QR_THRESHOLD,
};
use crate::natural::arithmetic::mul::mul_mod::{
limbs_mul_mod_base_pow_n_minus_1_next_size, limbs_mul_mod_base_pow_n_minus_1_scratch_len,
};
use crate::natural::arithmetic::mul::{
limbs_mul_greater_to_out, limbs_mul_greater_to_out_scratch_len, limbs_mul_same_length_to_out,
limbs_mul_same_length_to_out_scratch_len, limbs_mul_to_out, limbs_mul_to_out_scratch_len,
};
use crate::natural::arithmetic::shl::{limbs_shl_to_out, limbs_slice_shl_in_place};
use crate::natural::arithmetic::sub::{
limbs_sub_limb_in_place, limbs_sub_limb_to_out, limbs_sub_same_length_in_place_left,
limbs_sub_same_length_in_place_right, limbs_sub_same_length_to_out,
limbs_sub_same_length_with_borrow_in_in_place_right,
};
use crate::natural::arithmetic::sub_mul::limbs_sub_mul_limb_same_length_in_place_left;
use crate::natural::comparison::cmp::limbs_cmp_same_length;
use crate::natural::InnerNatural::{Large, Small};
use crate::natural::Natural;
use crate::platform::{
DoubleLimb, Limb, DC_DIVAPPR_Q_THRESHOLD, DC_DIV_QR_THRESHOLD, FUDGE, MU_DIVAPPR_Q_THRESHOLD,
};
use alloc::boxed::Box;
use alloc::vec::Vec;
use core::cmp::Ordering::*;
use core::iter::once;
use core::mem::swap;
use core::ops::{Div, DivAssign};
use malachite_base::fail_on_untested_path;
#[cfg(feature = "test_build")]
use malachite_base::num::arithmetic::traits::DivRem;
use malachite_base::num::arithmetic::traits::{
CheckedDiv, WrappingAddAssign, WrappingMulAssign, WrappingSubAssign, XMulYToZZ, XXAddYYToZZ,
};
use malachite_base::num::basic::integers::PrimitiveInt;
use malachite_base::num::basic::traits::{One, Zero};
use malachite_base::num::conversion::traits::{ExactFrom, JoinHalves, SplitInHalf};
use malachite_base::num::logic::traits::LeadingZeros;
use malachite_base::slices::{slice_move_left, slice_set_zero};
// Divide an number by a divisor of B - 1, where B is the limb base.
//
// # Worst-case complexity
// $T(n) = O(n)$
//
// $M(n) = O(1)$
//
// where $T$ is time, $M$ is additional memory, and $n$ is `ns.len()`.
//
// # Panics
// Panics if `out` is shorter than `ns`.
//
// This is equivalent to `mpn_bdiv_dbm1c` from `mpn/generic/bdiv_dbm1c.c`, GMP 6.2.1.
pub_crate_test! {limbs_div_divisor_of_limb_max_with_carry_to_out(
out: &mut [Limb],
ns: &[Limb],
d: Limb,
mut carry: Limb,
) -> Limb {
assert!(out.len() >= ns.len());
let d = DoubleLimb::from(d);
for (q, &n) in out.iter_mut().zip(ns.iter()) {
let (hi, lo) = (DoubleLimb::from(n) * d).split_in_half();
let inner_carry = carry < lo;
carry.wrapping_sub_assign(lo);
*q = carry;
carry.wrapping_sub_assign(hi);
if inner_carry {
carry.wrapping_sub_assign(1);
}
}
carry
}}
// Divide an number by a divisor of B - 1, where B is the limb base.
//
// # Worst-case complexity
// $T(n) = O(n)$
//
// $M(n) = O(1)$
//
// where $T$ is time, $M$ is additional memory, and $n$ is `ns.len()`.
//
// This is equivalent to `mpn_bdiv_dbm1c` from `mpn/generic/bdiv_dbm1c.c`, GMP 6.2.1, where `qp ==
// ap`.
pub_crate_test! {limbs_div_divisor_of_limb_max_with_carry_in_place(
ns: &mut [Limb],
d: Limb,
mut carry: Limb,
) -> Limb {
let d = DoubleLimb::from(d);
for n in &mut *ns {
let (hi, lo) = (DoubleLimb::from(*n) * d).split_in_half();
let inner_carry = carry < lo;
carry.wrapping_sub_assign(lo);
*n = carry;
carry.wrapping_sub_assign(hi);
if inner_carry {
carry.wrapping_sub_assign(1);
}
}
carry
}}
// # Worst-case complexity
// Constant time and additional memory.
//
// This is equivalent to `udiv_qrnnd_preinv` from `gmp-impl.h`, GMP 6.2.1, but not computing the
// remainder.
pub_test! {div_by_preinversion(n_high: Limb, n_low: Limb, d: Limb, d_inv: Limb) -> Limb {
let (mut q_high, q_low) = (DoubleLimb::from(n_high) * DoubleLimb::from(d_inv))
.wrapping_add(DoubleLimb::join_halves(n_high.wrapping_add(1), n_low))
.split_in_half();
let mut r = n_low.wrapping_sub(q_high.wrapping_mul(d));
if r > q_low {
q_high.wrapping_sub_assign(1);
r.wrapping_add_assign(d);
}
if r >= d {
q_high.wrapping_add_assign(1);
}
q_high
}}
// Interpreting a slice of `Limb`s as the limbs (in ascending order) of a `Natural`, returns the
// quotient limbs of the `Natural` divided by a `Limb`. The divisor limb cannot be zero and the limb
// slice must have at least two elements.
//
// # Worst-case complexity
// $T(n) = O(n)$
//
// $M(n) = O(n)$
//
// where $T$ is time, $M$ is additional memory, and $n$ is `ns.len()`.
//
// # Panics
// Panics if the length of `ns` is less than 2 or if `d` is zero.
//
// This is equivalent to `mpn_div_qr_1` from `mpn/generic/div_qr_1.c`, GMP 6.2.1, where the quotient
// is returned, but not computing the remainder.
pub_test! {limbs_div_limb(ns: &[Limb], d: Limb) -> Vec<Limb> {
let mut qs = vec![0; ns.len()];
limbs_div_limb_to_out(&mut qs, ns, d);
qs
}}
// Interpreting a slice of `Limb`s as the limbs (in ascending order) of a `Natural`, writes the
// limbs of the quotient of the `Natural` and a `Limb` to an output slice. The output slice must be
// at least as long as the input slice. The divisor limb cannot be zero and the input limb slice
// must have at least two elements.
//
// # Worst-case complexity
// $T(n) = O(n)$
//
// $M(n) = O(1)$
//
// where $T$ is time, $M$ is additional memory, and $n$ is `ns.len()`.
//
// # Panics
// Panics if `out` is shorter than `ns`, the length of `ns` is less than 2, or if `d` is zero.
//
// This is equivalent to `mpn_divrem_1` from `mpn/generic/divrem_1.c`, GMP 6.2.1, where `qxn == 0`.
// and `un > 1`, but not computing the remainder.
pub_crate_test! {limbs_div_limb_to_out(out: &mut [Limb], ns: &[Limb], d: Limb) {
assert_ne!(d, 0);
let len = ns.len();
assert!(len > 1);
let out = &mut out[..len];
let bits = LeadingZeros::leading_zeros(d);
if bits == 0 {
// High quotient limb is 0 or 1, skip a divide step.
let (r, ns_init) = ns.split_last().unwrap();
let mut r = *r;
let (out_last, out_init) = out.split_last_mut().unwrap();
let adjust = r >= d;
if adjust {
r -= d;
}
*out_last = Limb::from(adjust);
// Multiply-by-inverse, divisor already normalized.
let d_inv = limbs_invert_limb(d);
for (out_q, &n) in out_init.iter_mut().zip(ns_init.iter()).rev() {
(*out_q, r) = div_mod_by_preinversion(r, n, d, d_inv);
}
} else {
// Skip a division if high < divisor (high quotient 0). Testing here before normalizing will
// still skip as often as possible.
let (ns_last, ns_init) = ns.split_last().unwrap();
let (ns, mut r) = if *ns_last < d {
*out.last_mut().unwrap() = 0;
(ns_init, *ns_last)
} else {
(ns, 0)
};
let d = d << bits;
r <<= bits;
let d_inv = limbs_invert_limb(d);
let (previous_n, ns_init) = ns.split_last().unwrap();
let mut previous_n = *previous_n;
let cobits = Limb::WIDTH - bits;
r |= previous_n >> cobits;
let (out_first, out_tail) = out.split_first_mut().unwrap();
for (out_q, &n) in out_tail.iter_mut().zip(ns_init.iter()).rev() {
let shifted_n = (previous_n << bits) | (n >> cobits);
(*out_q, r) = div_mod_by_preinversion(r, shifted_n, d, d_inv);
previous_n = n;
}
*out_first = div_by_preinversion(r, previous_n << bits, d, d_inv);
}
}}
// Interpreting a slice of `Limb`s as the limbs (in ascending order) of a `Natural`, writes the
// limbs of the quotient of the `Natural` and a `Limb` to the input slice. The divisor limb cannot
// be zero and the input limb slice must have at least two elements.
//
// # Worst-case complexity
// $T(n) = O(n)$
//
// $M(n) = O(1)$
//
// where $T$ is time, $M$ is additional memory, and $n$ is `ns.len()`.
//
// # Panics
// Panics if the length of `ns` is less than 2 or if `d` is zero.
//
// This is equivalent to `mpn_divrem_1` from `mpn/generic/divrem_1.c`, GMP 6.2.1, where `qp == up`,
// `qxn == 0`, and `un > 1`, but not computing the remainder.
pub_test! {limbs_div_limb_in_place(ns: &mut [Limb], d: Limb) {
assert_ne!(d, 0);
let len = ns.len();
assert!(len > 1);
let bits = LeadingZeros::leading_zeros(d);
let (ns_last, ns_init) = ns.split_last_mut().unwrap();
if bits == 0 {
// High quotient limb is 0 or 1, skip a divide step.
let mut r = *ns_last;
let adjust = r >= d;
if adjust {
r -= d;
}
*ns_last = Limb::from(adjust);
// Multiply-by-inverse, divisor already normalized.
let d_inv = limbs_invert_limb(d);
for n in ns_init.iter_mut().rev() {
(*n, r) = div_mod_by_preinversion(r, *n, d, d_inv);
}
} else {
// Skip a division if high < divisor (high quotient 0). Testing here before normalizing will
// still skip as often as possible.
let (ns, mut r) = if *ns_last < d {
let r = *ns_last;
*ns_last = 0;
(ns_init, r)
} else {
(ns, 0)
};
let d = d << bits;
r <<= bits;
let d_inv = limbs_invert_limb(d);
let last_index = ns.len() - 1;
let mut previous_n = ns[last_index];
let cobits = Limb::WIDTH - bits;
r |= previous_n >> cobits;
for i in (0..last_index).rev() {
let n = ns[i];
let shifted_n = (previous_n << bits) | (n >> cobits);
(ns[i + 1], r) = div_mod_by_preinversion(r, shifted_n, d, d_inv);
previous_n = n;
}
ns[0] = div_by_preinversion(r, previous_n << bits, d, d_inv);
}
}}
// Schoolbook division using the Möller-Granlund 3/2 division algorithm.
//
// Divides `ns` by `ds` and writes the `ns.len()` - `ds.len()` least-significant quotient limbs to
// `qs`. Returns the most significant limb of the quotient; `true` means 1 and `false` means 0. `ds`
// must have length greater than 2, `ns` must be at least as long as `ds`, and the most significant
// bit of `ds` must be set. `d_inv` should be the result of `limbs_two_limb_inverse_helper` applied
// to the two highest limbs of the denominator.
//
// # Worst-case complexity
// $T(n) = O(n^2)$
//
// $M(n) = O(n)$
//
// where $T$ is time, $M$ is additional memory, and $n$ is `ns.len()`.
//
// # Panics
// Panics if `ds` has length smaller than 3, `ns` is shorter than `ds`, `qs` has length less than
// `ns.len()` - `ds.len()`, or the last limb of `ds` does not have its highest bit set.
//
// This is equivalent to `mpn_sbpi1_div_q` from `mpn/generic/sbpi1_div_q.c`, GMP 6.2.1.
pub_test! {limbs_div_schoolbook(
qs: &mut [Limb],
ns: &mut [Limb],
ds: &[Limb],
d_inv: Limb
) -> bool {
let n_len = ns.len();
let d_len = ds.len();
assert!(d_len > 2);
assert!(n_len >= d_len);
let d_len_m_1 = d_len - 1;
let d_1 = ds[d_len_m_1];
assert!(d_1.get_highest_bit());
let q_len = n_len - d_len;
let ds_s = if q_len < d_len_m_1 {
&ds[d_len_m_1 - q_len..]
} else {
ds
};
let d_len_s = ds_s.len(); // d_len or n_len - d_len + 1
let d_sum = d_len + d_len_s; // 2 * d_len or n_len + 1
let d_diff = d_len - d_len_s; // 0 or 2 * d_len - n_len - 1
let ns_hi = &mut ns[n_len - d_len_s..];
let highest_q = limbs_cmp_same_length(ns_hi, ds_s) >= Equal;
if highest_q {
limbs_sub_same_length_in_place_left(ns_hi, ds_s);
}
// Offset d_len by 2 for main division loops, saving two iterations in
// limbs_sub_mul_limb_same_length_in_place_left.
let d_len_m_2 = d_len - 2;
let d_len_s_m_1 = d_len_s - 1;
let d_len_s_m_2 = d_len_s.wrapping_sub(2); // only used when d_len_s >= 2
let d_2 = ds[d_len_m_2];
let mut n_1 = ns[n_len - 1];
for i in (d_sum - 1..n_len).rev() {
let ns = &mut ns[i - d_len_s..i];
let mut q;
if n_1 == d_1 && ns[d_len_s_m_1] == d_2 {
q = Limb::MAX;
limbs_sub_mul_limb_same_length_in_place_left(ns, ds_s, q);
n_1 = ns[d_len_s_m_1]; // update n_1; last loop's value will now be invalid
} else {
let n;
(q, n) = limbs_div_mod_three_limb_by_two_limb(
n_1,
ns[d_len_s_m_1],
ns[d_len_s - 2],
d_1,
d_2,
d_inv,
);
let mut n_0;
(n_1, n_0) = n.split_in_half();
let carry = limbs_sub_mul_limb_same_length_in_place_left(
&mut ns[..d_len_s - 2],
&ds_s[..d_len_s - 2],
q,
);
let carry_2 = n_0 < carry;
n_0.wrapping_sub_assign(carry);
let carry = carry_2 && n_1 == 0;
if carry_2 {
n_1.wrapping_sub_assign(1);
}
ns[d_len_s_m_2] = n_0;
if carry {
n_1.wrapping_add_assign(d_1);
if limbs_slice_add_same_length_in_place_left(
&mut ns[..d_len_s_m_1],
&ds_s[..d_len_s_m_1],
) {
n_1.wrapping_add_assign(1);
}
q.wrapping_sub_assign(1);
}
}
qs[i - d_len] = q;
}
let mut flag = true;
let offset = if d_len_s >= 2 {
let mut ds_suffix = &ds[d_diff..];
for i in (1..d_len_s_m_1).rev() {
let ns = &mut ns[d_len_m_2..d_len + i];
let mut q;
if !flag || n_1 >= d_1 {
q = Limb::MAX;
let carry = limbs_sub_mul_limb_same_length_in_place_left(ns, ds_suffix, q);
if n_1 != carry {
if flag && n_1 < carry {
q.wrapping_sub_assign(1);
limbs_slice_add_same_length_in_place_left(ns, ds_suffix);
} else {
flag = false;
}
}
n_1 = ns[i + 1];
} else {
let n;
(q, n) =
limbs_div_mod_three_limb_by_two_limb(n_1, ns[i + 1], ns[i], d_1, d_2, d_inv);
let mut n_0;
(n_1, n_0) = n.split_in_half();
let carry = limbs_sub_mul_limb_same_length_in_place_left(
&mut ns[..i],
&ds_suffix[..ds_suffix.len() - 2],
q,
);
let carry_2 = n_0 < carry;
n_0.wrapping_sub_assign(carry);
let carry = carry_2 && n_1 == 0;
if carry_2 {
n_1.wrapping_sub_assign(1);
}
ns[i] = n_0;
if carry {
n_1.wrapping_add_assign(d_1);
if limbs_slice_add_same_length_in_place_left(
&mut ns[..i + 1],
&ds_suffix[..ds_suffix.len() - 1],
) {
n_1.wrapping_add_assign(1);
}
q.wrapping_sub_assign(1);
}
}
qs[i] = q;
ds_suffix = &ds_suffix[1..];
}
let mut q;
let ns = &mut ns[d_len_m_2..d_len];
if !flag || n_1 >= d_1 {
q = Limb::MAX;
let ds_hi = &ds[d_len_m_2..];
let carry = limbs_sub_mul_limb_same_length_in_place_left(ns, &ds_hi[..2], q);
if n_1 != carry {
if flag && n_1 < carry {
q.wrapping_sub_assign(1);
(ns[1], ns[0]) = Limb::xx_add_yy_to_zz(ns[1], ns[0], d_2, ds_hi[0]);
} else {
flag = false;
}
}
n_1 = ns[1];
} else {
let new_n;
(q, new_n) = limbs_div_mod_three_limb_by_two_limb(n_1, ns[1], ns[0], d_1, d_2, d_inv);
(n_1, ns[0]) = new_n.split_in_half();
ns[1] = n_1;
}
qs[0] = q;
d_len
} else {
d_sum - 1
};
let (ns_last, ns_init) = ns[..offset].split_last_mut().unwrap();
assert_eq!(*ns_last, n_1);
if flag && n_1 < Limb::exact_from(d_len) {
let qs = &mut qs[offset - d_len..];
let qs = &mut qs[..q_len];
// The quotient may be too large if the remainder is small. Recompute for above ignored
// operand parts, until the remainder spills. Compensate for triangularization.
let ns = ns_init;
{
let (ns_last, ns_init) = ns.split_last_mut().unwrap();
for i in 3..d_len_s + 1 {
let q = qs[d_len_s - i];
let carry = limbs_sub_mul_limb_same_length_in_place_left(
&mut ns_init[offset - i..],
&ds_s[..i - 2],
q,
);
if *ns_last < carry {
if n_1 == 0 {
assert!(!limbs_sub_limb_in_place(qs, 1));
return highest_q;
}
n_1 -= 1;
}
ns_last.wrapping_sub_assign(carry);
}
}
if d_diff != 0 {
// Compensate for ignored dividend and divisor tails.
if highest_q {
let mut carry =
limbs_sub_same_length_in_place_left(&mut ns[q_len..d_len_m_1], &ds[..d_diff]);
if carry {
if n_1 == 0 {
if q_len != 0 {
carry = limbs_sub_limb_in_place(qs, 1);
}
assert!(highest_q || !carry);
return highest_q != carry;
}
n_1 -= 1;
}
}
if q_len == 0 {
return highest_q;
}
let ns = &mut ns[..d_len_m_1];
for i in (0..d_diff).rev() {
let (ns_lo, ns_hi) = ns[i..].split_at_mut(q_len);
if limbs_sub_limb_in_place(
ns_hi,
limbs_sub_mul_limb_same_length_in_place_left(ns_lo, qs, ds[i]),
) {
if n_1 == 0 {
limbs_sub_limb_in_place(qs, 1);
return highest_q;
}
n_1 -= 1;
}
}
}
}
highest_q
}}
// Recursive divide-and-conquer division.
//
// Divides `ns` by `ds` and writes the `ns.len()` - `ds.len()` least-significant quotient limbs to
// `qs`. Returns the most significant limb of the quotient; `true` means 1 and `false` means 0. `ds`
// must have length greater than 2, `ns` must be at least as long as `ds`, and the most significant
// bit of `ds` must be set. `d_inv` should be the result of `limbs_two_limb_inverse_helper` applied
// to the two highest limbs of the denominator.
//
// # Worst-case complexity
// $T(n) = O(n (\log n)^2 \log \log n)$
//
// $M(n) = O(n \log n)$
//
// where $T$ is time, $M$ is additional memory, and $n$ is `ns.len()`.
//
// # Panics
// Panics if `ds` has length smaller than 6, `ns` is shorter than or the same length as `ds`, `qs`
// has length less than `ns.len()` - `ds.len()`, or the last limb of `ds` does not have its highest
// bit set.
//
// This is equivalent to `mpn_dcpi1_div_q` from `mpn/generic/dcpi1_div_q.c`, GMP 6.2.1.
pub_test! {limbs_div_divide_and_conquer(
qs: &mut [Limb],
ns: &[Limb],
ds: &[Limb],
d_inv: Limb,
) -> bool {
let n_len = ns.len();
let d_len = ds.len();
assert!(d_len >= 6);
assert!(n_len - d_len >= 3);
let q_len = n_len - d_len;
assert!(ds[d_len - 1].get_highest_bit());
let qs = &mut qs[..q_len];
let mut scratch = Vec::with_capacity(n_len + 1);
scratch.push(1);
scratch.extend_from_slice(ns);
let mut scratch_2 = vec![0; q_len + 1];
let highest_q = limbs_div_divide_and_conquer_approx(&mut scratch_2, &mut scratch, ds, d_inv);
let (scratch_2_head, scratch_2_tail) = scratch_2.split_first_mut().unwrap();
if *scratch_2_head == 0 {
let mut mul_scratch = vec![0; limbs_mul_to_out_scratch_len(q_len, d_len)];
limbs_mul_to_out(&mut scratch, scratch_2_tail, ds, &mut mul_scratch);
let scratch_init = &mut scratch[..n_len];
// At most is wrong by one, no cycle.
if highest_q && limbs_slice_add_same_length_in_place_left(&mut scratch_init[q_len..], ds)
|| limbs_cmp_same_length(scratch_init, ns) == Greater
{
return if limbs_sub_limb_to_out(qs, scratch_2_tail, 1) {
assert!(highest_q);
false
} else {
highest_q
};
}
}
qs.copy_from_slice(scratch_2_tail);
highest_q
}}
// Divides `ns` by `ds` and writes the `ns.len()` - `ds.len()` least-significant quotient limbs to
// `qs`. Returns the most significant limb of the quotient; `true` means 1 and `false` means 0. `ds`
// must have length greater than 2, `ns` must be longer than `ds`, and the most significant bit of
// `ds` must be set.
//
// The idea of the algorithm used herein is to compute a smaller inverted value than used in the
// standard Barrett algorithm, and thus save time in the Newton iterations, and pay just a small
// price when using the inverted value for developing quotient bits. This algorithm was presented at
// ICMS 2006.
//
// # Worst-case complexity
// $T(n) = O(n \log n \log \log n)$
//
// $M(n) = O(n \log n)$
//
// where $T$ is time, $M$ is additional memory, and $n$ is `ns.len()`.
//
// This is equivalent to `mpn_mu_div_q` from `mpn/generic/mu_div_q.c`, GMP 6.2.1.
pub_test! {limbs_div_barrett(
qs: &mut [Limb],
ns: &[Limb],
ds: &[Limb],
scratch: &mut [Limb]
) -> bool {
let n_len = ns.len();
let d_len = ds.len();
assert!(n_len > d_len);
let q_len = n_len - d_len;
let qs = &mut qs[..q_len];
let q_len_plus_1 = q_len + 1;
let mut scratch_2 = vec![0; q_len_plus_1];
let highest_q;
if q_len >= d_len {
// ```
// |_______________________| dividend
// |________| divisor
// ```
let mut rs = Vec::with_capacity(n_len + 1);
rs.push(0);
rs.extend_from_slice(ns);
let rs_hi = &mut rs[q_len_plus_1..];
highest_q = limbs_cmp_same_length(rs_hi, ds) >= Equal;
if highest_q {
limbs_sub_same_length_in_place_left(rs_hi, ds);
}
if limbs_div_barrett_approx(&mut scratch_2, &rs, ds, scratch) {
// Since the partial remainder fed to limbs_div_barrett_approx_preinverted was
// canonically reduced, replace the returned value of B ^ (q_len - d_len) + epsilon by
// the largest possible value.
for s in &mut scratch_2 {
*s = Limb::MAX;
}
}
// The max error of limbs_div_barrett_approx is +4. If the low quotient limb is smaller than
// the max error, we cannot trust the quotient.
let (scratch_2_head, scratch_2_tail) = scratch_2.split_first().unwrap();
if *scratch_2_head > 4 {
qs.copy_from_slice(scratch_2_tail);
} else {
let rs = &mut rs[..n_len];
let mut mul_scratch =
vec![0; limbs_mul_greater_to_out_scratch_len(scratch_2_tail.len(), ds.len())];
limbs_mul_greater_to_out(rs, scratch_2_tail, ds, &mut mul_scratch);
if highest_q && limbs_slice_add_same_length_in_place_left(&mut rs[q_len..], ds)
|| limbs_cmp_same_length(rs, ns) == Greater
{
// At most is wrong by one, no cycle.
if limbs_sub_limb_to_out(qs, scratch_2_tail, 1) {
fail_on_untested_path("limbs_div_barrett, limbs_sub_greater_to_out 1");
assert!(highest_q);
return false;
}
} else {
qs.copy_from_slice(scratch_2_tail);
}
}
} else {
// ```
// |_______________________| dividend
// |________________| divisor
// ```
let ghost_n = n_len == (d_len << 1) - 1;
highest_q = limbs_div_barrett_approx_helper(
&mut scratch_2,
&ns[if ghost_n {
0
} else {
n_len - (q_len_plus_1 << 1)
}..],
ghost_n,
&ds[d_len - q_len_plus_1..],
scratch,
);
// The max error of limbs_div_barrett_approx is +4, but we get an additional error from the
// divisor truncation.
let (scratch_2_head, scratch_2_tail) = scratch_2.split_first().unwrap();
if *scratch_2_head > 6 {
qs.copy_from_slice(scratch_2_tail);
} else {
let mut rs = vec![0; n_len];
let mut mul_scratch =
vec![0; limbs_mul_greater_to_out_scratch_len(ds.len(), scratch_2_tail.len())];
limbs_mul_greater_to_out(&mut rs, ds, scratch_2_tail, &mut mul_scratch);
if highest_q && limbs_slice_add_same_length_in_place_left(&mut rs[q_len..], ds)
|| limbs_cmp_same_length(&rs, ns) == Greater
{
// At most is wrong by one, no cycle.
if limbs_sub_limb_to_out(qs, scratch_2_tail, 1) {
assert!(highest_q);
return false;
}
} else {
qs.copy_from_slice(scratch_2_tail);
}
}
}
highest_q
}}
// # Worst-case complexity
// Constant time and additional memory.
//
// The result is $O(n)$, where $n$ is `n_len`.
//
// This is equivalent to `mpn_mu_div_q_itch` from `mpn/generic/mu_div_q.c`, GMP 6.2.1, where `mua_k
// == 0`.
pub_test! {limbs_div_barrett_scratch_len(n_len: usize, d_len: usize) -> usize {
let q_len = n_len - d_len;
if q_len >= d_len {
limbs_div_barrett_approx_scratch_len(n_len + 1, d_len)
} else {
let q_len_plus_1 = q_len + 1;
limbs_div_barrett_approx_scratch_len(q_len_plus_1 << 1, q_len_plus_1)
}
}}
// Schoolbook division using the Möller-Granlund 3/2 division algorithm, returning approximate
// quotient.
//
// Divides `ns` by `ds` and writes the `ns.len()` - `ds.len()` least-significant quotient limbs to
// `qs`. Returns the most significant limb of the quotient; `true` means 1 and `false` means 0. The
// quotient is either correct, or one too large. `ds` must have length greater than 2, `ns` must be
// at least as long as `ds`, and the most significant bit of `ds` must be set. `d_inv` should be the
// result of `limbs_two_limb_inverse_helper` applied to the two highest limbs of the denominator.
//
// # Worst-case complexity
// $T(n) = O(n^2)$
//
// $M(n) = O(1)$
//
// where $T$ is time, $M$ is additional memory, and $n$ is `ns.len()`.
//
// # Panics
// Panics if `ds` has length smaller than 3, `ns` is shorter than `ds`, `qs` has length less than
// `ns.len()` - `ds.len()`, or the last limb of `ds` does not have its highest bit set.
//
// This is equivalent to `mpn_sbpi1_divappr_q` from `mpn/generic/sbpi1_divappr_q.c`, GMP 6.2.1.
pub_crate_test! {limbs_div_schoolbook_approx(
qs: &mut [Limb],
ns: &mut [Limb],
mut ds: &[Limb],
d_inv: Limb,
) -> bool {
let n_len = ns.len();
let d_len = ds.len();
assert!(d_len > 2);
assert!(n_len >= d_len);
let a = d_len - 1;
let d_1 = ds[a];
assert!(d_1.get_highest_bit());
let b = d_len - 2;
let d_0 = ds[b];
let q_len = n_len - d_len;
assert!(qs.len() >= q_len);
if q_len + 1 < d_len {
ds = &ds[d_len - (q_len + 1)..];
}
let d_len = ds.len();
let d_len_minus_1 = d_len - 1;
let ns_hi = &mut ns[n_len - d_len..];
let highest_q = limbs_cmp_same_length(ns_hi, ds) >= Equal;
if highest_q {
limbs_sub_same_length_in_place_left(ns_hi, ds);
}
let mut n_1 = *ns.last().unwrap();
let mut q;
let mut n_0;
for i in (d_len_minus_1..q_len).rev() {
let j = i + a;
if n_1 == d_1 && ns[j] == d_0 {
q = Limb::MAX;
limbs_sub_mul_limb_same_length_in_place_left(&mut ns[j - d_len_minus_1..j + 1], ds, q);
n_1 = ns[j]; // update n_1, last loop's value will now be invalid
} else {
let n;
(q, n) = limbs_div_mod_three_limb_by_two_limb(n_1, ns[j], ns[j - 1], d_1, d_0, d_inv);
(n_1, n_0) = n.split_in_half();
let local_carry_1 = limbs_sub_mul_limb_same_length_in_place_left(
&mut ns[j - d_len_minus_1..j - 1],
&ds[..d_len_minus_1 - 1],
q,
);
let local_carry_2 = n_0 < local_carry_1;
n_0.wrapping_sub_assign(local_carry_1);
let carry = local_carry_2 && n_1 == 0;
if local_carry_2 {
n_1.wrapping_sub_assign(1);
}
ns[j - 1] = n_0;
if carry {
n_1.wrapping_add_assign(d_1);
if limbs_slice_add_same_length_in_place_left(
&mut ns[j - d_len_minus_1..j],
&ds[..d_len_minus_1],
) {
n_1.wrapping_add_assign(1);
}
q.wrapping_sub_assign(1);
}
}
qs[i] = q;
}
let mut flag = true;
if d_len_minus_1 > 0 {
for i in (1..d_len_minus_1).rev() {
let j = i + a;
if !flag || n_1 >= d_1 {
q = Limb::MAX;
let carry = limbs_sub_mul_limb_same_length_in_place_left(&mut ns[b..j + 1], ds, q);
if n_1 != carry {
if flag && n_1 < carry {
q.wrapping_sub_assign(1);
limbs_slice_add_same_length_in_place_left(&mut ns[b..j + 1], ds);
} else {
flag = false;
}
}
n_1 = ns[j];
} else {
let n;
(q, n) =
limbs_div_mod_three_limb_by_two_limb(n_1, ns[j], ns[j - 1], d_1, d_0, d_inv);
(n_1, n_0) = n.split_in_half();
let local_carry_1 =
limbs_sub_mul_limb_same_length_in_place_left(&mut ns[b..j - 1], &ds[..i], q);
let local_carry_2 = n_0 < local_carry_1;
n_0.wrapping_sub_assign(local_carry_1);
let carry = local_carry_2 && n_1 == 0;
if local_carry_2 {
n_1.wrapping_sub_assign(1);
}
ns[j - 1] = n_0;
if carry {
n_1.wrapping_add_assign(d_1);
if limbs_slice_add_same_length_in_place_left(&mut ns[b..j], &ds[..i + 1]) {
n_1.wrapping_add_assign(1);
}
q.wrapping_sub_assign(1);
}
}
qs[i] = q;
ds = &ds[1..];
}
let ns = &mut ns[b..];
if !flag || n_1 >= d_1 {
q = Limb::MAX;
let carry = limbs_sub_mul_limb_same_length_in_place_left(&mut ns[..2], &ds[..2], q);
if flag && n_1 < carry {
q.wrapping_sub_assign(1);
limbs_slice_add_same_length_in_place_left(&mut ns[..2], &ds[..2]);
}
n_1 = ns[1];
} else {
let n;
(q, n) = limbs_div_mod_three_limb_by_two_limb(n_1, ns[1], ns[0], d_1, d_0, d_inv);
(n_1, ns[0]) = n.split_in_half();
ns[1] = n_1;
}
qs[0] = q;
}
assert_eq!(ns[a], n_1);
highest_q
}}
// # Worst-case complexity
// $T(n) = O(n (\log n)^2 \log \log n)$
//
// $M(n) = O(n \log n)$
//
// where $T$ is time, $M$ is additional memory, and $n$ is `ds.len()`.
//
// This is equivalent to `mpn_dcpi1_divappr_q_n` from `mpn/generic/dcpi1_divappr_q.c`, GMP 6.2.1,
// where `ns` here is `np + (n >> 1)`.
fn limbs_div_divide_and_conquer_approx_helper(
qs: &mut [Limb],
ns: &mut [Limb],
ds: &[Limb],
d_inv: Limb,
scratch: &mut [Limb],
) -> bool {
let d_len = ds.len();
let lo = d_len >> 1; // floor(d_len / 2)
let hi = d_len - lo; // ceil(d_len / 2)
assert!(ns.len() >= d_len + hi);
let (ds_lo, ds_hi) = ds.split_at(lo);
let qs_hi = &mut qs[lo..];
let ns_hi = &mut ns[lo..];
let mut highest_q = if hi < DC_DIV_QR_THRESHOLD {
limbs_div_mod_schoolbook(qs_hi, &mut ns_hi[..hi << 1], ds_hi, d_inv)
} else {
limbs_div_mod_divide_and_conquer_helper(qs_hi, ns_hi, ds_hi, d_inv, scratch)
};
let mut mul_scratch = vec![0; limbs_mul_greater_to_out_scratch_len(hi, ds_lo.len())];
limbs_mul_greater_to_out(scratch, &qs_hi[..hi], ds_lo, &mut mul_scratch);
let ns_lo = &mut ns[..d_len];
let mut carry = Limb::from(limbs_sub_same_length_in_place_left(
ns_lo,
&scratch[..d_len],
));
if highest_q && limbs_sub_same_length_in_place_left(&mut ns_lo[hi..], ds_lo) {
carry += 1;
}
while carry != 0 {
if limbs_sub_limb_in_place(&mut qs_hi[..hi], 1) {
assert!(highest_q);
highest_q = false;
}
if limbs_slice_add_same_length_in_place_left(ns_lo, ds) {
carry -= 1;
}
}
let ds_hi = &ds[hi..];
let ns_hi = &mut ns[hi - lo..];
let q_lo = if lo < DC_DIVAPPR_Q_THRESHOLD {
limbs_div_schoolbook_approx(qs, &mut ns_hi[..lo << 1], ds_hi, d_inv)
} else {
limbs_div_divide_and_conquer_approx_helper(qs, &mut ns_hi[lo >> 1..], ds_hi, d_inv, scratch)
};
if q_lo {
for q in &mut qs[..lo] {
*q = Limb::MAX;
}
}
highest_q
}
// Recursive divide-and-conquer division, returning approximate quotient.
//
// Divides `ns` by `ds` and writes the `ns.len()` - `ds.len()` least-significant quotient limbs to
// `qs`. Returns the most significant limb of the quotient; `true` means 1 and `false` means 0. The
// quotient is either correct, or one too large. `ds` must have length greater than 2, `ns` must be
// at least as long as `ds`, and the most significant bit of `ds` must be set. `d_inv` should be the
// result of `limbs_two_limb_inverse_helper` applied to the two highest limbs of the denominator.
//
// # Worst-case complexity
// $T(n) = O(n (\log n)^2 \log \log n)$
//
// $M(n) = O(n \log n)$
//
// where $T$ is time, $M$ is additional memory, and $n$ is `ns.len()`.
//
// # Panics
// Panics if `ds` has length smaller than 6, `ns` is shorter than or the same length as `ds`, `qs`
// has length less than `ns.len()` - `ds.len()`, or the last limb of `ds` does not have its highest
// bit set.
//
// This is equivalent to `mpn_dcpi1_divappr_q` from `mpn/generic/dcpi1_divappr_q.c`, GMP 6.2.1.
pub_crate_test! {limbs_div_divide_and_conquer_approx(
qs: &mut [Limb],
ns: &mut [Limb],
ds: &[Limb],
d_inv: Limb,
) -> bool {
let n_len = ns.len();
let d_len = ds.len();
assert!(d_len >= 6);
assert!(n_len > d_len);
let a = d_len - 1;
assert!(ds[a].get_highest_bit());
let b = d_len - 2;
let q_len = n_len - d_len;
let mut highest_q;
if q_len >= d_len {
let q_len_mod_d_len = {
let mut m = (q_len + 1) % d_len;
if m == 0 {
m = d_len;
}
m
};
let mut scratch = vec![0; d_len];
let offset = q_len - q_len_mod_d_len;
let ns_hi = &mut ns[offset..];
let qs_hi = &mut qs[offset..];
let r = d_len - q_len_mod_d_len;
let (ds_lo, ds_hi) = ds.split_at(r);
// Perform the typically smaller block first.
if q_len_mod_d_len == 1 {
// Handle highest_q up front, for simplicity.
let ns_2 = &mut ns_hi[1..d_len + 1];
highest_q = limbs_cmp_same_length(ns_2, ds) >= Equal;
if highest_q {
assert!(!limbs_sub_same_length_in_place_left(ns_2, ds));
}
// A single iteration of schoolbook: One 3/2 division, followed by the bignum update and
// adjustment.
let n_2 = ns_hi[d_len];
let mut n_1 = ns_hi[a];
let mut n_0 = ns_hi[b];
let d_1 = ds[a];
let d_0 = ds[b];
assert!(n_2 < d_1 || (n_2 == d_1 && n_1 <= d_0));
let mut q;
if n_2 == d_1 && n_1 == d_0 {
q = Limb::MAX;
assert_eq!(
limbs_sub_mul_limb_same_length_in_place_left(&mut ns_hi[..d_len], ds, q),
n_2
);
} else {
let n;
(q, n) = limbs_div_mod_three_limb_by_two_limb(n_2, n_1, n_0, d_1, d_0, d_inv);
(n_1, n_0) = n.split_in_half();
// d_len > 2
let local_carry_1 =
limbs_sub_mul_limb_same_length_in_place_left(&mut ns_hi[..b], &ds[..b], q);
let local_carry_2 = n_0 < local_carry_1;
n_0.wrapping_sub_assign(local_carry_1);
let carry = local_carry_2 && n_1 == 0;
if local_carry_2 {
n_1.wrapping_sub_assign(1);
}
ns_hi[b] = n_0;
if carry {
n_1.wrapping_add_assign(d_1);
if limbs_slice_add_same_length_in_place_left(&mut ns_hi[..a], &ds[..a]) {
n_1.wrapping_add_assign(1);
}
if q == 0 {
fail_on_untested_path("limbs_div_divide_and_conquer_approx, q == 0");
assert!(highest_q);
highest_q = false;
}
q.wrapping_sub_assign(1);
}
ns_hi[a] = n_1;
}
qs_hi[0] = q;
} else {
let ns_hi_2 = &mut ns_hi[r..];
highest_q = if q_len_mod_d_len == 2 {
limbs_div_mod_by_two_limb_normalized(
qs_hi,
&mut ns_hi_2[..q_len_mod_d_len + 2],
ds_hi,
)
} else if q_len_mod_d_len < DC_DIV_QR_THRESHOLD {
limbs_div_mod_schoolbook(qs_hi, ns_hi_2, ds_hi, d_inv)
} else {
limbs_div_mod_divide_and_conquer_helper(qs_hi, ns_hi_2, ds_hi, d_inv, &mut scratch)
};
let qs = &mut qs_hi[..q_len_mod_d_len];
if q_len_mod_d_len != d_len {
let mut mul_scratch = vec![0; limbs_mul_to_out_scratch_len(qs.len(), ds_lo.len())];
limbs_mul_to_out(&mut scratch, qs, ds_lo, &mut mul_scratch);
let mut carry = Limb::from(limbs_sub_same_length_in_place_left(
&mut ns_hi[..d_len],
&scratch[..d_len],
));
if highest_q
&& limbs_sub_same_length_in_place_left(
&mut ns_hi[q_len_mod_d_len..d_len],
ds_lo,
)
{
carry += 1;
}
while carry != 0 {
if limbs_sub_limb_in_place(qs, 1) {
assert!(highest_q);
highest_q = false;
}
if limbs_slice_add_same_length_in_place_left(&mut ns_hi[..d_len], ds) {
carry -= 1;
}
}
}
}
let mut offset = q_len.checked_sub(q_len_mod_d_len).unwrap();
while offset >= d_len {
offset -= d_len;
limbs_div_mod_divide_and_conquer_helper(
&mut qs[offset..],
&mut ns[offset..],
ds,
d_inv,
&mut scratch,
);
}
// Since we pretended we'd need an extra quotient limb before, we now have made sure the
// code above left just ds.len() - 1 = qs.len() quotient limbs to develop. Develop that plus
// a guard limb.
let ns = &mut ns[offset + (d_len >> 1) - d_len..];
let q_save = qs[offset];
limbs_div_divide_and_conquer_approx_helper(qs, ns, ds, d_inv, &mut scratch);
slice_move_left(&mut qs[..offset + 1], 1);
qs[offset] = q_save;
} else {
let offset = a - q_len;
let q_len_plus_one = q_len + 1;
let mut qs_2 = vec![0; q_len_plus_one];
let ds = &ds[offset..];
highest_q = if q_len < DC_DIVAPPR_Q_THRESHOLD && offset > 0 {
limbs_div_schoolbook_approx(&mut qs_2, &mut ns[offset - 1..], ds, d_inv)
} else {
let mut scratch = vec![0; q_len_plus_one];
limbs_div_divide_and_conquer_approx_helper(
&mut qs_2,
&mut ns[offset + (q_len_plus_one >> 1) - 1..],
ds,
d_inv,
&mut scratch,
)
};
qs[..q_len].copy_from_slice(&qs_2[1..]);
}
highest_q
}}
// Compute Q = floor(N / D) + e. N has n_len limbs, D has d_len limbs and must be normalized, and Q
// must have n_len - d_len limbs, 0 <= e <= 4. The requirement that Q has n_len - d_len limbs (and
// not n_len - d_len + 1 limbs) was put in place in order to allow us to let N be unmodified during
// the operation.
//
// # Worst-case complexity
// $T(n) = O(n \log n \log \log n)$
//
// $M(n) = O(n \log n)$
//
// where $T$ is time, $M$ is additional memory, and $n$ is `ns.len()`.
//
// This is equivalent to `mpn_mu_divappr_q` from `mpn/generic/mu_divappr_q.c`, GMP 6.2.1.
pub_crate_test! {limbs_div_barrett_approx(
qs: &mut [Limb],
ns: &[Limb],
ds: &[Limb],
scratch: &mut [Limb],
) -> bool {
limbs_div_barrett_approx_helper(qs, ns, false, ds, scratch)
}}
fn limbs_div_barrett_approx_helper(
qs: &mut [Limb],
ns: &[Limb],
mut ns_ghost_limb: bool,
ds: &[Limb],
scratch: &mut [Limb],
) -> bool {
let n_len = if ns_ghost_limb {
ns.len() + 1
} else {
ns.len()
};
let d_len = ds.len();
assert!(d_len > 1);
assert!(n_len >= d_len);
assert!(ds[d_len - 1].get_highest_bit());
let q_len = n_len - d_len;
// If Q is smaller than D, truncate operands.
let (ns, ds) = if q_len + 1 < d_len {
let start = d_len - q_len - 1; // start > 0
if ns_ghost_limb {
ns_ghost_limb = false;
(&ns[start - 1..], &ds[start..])
} else {
(&ns[start..], &ds[start..])
}
} else {
(ns, ds)
};
let d_len_s = ds.len();
// Compute the inverse size.
let i_len = limbs_div_barrett_approx_is_len(q_len, d_len_s);
assert!(i_len <= d_len_s);
let n = i_len + 1;
let (is, scratch_2) = scratch.split_at_mut(n);
// compute an approximate inverse on i_len + 1 limbs
if d_len_s == i_len {
scratch_2[1..n].copy_from_slice(&ds[..i_len]);
scratch_2[0] = 1;
let (scratch_2_lo, scratch_2_hi) = scratch_2.split_at_mut(n);
limbs_invert_approx(is, scratch_2_lo, scratch_2_hi);
slice_move_left(is, 1);
} else if limbs_add_limb_to_out(scratch_2, &ds[d_len_s - n..], 1) {
slice_set_zero(&mut is[..i_len]);
} else {
let (scratch_2_lo, scratch_2_hi) = scratch_2.split_at_mut(n);
limbs_invert_approx(is, scratch_2_lo, scratch_2_hi);
slice_move_left(is, 1);
}
let (is, scratch_hi) = scratch.split_at_mut(i_len);
limbs_div_barrett_approx_preinverted(qs, ns, ns_ghost_limb, ds, is, scratch_hi)
}
// $T(n, d) = O(n \log d \log\log d)$
//
// $M(n) = O(d \log d)$
//
// where $T$ is time, $M$ is additional memory, $n$ is `ns.len()`, and $d$ is `ds.len()`.
//
// This is equivalent to `mpn_preinv_mu_divappr_q` from `mpn/generic/mu_divappr_q.c`, GMP 6.2.1.
fn limbs_div_barrett_approx_preinverted(
qs: &mut [Limb],
ns: &[Limb],
ns_ghost_limb: bool,
ds: &[Limb],
mut is: &[Limb],
scratch: &mut [Limb],
) -> bool {
let n_len = if ns_ghost_limb {
ns.len() + 1
} else {
ns.len()
};
let d_len = ds.len();
let mut i_len = is.len();
let mut q_len = n_len - d_len;
let qs = &mut qs[..q_len];
if ns_ghost_limb {
assert_ne!(q_len, 0);
assert_ne!(i_len, 0);
}
let (ns_lo, ns_hi) = ns.split_at(if ns_ghost_limb { q_len - 1 } else { q_len });
let highest_q = limbs_cmp_same_length(ns_hi, ds) >= Equal;
if q_len == 0 {
return highest_q;
}
let (rs, scratch) = scratch.split_at_mut(d_len);
if highest_q {
limbs_sub_same_length_to_out(rs, ns_hi, ds);
} else {
rs.copy_from_slice(ns_hi);
}
let scratch_len = if i_len < MUL_TO_MULMOD_BNM1_FOR_2NXN_THRESHOLD {
0
} else {
limbs_mul_mod_base_pow_n_minus_1_next_size(d_len + 1)
};
let mut carry = false; // This value is never used
let mut n = d_len - i_len;
let empty_slice: &[Limb] = &[];
let ns_iter: Box<dyn Iterator<Item = &[Limb]>> = if ns_ghost_limb {
Box::new(ns_lo.rchunks(i_len).chain(once(empty_slice)))
} else {
Box::new(ns_lo.rchunks(i_len))
};
let mut mul_scratch = vec![0; limbs_mul_same_length_to_out_scratch_len(i_len)];
for (ns, qs) in ns_iter.zip(qs.rchunks_mut(i_len)) {
let chunk_len = qs.len();
if i_len != chunk_len {
// last iteration
is = &is[i_len - chunk_len..];
i_len = chunk_len;
n = d_len - i_len;
}
let (rs_lo, rs_hi) = rs.split_at_mut(n);
// Compute the next block of quotient limbs by multiplying the inverse I by the upper part
// of the partial remainder R.
limbs_mul_same_length_to_out(scratch, rs_hi, is, &mut mul_scratch);
// i's highest bit is implicit
carry = limbs_add_same_length_to_out(qs, &scratch[i_len..i_len << 1], rs_hi);
assert!(!carry);
q_len -= i_len;
if q_len == 0 {
break;
}
// Compute the product of the quotient block and the divisor D, to be subtracted from the
// partial remainder combined with new limbs from the dividend N. We only really need the
// low d_len limbs.
if i_len < MUL_TO_MULMOD_BNM1_FOR_2NXN_THRESHOLD {
let mut mul_scratch = vec![0; limbs_mul_greater_to_out_scratch_len(ds.len(), qs.len())];
limbs_mul_greater_to_out(scratch, ds, qs, &mut mul_scratch);
} else {
limbs_div_barrett_large_product(scratch, ds, qs, rs_hi, scratch_len, i_len)
}
let mut r = rs_hi[0].wrapping_sub(scratch[d_len]);
// Subtract the product from the partial remainder combined with new limbs from the dividend
// N, generating a new partial remainder R.
let scratch = &mut scratch[..d_len];
if n == 0 {
// get next i_len limbs from N
carry = limbs_sub_same_length_to_out(rs, ns, scratch);
} else {
// get next i_len limbs from N.
let (scratch_lo, scratch_hi) = scratch.split_at_mut(i_len);
carry = limbs_sub_same_length_with_borrow_in_in_place_right(
rs_lo,
scratch_hi,
limbs_sub_same_length_in_place_right(ns, scratch_lo),
);
rs.copy_from_slice(scratch);
}
// Check the remainder R and adjust the quotient as needed.
if carry {
r.wrapping_sub_assign(1);
}
while r != 0 {
// We loop 0 times with about 69% probability, 1 time with about 31% probability, and 2
// times with about 0.6% probability, if inverse is computed as recommended.
assert!(!limbs_slice_add_limb_in_place(qs, 1));
carry = limbs_sub_same_length_in_place_left(rs, ds);
if carry {
r -= 1;
}
}
if limbs_cmp_same_length(rs, ds) >= Equal {
// This is executed with about 76% probability.
assert!(!limbs_slice_add_limb_in_place(qs, 1));
carry = limbs_sub_same_length_in_place_left(rs, ds);
}
}
if limbs_slice_add_limb_in_place(qs, 3) || carry {
if highest_q {
// Return a quotient of just 1-bits, with highest_q set.
for q in &mut *qs {
*q = Limb::MAX;
}
}
true
} else {
highest_q
}
}
// We distinguish 3 cases:
//
// - d_len < q_len: i_len = ceil(q_len / ceil(q_len / d_len))
// - d_len / 3 < q_len <= d_len: i_len = ceil(q_len / 2)
// - q_len < d_len / 3: i_len = q_len
//
// In all cases we have i_len <= d_len.
//
// # Worst-case complexity
// Constant time and additional memory.
//
// The result is $O(n)$, where $n$ is `q_len`.
//
// This is equivalent to `mpn_mu_divappr_q_choose_in` from `mpn/generic/mu_divappr_q.c`, GMP 6.2.1,
// where `k == 0`.
#[allow(clippy::missing_const_for_fn)]
fn limbs_div_barrett_approx_is_len(q_len: usize, d_len: usize) -> usize {
if q_len > d_len {
// Compute an inverse size that is a nice partition of the quotient.
let b = q_len.saturating_sub(1) / d_len + 1; // ceil(q_len / d_len), number of blocks
q_len.saturating_sub(1) / b + 1 // ceil(q_len / b) = ceil(q_len / ceil(q_len / d_len))
} else if 3 * q_len > d_len {
q_len.saturating_sub(1) / 2 + 1 // b = 2
} else {
q_len.saturating_sub(1) + 1 // b = 1
}
}
// # Worst-case complexity
// Constant time and additional memory.
//
// The result is $O(n)$, where $n$ is `n_len`.
//
// This is equivalent to `mpn_mu_divappr_q_itch` from `mpn/generic/mu_divappr_q.c`, GMP 6.2.1, where
// `mua_k == 0`.
pub_crate_test! {limbs_div_barrett_approx_scratch_len(n_len: usize, mut d_len: usize) -> usize {
let qn = n_len - d_len;
if qn + 1 < d_len {
d_len = qn + 1;
}
let is_len = limbs_div_barrett_approx_is_len(qn, d_len);
let local_len = limbs_mul_mod_base_pow_n_minus_1_next_size(d_len + 1);
let out_len = limbs_mul_mod_base_pow_n_minus_1_scratch_len(local_len, d_len, is_len);
// 3 * is_len + 4
let inv_approx_len = limbs_invert_approx_scratch_len(is_len + 1) + is_len + 2;
assert!(d_len + local_len + out_len >= inv_approx_len);
is_len + d_len + local_len + out_len
}}
// TODO tune
const DC_DIV_Q_THRESHOLD: usize = DC_DIVAPPR_Q_THRESHOLD;
// TODO tune
const MU_DIV_Q_THRESHOLD: usize = MU_DIVAPPR_Q_THRESHOLD;
// TODO tune
const MUPI_DIV_Q_THRESHOLD: usize = MUPI_DIVAPPR_Q_THRESHOLD;
// TODO tune
const MUPI_DIVAPPR_Q_THRESHOLD: usize = MUPI_DIV_QR_THRESHOLD;
fn limbs_div_dc_condition(n_len: usize, d_len: usize) -> bool {
let n_64 = n_len as f64;
let d_64 = d_len as f64;
d_len < MUPI_DIV_Q_THRESHOLD
|| n_len < MU_DIV_Q_THRESHOLD << 1
|| libm::fma(
((MU_DIV_Q_THRESHOLD - MUPI_DIV_Q_THRESHOLD) << 1) as f64,
d_64,
MUPI_DIV_Q_THRESHOLD as f64 * n_64,
) > d_64 * n_64
}
// Division when n_len >= 2 * d_len - FUDGE.
//
// # Worst-case complexity
// $T(n) = O(n \log n \log \log n)$
//
// $M(n) = O(n \log n)$
//
// where $T$ is time, $M$ is additional memory, and $n$ is `ns.len()`.
pub_crate_test! {limbs_div_to_out_unbalanced(qs: &mut [Limb], ns: &mut [Limb], ds: &mut [Limb]) {
// ```
// |________________________|
// |_______|
// ```
let n_len = ns.len();
let d_len = ds.len();
let highest_d = ds[d_len - 1];
let bits = LeadingZeros::leading_zeros(highest_d);
if bits == 0 {
let highest_q = if d_len == 2 {
limbs_div_mod_by_two_limb_normalized(qs, ns, ds)
} else if d_len < DC_DIV_Q_THRESHOLD || n_len - d_len < DC_DIV_Q_THRESHOLD {
let d_inv = limbs_two_limb_inverse_helper(highest_d, ds[d_len - 2]);
limbs_div_schoolbook(qs, ns, ds, d_inv)
} else if limbs_div_dc_condition(n_len, d_len) {
let d_inv = limbs_two_limb_inverse_helper(highest_d, ds[d_len - 2]);
limbs_div_divide_and_conquer(qs, ns, ds, d_inv)
} else {
let mut scratch = vec![0; limbs_div_barrett_scratch_len(n_len, d_len)];
limbs_div_barrett(qs, ns, ds, &mut scratch)
};
qs[n_len - d_len] = Limb::from(highest_q);
} else {
let mut scratch = vec![0; n_len + 1];
let carry = limbs_shl_to_out(&mut scratch, ns, bits);
scratch[n_len] = carry;
let new_n_len = if carry == 0 { n_len } else { n_len + 1 };
let new_ns = &mut scratch[..new_n_len];
limbs_slice_shl_in_place(ds, bits);
let highest_q = if d_len == 2 {
limbs_div_mod_by_two_limb_normalized(qs, new_ns, ds)
} else if d_len < DC_DIV_Q_THRESHOLD || new_n_len - d_len < DC_DIV_Q_THRESHOLD {
let d_inv = limbs_two_limb_inverse_helper(ds[d_len - 1], ds[d_len - 2]);
limbs_div_schoolbook(qs, new_ns, ds, d_inv)
} else if limbs_div_dc_condition(n_len, d_len) {
let d_inv = limbs_two_limb_inverse_helper(ds[d_len - 1], ds[d_len - 2]);
limbs_div_divide_and_conquer(qs, new_ns, ds, d_inv)
} else {
let mut scratch = vec![0; limbs_div_barrett_scratch_len(new_n_len, d_len)];
limbs_div_barrett(qs, new_ns, ds, &mut scratch)
};
if carry == 0 {
qs[n_len - d_len] = Limb::from(highest_q);
} else {
assert!(!highest_q);
}
}
}}
pub_test! {limbs_div_q_dc_helper(qs: &mut [Limb], ns: &mut [Limb], ds: &[Limb]) -> bool {
let n_len = ns.len();
let d_len = ds.len();
let highest_d = ds[d_len - 1];
if d_len < DC_DIV_Q_THRESHOLD || ns.len() - d_len < DC_DIV_Q_THRESHOLD {
let d_inv = limbs_two_limb_inverse_helper(highest_d, ds[d_len - 2]);
limbs_div_schoolbook(qs, ns, ds, d_inv)
} else if limbs_div_dc_condition(n_len, d_len) {
let d_inv = limbs_two_limb_inverse_helper(highest_d, ds[d_len - 2]);
limbs_div_divide_and_conquer(qs, ns, ds, d_inv)
} else {
let mut scratch = vec![0; limbs_div_barrett_scratch_len(n_len, d_len)];
limbs_div_barrett(qs, ns, ds, &mut scratch)
}
}}
/// Division when n_len >= 2 * d_len - FUDGE.
///
// # Worst-case complexity
// $T(n) = O(n \log n \log \log n)$
//
// $M(n) = O(n \log n)$
//
// where $T$ is time, $M$ is additional memory, and $n$ is `ns.len()`.
fn limbs_div_to_out_unbalanced_val_ref(qs: &mut [Limb], ns: &mut [Limb], ds: &[Limb]) {
// ```
// |________________________|
// |_______|
// ```
let n_len = ns.len();
let d_len = ds.len();
let highest_d = ds[d_len - 1];
let bits = LeadingZeros::leading_zeros(highest_d);
if bits == 0 {
let highest_q = if d_len == 2 {
limbs_div_mod_by_two_limb_normalized(qs, ns, ds)
} else {
limbs_div_q_dc_helper(qs, ns, ds)
};
qs[n_len - d_len] = Limb::from(highest_q);
} else {
let mut scratch = vec![0; n_len + 1];
let carry = limbs_shl_to_out(&mut scratch, ns, bits);
scratch[n_len] = carry;
let new_n_len = if carry == 0 { n_len } else { n_len + 1 };
let new_ns = &mut scratch[..new_n_len];
let mut new_ds = vec![0; d_len];
limbs_shl_to_out(&mut new_ds, ds, bits);
let highest_q = if d_len == 2 {
limbs_div_mod_by_two_limb_normalized(qs, new_ns, &new_ds)
} else if d_len < DC_DIV_Q_THRESHOLD || new_n_len - d_len < DC_DIV_Q_THRESHOLD {
let d_inv = limbs_two_limb_inverse_helper(new_ds[d_len - 1], new_ds[d_len - 2]);
limbs_div_schoolbook(qs, new_ns, &new_ds, d_inv)
} else if limbs_div_dc_condition(n_len, d_len) {
let d_inv = limbs_two_limb_inverse_helper(new_ds[d_len - 1], new_ds[d_len - 2]);
limbs_div_divide_and_conquer(qs, new_ns, &new_ds, d_inv)
} else {
let mut scratch = vec![0; limbs_div_barrett_scratch_len(new_n_len, d_len)];
limbs_div_barrett(qs, new_ns, &new_ds, &mut scratch)
};
if carry == 0 {
qs[n_len - d_len] = Limb::from(highest_q);
} else {
assert!(!highest_q);
}
}
}
// Division when n_len >= 2 * d_len - FUDGE.
//
// # Worst-case complexity
// $T(n) = O(n \log n \log \log n)$
//
// $M(n) = O(n \log n)$
//
// where $T$ is time, $M$ is additional memory, and $n$ is `ns.len()`.
fn limbs_div_to_out_unbalanced_ref_val(qs: &mut [Limb], ns: &[Limb], ds: &mut [Limb]) {
// ```
// |________________________|
// |_______|
// ```
let n_len = ns.len();
let d_len = ds.len();
let highest_d = ds[d_len - 1];
let bits = LeadingZeros::leading_zeros(highest_d);
if bits == 0 {
let highest_q = if d_len == 2 {
let mut new_ns = ns.to_vec();
limbs_div_mod_by_two_limb_normalized(qs, &mut new_ns, ds)
} else if d_len < DC_DIV_Q_THRESHOLD || n_len - d_len < DC_DIV_Q_THRESHOLD {
let d_inv = limbs_two_limb_inverse_helper(highest_d, ds[d_len - 2]);
let mut new_ns = ns.to_vec();
limbs_div_schoolbook(qs, &mut new_ns, ds, d_inv)
} else if limbs_div_dc_condition(n_len, d_len) {
let d_inv = limbs_two_limb_inverse_helper(highest_d, ds[d_len - 2]);
limbs_div_divide_and_conquer(qs, ns, ds, d_inv)
} else {
let mut scratch = vec![0; limbs_div_barrett_scratch_len(n_len, d_len)];
limbs_div_barrett(qs, ns, ds, &mut scratch)
};
qs[n_len - d_len] = Limb::from(highest_q);
} else {
let mut scratch = vec![0; n_len + 1];
let carry = limbs_shl_to_out(&mut scratch, ns, bits);
scratch[n_len] = carry;
let new_n_len = if carry == 0 { n_len } else { n_len + 1 };
let new_ns = &mut scratch[..new_n_len];
limbs_slice_shl_in_place(ds, bits);
let highest_q = if d_len == 2 {
limbs_div_mod_by_two_limb_normalized(qs, new_ns, ds)
} else if d_len < DC_DIV_Q_THRESHOLD || new_n_len - d_len < DC_DIV_Q_THRESHOLD {
let d_inv = limbs_two_limb_inverse_helper(ds[d_len - 1], ds[d_len - 2]);
limbs_div_schoolbook(qs, new_ns, ds, d_inv)
} else if limbs_div_dc_condition(n_len, d_len) {
let d_inv = limbs_two_limb_inverse_helper(ds[d_len - 1], ds[d_len - 2]);
limbs_div_divide_and_conquer(qs, new_ns, ds, d_inv)
} else {
let mut scratch = vec![0; limbs_div_barrett_scratch_len(new_n_len, d_len)];
limbs_div_barrett(qs, new_ns, ds, &mut scratch)
};
if carry == 0 {
qs[n_len - d_len] = Limb::from(highest_q);
} else {
assert!(!highest_q);
}
}
}
// Division when n_len >= 2 * d_len - FUDGE.
//
// # Worst-case complexity
// $T(n) = O(n \log n \log \log n)$
//
// $M(n) = O(n \log n)$
//
// where $T$ is time, $M$ is additional memory, and $n$ is `ns.len()`.
fn limbs_div_to_out_unbalanced_ref_ref(qs: &mut [Limb], ns: &[Limb], ds: &[Limb]) {
// ```
// |________________________|
// |_______|
// ```
let n_len = ns.len();
let d_len = ds.len();
let highest_d = ds[d_len - 1];
let bits = LeadingZeros::leading_zeros(highest_d);
if bits == 0 {
let highest_q = if d_len == 2 {
let mut new_ns = ns.to_vec();
limbs_div_mod_by_two_limb_normalized(qs, &mut new_ns, ds)
} else if d_len < DC_DIV_Q_THRESHOLD || n_len - d_len < DC_DIV_Q_THRESHOLD {
let d_inv = limbs_two_limb_inverse_helper(highest_d, ds[d_len - 2]);
let mut new_ns = ns.to_vec();
limbs_div_schoolbook(qs, &mut new_ns, ds, d_inv)
} else if limbs_div_dc_condition(n_len, d_len) {
let d_inv = limbs_two_limb_inverse_helper(highest_d, ds[d_len - 2]);
limbs_div_divide_and_conquer(qs, ns, ds, d_inv)
} else {
let mut scratch = vec![0; limbs_div_barrett_scratch_len(n_len, d_len)];
limbs_div_barrett(qs, ns, ds, &mut scratch)
};
qs[n_len - d_len] = Limb::from(highest_q);
} else {
let mut scratch = vec![0; n_len + 1];
let carry = limbs_shl_to_out(&mut scratch, ns, bits);
scratch[n_len] = carry;
let new_n_len = if carry == 0 { n_len } else { n_len + 1 };
let new_ns = &mut scratch[..new_n_len];
let mut new_ds = vec![0; d_len];
limbs_shl_to_out(&mut new_ds, ds, bits);
let highest_q = if d_len == 2 {
limbs_div_mod_by_two_limb_normalized(qs, new_ns, &new_ds)
} else if d_len < DC_DIV_Q_THRESHOLD || new_n_len - d_len < DC_DIV_Q_THRESHOLD {
let d_inv = limbs_two_limb_inverse_helper(new_ds[d_len - 1], new_ds[d_len - 2]);
limbs_div_schoolbook(qs, new_ns, &new_ds, d_inv)
} else if limbs_div_dc_condition(n_len, d_len) {
let d_inv = limbs_two_limb_inverse_helper(new_ds[d_len - 1], new_ds[d_len - 2]);
limbs_div_divide_and_conquer(qs, new_ns, &new_ds, d_inv)
} else {
let mut scratch = vec![0; limbs_div_barrett_scratch_len(new_n_len, d_len)];
limbs_div_barrett(qs, new_ns, &new_ds, &mut scratch)
};
if carry == 0 {
qs[n_len - d_len] = Limb::from(highest_q);
} else {
assert!(!highest_q);
}
}
}
// Division when n_len < 2 * d_len - FUDGE.
//
// # Worst-case complexity
// $T(n) = O(n \log n \log \log n)$
//
// $M(n) = O(n \log n)$
//
// where $T$ is time, $M$ is additional memory, and $n$ is `ns.len()`.
pub_test! {limbs_div_to_out_balanced(qs: &mut [Limb], ns: &[Limb], ds: &[Limb]) {
// ```
// |________________________|
// |_________________|
// ```
let n_len = ns.len();
let d_len = ds.len();
let q_len = n_len - d_len + 1;
let q_len_plus_1 = q_len + 1;
let mut scratch_2 = vec![0; q_len_plus_1];
let new_n_len = q_len + q_len_plus_1;
let ns_tail = &ns[n_len.checked_sub(new_n_len).unwrap()..];
let highest_d = ds[d_len - 1];
let bits = LeadingZeros::leading_zeros(highest_d);
if bits == 0 {
let new_ds = &ds[d_len - q_len_plus_1..];
let highest_q = if q_len_plus_1 == 2 {
let mut new_ns = ns_tail.to_vec();
limbs_div_mod_by_two_limb_normalized(&mut scratch_2, &mut new_ns, new_ds)
} else if q_len_plus_1 < DC_DIVAPPR_Q_THRESHOLD {
let d_inv = limbs_two_limb_inverse_helper(highest_d, new_ds[q_len - 1]);
let mut new_ns = ns_tail.to_vec();
limbs_div_schoolbook_approx(&mut scratch_2, &mut new_ns, new_ds, d_inv)
} else if q_len_plus_1 < MU_DIVAPPR_Q_THRESHOLD {
let d_inv = limbs_two_limb_inverse_helper(highest_d, new_ds[q_len - 1]);
let mut new_ns = ns_tail.to_vec();
limbs_div_divide_and_conquer_approx(&mut scratch_2, &mut new_ns, new_ds, d_inv)
} else {
let mut scratch =
vec![0; limbs_div_barrett_approx_scratch_len(new_n_len, q_len_plus_1)];
limbs_div_barrett_approx(&mut scratch_2, ns_tail, new_ds, &mut scratch)
};
scratch_2[q_len] = Limb::from(highest_q);
} else {
let mut scratch = vec![0; n_len + 1];
let carry = limbs_shl_to_out(&mut scratch, ns_tail, bits);
scratch[new_n_len] = carry;
let new_n_len = if carry == 0 { new_n_len } else { new_n_len + 1 };
let new_ns = &mut scratch[..new_n_len];
let mut new_ds = vec![0; q_len_plus_1];
limbs_shl_to_out(&mut new_ds, &ds[d_len - q_len_plus_1..], bits);
new_ds[0] |= ds[d_len - q_len_plus_1 - 1] >> (Limb::WIDTH - bits);
let highest_q = if q_len_plus_1 == 2 {
limbs_div_mod_by_two_limb_normalized(&mut scratch_2, new_ns, &new_ds)
} else if q_len_plus_1 < DC_DIVAPPR_Q_THRESHOLD {
let d_inv = limbs_two_limb_inverse_helper(new_ds[q_len], new_ds[q_len - 1]);
limbs_div_schoolbook_approx(&mut scratch_2, new_ns, &new_ds, d_inv)
} else if q_len_plus_1 < MU_DIVAPPR_Q_THRESHOLD {
let d_inv = limbs_two_limb_inverse_helper(new_ds[q_len], new_ds[q_len - 1]);
limbs_div_divide_and_conquer_approx(&mut scratch_2, new_ns, &new_ds, d_inv)
} else {
let mut scratch =
vec![0; limbs_div_barrett_approx_scratch_len(new_n_len, q_len_plus_1)];
limbs_div_barrett_approx(&mut scratch_2, new_ns, &new_ds, &mut scratch)
};
if carry == 0 {
scratch_2[q_len] = Limb::from(highest_q);
} else if highest_q {
fail_on_untested_path("limbs_div_to_out_balanced, highest_q");
// This happens only when the quotient is close to B ^ n and one of the approximate
// division functions returned B ^ n.
for s in &mut scratch_2[..new_n_len - q_len_plus_1] {
*s = Limb::MAX;
}
}
}
let (scratch_2_head, scratch_2_tail) = scratch_2.split_first().unwrap();
qs[..q_len].copy_from_slice(scratch_2_tail);
if *scratch_2_head <= 4 {
let mut rs = vec![0; n_len + 1];
let mut mul_scratch =
vec![0; limbs_mul_greater_to_out_scratch_len(ds.len(), scratch_2_tail.len())];
limbs_mul_greater_to_out(&mut rs, ds, scratch_2_tail, &mut mul_scratch);
let r_len = if rs[n_len] == 0 { n_len } else { n_len + 1 };
if r_len > n_len || limbs_cmp_same_length(ns, &rs[..n_len]) == Less {
assert!(!limbs_sub_limb_in_place(qs, 1));
}
}
}}
// Interpreting two slices of `Limb`s, `ns` and `ds`, as the limbs (in ascending order) of two
// `Natural`s, divides them, returning the quotient. The quotient has `ns.len() - ds.len() + 1`
// limbs.
//
// `ns` must be at least as long as `ds` and `ds` must have length at least 2 and its most
// significant limb must be greater than zero.
//
// # Worst-case complexity
// $T(n) = O(n \log n \log \log n)$
//
// $M(n) = O(n \log n)$
//
// where $T$ is time, $M$ is additional memory, and $n$ is `ns.len()`.
//
// # Panics
// Panics if `ns` is shorter than `ds`, `ds` has length less than 2, or the most-significant limb of
// `ds` is zero.
//
// This is equivalent to `mpn_div_q` from `mpn/generic/div_q.c`, GMP 6.2.1, where `scratch` is
// allocated internally and `qp` is returned.
pub_test! {limbs_div(ns: &[Limb], ds: &[Limb]) -> Vec<Limb> {
let mut qs = vec![0; ns.len() - ds.len() + 1];
limbs_div_to_out_ref_ref(&mut qs, ns, ds);
qs
}}
// Interpreting two slices of `Limb`s, `ns` and `ds`, as the limbs (in ascending order) of two
// `Natural`s, divides them, writing the `ns.len() - ds.len() + 1` limbs of the quotient to `qs`.
//
// `ns` must be at least as long as `ds`, `qs` must have length at least `ns.len() - ds.len() + 1`,
// and `ds` must have length at least 2 and its most significant limb must be greater than zero.
//
// # Worst-case complexity
// $T(n) = O(n \log n \log \log n)$
//
// $M(n) = O(n \log n)$
//
// where $T$ is time, $M$ is additional memory, and $n$ is `ns.len()`.
//
// # Panics
// Panics if `qs` is too short, `ns` is shorter than `ds`, `ds` has length less than 2, or the
// most-significant limb of `ds` is zero.
//
// This is equivalent to `mpn_div_q` from `mpn/generic/div_q.c`, GMP 6.2.1, where `scratch` is
// allocated internally and `np` and `dp` are consumed, saving some memory allocations.
pub_crate_test! {limbs_div_to_out(qs: &mut [Limb], ns: &mut [Limb], ds: &mut [Limb]) {
let n_len = ns.len();
let d_len = ds.len();
assert!(n_len >= d_len);
assert!(d_len > 1);
assert_ne!(ds[d_len - 1], 0);
assert!(FUDGE >= 2);
let q_len = n_len - d_len + 1; // Quotient size, high limb might be zero
if q_len + FUDGE >= d_len {
limbs_div_to_out_unbalanced(qs, ns, ds);
} else {
limbs_div_to_out_balanced(qs, ns, ds);
}
}}
// Interpreting two slices of `Limb`s, `ns` and `ds`, as the limbs (in ascending order) of two
// `Natural`s, divides them, writing the `ns.len() - ds.len() + 1` limbs of the quotient to `qs`.
//
// `ns` must be at least as long as `ds`, `qs` must have length at least `ns.len() - ds.len() + 1`,
// and `ds` must have length at least 2 and its most significant limb must be greater than zero.
//
// # Worst-case complexity
// $T(n) = O(n \log n \log \log n)$
//
// $M(n) = O(n \log n)$
//
// where $T$ is time, $M$ is additional memory, and $n$ is `ns.len()`.
//
// # Panics
// Panics if `qs` is too short, `ns` is shorter than `ds`, `ds` has length less than 2, or the
// most-significant limb of `ds` is zero.
//
// This is equivalent to `mpn_div_q` from `mpn/generic/div_q.c`, GMP 6.2.1, where `scratch` is
// allocated internally and `np` is consumed, saving some memory allocations.
pub_test! {limbs_div_to_out_val_ref(qs: &mut [Limb], ns: &mut [Limb], ds: &[Limb]) {
let n_len = ns.len();
let d_len = ds.len();
assert!(n_len >= d_len);
assert!(d_len > 1);
assert_ne!(ds[d_len - 1], 0);
assert!(FUDGE >= 2);
let q_len = n_len - d_len + 1; // Quotient size, high limb might be zero
if q_len + FUDGE >= d_len {
limbs_div_to_out_unbalanced_val_ref(qs, ns, ds);
} else {
limbs_div_to_out_balanced(qs, ns, ds);
}
}}
// Interpreting two slices of `Limb`s, `ns` and `ds`, as the limbs (in ascending order) of two
// `Natural`s, divides them, writing the `ns.len() - ds.len() + 1` limbs of the quotient to `qs`.
//
// `ns` must be at least as long as `ds`, `qs` must have length at least `ns.len() - ds.len() + 1`,
// and `ds` must have length at least 2 and its most significant limb must be greater than zero.
//
// # Worst-case complexity
// $T(n) = O(n \log n \log \log n)$
//
// $M(n) = O(n \log n)$
//
// where $T$ is time, $M$ is additional memory, and $n$ is `ns.len()`.
//
// # Panics
// Panics if `qs` is too short, `ns` is shorter than `ds`, `ds` has length less than 2, or the
// most-significant limb of `ds` is zero.
//
// This is equivalent to `mpn_div_q` from `mpn/generic/div_q.c`, GMP 6.2.1, where `scratch` is
// allocated internally and `dp` is consumed, saving some memory allocations.
pub_test! {limbs_div_to_out_ref_val(qs: &mut [Limb], ns: &[Limb], ds: &mut [Limb]) {
let n_len = ns.len();
let d_len = ds.len();
assert!(n_len >= d_len);
assert!(d_len > 1);
assert_ne!(ds[d_len - 1], 0);
assert!(FUDGE >= 2);
let q_len = n_len - d_len + 1; // Quotient size, high limb might be zero
if q_len + FUDGE >= d_len {
limbs_div_to_out_unbalanced_ref_val(qs, ns, ds);
} else {
limbs_div_to_out_balanced(qs, ns, ds);
}
}}
// Interpreting two slices of `Limb`s, `ns` and `ds`, as the limbs (in ascending order) of two
// `Natural`s, divides them, writing the `ns.len() - ds.len() + 1` limbs of the quotient to `qs`.
//
// `ns` must be at least as long as `ds`, `qs` must have length at least `ns.len() - ds.len() + 1`,
// and `ds` must have length at least 2 and its most significant limb must be greater than zero.
//
// # Worst-case complexity
// $T(n) = O(n \log n \log \log n)$
//
// $M(n) = O(n \log n)$
//
// where $T$ is time, $M$ is additional memory, and $n$ is `ns.len()`.
//
// # Panics
// Panics if `qs` is too short, `ns` is shorter than `ds`, `ds` has length less than 2, or the
// most-significant limb of `ds` is zero.
//
// This is equivalent to `mpn_div_q` from `mpn/generic/div_q.c`, GMP 6.2.1, where `scratch` is
// allocated internally.
pub_test! {limbs_div_to_out_ref_ref(qs: &mut [Limb], ns: &[Limb], ds: &[Limb]) {
let n_len = ns.len();
let d_len = ds.len();
assert!(n_len >= d_len);
assert!(d_len > 1);
assert_ne!(ds[d_len - 1], 0);
assert!(FUDGE >= 2);
let q_len = n_len - d_len + 1; // Quotient size, high limb might be zero
if q_len + FUDGE >= d_len {
limbs_div_to_out_unbalanced_ref_ref(qs, ns, ds);
} else {
limbs_div_to_out_balanced(qs, ns, ds);
}
}}
// Divides using the naive (schoolbook) algorithm.
//
// # Worst-case complexity
// Constant time and additional memory.
#[cfg(feature = "test_build")]
fn limbs_div_in_place_naive(ns: &mut [Limb], d: Limb) {
let limb = DoubleLimb::from(d);
let mut upper = 0;
for n in ns.iter_mut().rev() {
let lower = *n;
let (q, r) = DoubleLimb::join_halves(upper, lower).div_rem(limb);
*n = q.lower_half();
upper = r.lower_half();
}
}
// This is equivalent to `mpn_pi1_bdiv_q_1` from `mpn/generic/bdiv_q_1.c`, GMP 6.2.1, where rp ==
// up.
pub(crate) fn limbs_hensel_div_limb_in_place(
ns: &mut [Limb],
d: Limb,
d_inv: Limb,
shift: u64,
) -> bool {
let n_len = ns.len();
assert_ne!(n_len, 0);
assert_ne!(d, 0);
let mut carry = 0;
if shift == 0 {
let (ns_head, ns_tail) = ns.split_first_mut().unwrap();
let mut l = ns_head.wrapping_mul(d_inv);
*ns_head = l;
let mut carry_2 = false;
for n in ns_tail {
let mut carry = Limb::x_mul_y_to_zz(l, d).0;
if carry_2 {
carry += 1;
}
(l, carry_2) = n.overflowing_sub(carry);
l.wrapping_mul_assign(d_inv);
*n = l;
}
carry_2
} else {
for i in 0..n_len - 1 {
let n = (ns[i] >> shift) | (ns[i + 1] << (Limb::WIDTH - shift));
let (mut l, carry_2) = n.overflowing_sub(carry);
l.wrapping_mul_assign(d_inv);
ns[i] = l;
carry = Limb::x_mul_y_to_zz(l, d).0;
if carry_2 {
carry += 1;
}
}
let ns_last = ns.last_mut().unwrap();
let (l, carry_2) = (*ns_last >> shift).overflowing_sub(carry);
*ns_last = l.wrapping_mul(d_inv);
carry_2
}
}
impl Natural {
fn div_limb_ref(&self, other: Limb) -> Natural {
match (self, other) {
(_, 0) => panic!("division by zero"),
(n, 1) => n.clone(),
(Natural(Small(small)), other) => Natural(Small(small / other)),
(Natural(Large(ref limbs)), other) => {
Natural::from_owned_limbs_asc(limbs_div_limb(limbs, other))
}
}
}
#[cfg(feature = "test_build")]
#[inline]
pub fn div_limb_naive(mut self, other: Limb) -> Natural {
self.div_assign_limb_naive(other);
self
}
fn div_assign_limb(&mut self, other: Limb) {
match (&mut *self, other) {
(_, 0) => panic!("division by zero"),
(_, 1) => {}
(Natural(Small(ref mut small)), other) => *small /= other,
(Natural(Large(ref mut limbs)), other) => {
limbs_div_limb_in_place(limbs, other);
self.trim();
}
}
}
#[cfg(feature = "test_build")]
pub fn div_assign_limb_naive(&mut self, other: Limb) {
match (&mut *self, other) {
(_, 0) => panic!("division by zero"),
(_, 1) => {}
(Natural(Small(ref mut small)), other) => {
*small /= other;
}
(Natural(Large(ref mut limbs)), other) => {
limbs_div_in_place_naive(limbs, other);
self.trim();
}
}
}
}
impl Div<Natural> for Natural {
type Output = Natural;
/// Divides a [`Natural`] by another [`Natural`], taking both by value. The quotient is rounded
/// towards negative infinity. The quotient and remainder (which is not computed) satisfy $x =
/// qy + r$ and $0 \leq r < y$.
///
/// $$
/// f(x, y) = \left \lfloor \frac{x}{y} \right \rfloor.
/// $$
///
/// # Worst-case complexity
/// $T(n) = O(n \log n \log\log n)$
///
/// $M(n) = O(n \log n)$
///
/// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.
///
/// # Panics
/// Panics if `other` is zero.
///
/// # Examples
/// ```
/// use core::str::FromStr;
/// use malachite_nz::natural::Natural;
///
/// // 2 * 10 + 3 = 23
/// assert_eq!(Natural::from(23u32) / Natural::from(10u32), 2);
///
/// // 810000006723 * 1234567890987 + 530068894399 = 1000000000000000000000000
/// assert_eq!(
/// Natural::from_str("1000000000000000000000000").unwrap()
/// / Natural::from_str("1234567890987").unwrap(),
/// 810000006723u64
/// );
/// ```
#[inline]
fn div(mut self, other: Natural) -> Natural {
self /= other;
self
}
}
impl<'a> Div<&'a Natural> for Natural {
type Output = Natural;
/// Divides a [`Natural`] by another [`Natural`], taking the first by value and the second by
/// reference. The quotient is rounded towards negative infinity. The quotient and remainder
/// (which is not computed) satisfy $x = qy + r$ and $0 \leq r < y$.
///
/// # Worst-case complexity
/// $T(n) = O(n \log n \log\log n)$
///
/// $M(n) = O(n \log n)$
///
/// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.
///
/// # Panics
/// Panics if `other` is zero.
///
/// # Examples
/// ```
/// use core::str::FromStr;
/// use malachite_nz::natural::Natural;
///
/// // 2 * 10 + 3 = 23
/// assert_eq!(Natural::from(23u32) / &Natural::from(10u32), 2);
///
/// // 810000006723 * 1234567890987 + 530068894399 = 1000000000000000000000000
/// assert_eq!(
/// Natural::from_str("1000000000000000000000000").unwrap()
/// / &Natural::from_str("1234567890987").unwrap(),
/// 810000006723u64
/// );
/// ```
#[inline]
fn div(mut self, other: &'a Natural) -> Natural {
self /= other;
self
}
}
impl<'a> Div<Natural> for &'a Natural {
type Output = Natural;
/// Divides a [`Natural`] by another [`Natural`], taking the first by reference and the second
/// by value. The quotient is rounded towards negative infinity. The quotient and remainder
/// (which is not computed) satisfy $x = qy + r$ and $0 \leq r < y$.
///
/// # Worst-case complexity
/// $T(n) = O(n \log n \log\log n)$
///
/// $M(n) = O(n \log n)$
///
/// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.
///
/// # Panics
/// Panics if `other` is zero.
///
/// # Examples
/// ```
/// use core::str::FromStr;
/// use malachite_nz::natural::Natural;
///
/// // 2 * 10 + 3 = 23
/// assert_eq!(&Natural::from(23u32) / Natural::from(10u32), 2);
///
/// // 810000006723 * 1234567890987 + 530068894399 = 1000000000000000000000000
/// assert_eq!(
/// &Natural::from_str("1000000000000000000000000").unwrap()
/// / Natural::from_str("1234567890987").unwrap(),
/// 810000006723u64
/// );
/// ```
fn div(self, mut other: Natural) -> Natural {
match (self, &mut other) {
(_, &mut Natural::ZERO) => panic!("division by zero"),
(x, y) if x == y => Natural::ONE,
(n, &mut Natural::ONE) => n.clone(),
(n, &mut Natural(Small(d))) => n.div_limb_ref(d),
(Natural(Small(_)), _) => Natural::ZERO,
(&Natural(Large(ref ns)), &mut Natural(Large(ref mut ds))) => {
let ns_len = ns.len();
let ds_len = ds.len();
if ns_len < ds_len {
Natural::ZERO
} else {
let mut qs = vec![0; ns_len - ds_len + 1];
limbs_div_to_out_ref_val(&mut qs, ns, ds);
Natural::from_owned_limbs_asc(qs)
}
}
}
}
}
impl<'a, 'b> Div<&'b Natural> for &'a Natural {
type Output = Natural;
/// Divides a [`Natural`] by another [`Natural`], taking both by reference. The quotient is
/// rounded towards negative infinity. The quotient and remainder (which is not computed)
/// satisfy $x = qy + r$ and $0 \leq r < y$.
///
/// # Worst-case complexity
/// $T(n) = O(n \log n \log\log n)$
///
/// $M(n) = O(n \log n)$
///
/// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.
///
/// # Panics
/// Panics if `other` is zero.
///
/// # Examples
/// ```
/// use core::str::FromStr;
/// use malachite_nz::natural::Natural;
///
/// // 2 * 10 + 3 = 23
/// assert_eq!(&Natural::from(23u32) / &Natural::from(10u32), 2);
///
/// // 810000006723 * 1234567890987 + 530068894399 = 1000000000000000000000000
/// assert_eq!(
/// &Natural::from_str("1000000000000000000000000").unwrap()
/// / &Natural::from_str("1234567890987").unwrap(),
/// 810000006723u64
/// );
/// ```
fn div(self, other: &'b Natural) -> Natural {
match (self, other) {
(_, &Natural::ZERO) => panic!("division by zero"),
(x, y) if x == y => Natural::ONE,
(n, &Natural::ONE) => n.clone(),
(n, &Natural(Small(d))) => n.div_limb_ref(d),
(Natural(Small(_)), _) => Natural::ZERO,
(&Natural(Large(ref ns)), &Natural(Large(ref ds))) => {
if ns.len() < ds.len() {
Natural::ZERO
} else {
Natural::from_owned_limbs_asc(limbs_div(ns, ds))
}
}
}
}
}
impl DivAssign<Natural> for Natural {
/// Divides a [`Natural`] by another [`Natural`] in place, taking the [`Natural`] on the
/// right-hand side by value. The quotient is rounded towards negative infinity. The quotient
/// and remainder (which is not computed) satisfy $x = qy + r$ and $0 \leq r < y$.
///
/// # Worst-case complexity
/// $T(n) = O(n \log n \log\log n)$
///
/// $M(n) = O(n \log n)$
///
/// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.
///
/// # Panics
/// Panics if `other` is zero.
///
/// # Examples
/// ```
/// use core::str::FromStr;
/// use malachite_nz::natural::Natural;
///
/// // 2 * 10 + 3 = 23
/// let mut x = Natural::from(23u32);
/// x /= Natural::from(10u32);
/// assert_eq!(x, 2);
///
/// // 810000006723 * 1234567890987 + 530068894399 = 1000000000000000000000000
/// let mut x = Natural::from_str("1000000000000000000000000").unwrap();
/// x /= Natural::from_str("1234567890987").unwrap();
/// assert_eq!(x, 810000006723u64);
/// ```
fn div_assign(&mut self, other: Natural) {
match (&mut *self, other) {
(_, Natural::ZERO) => panic!("division by zero"),
(x, y) if *x == y => {
*self = Natural::ONE;
}
(_, Natural::ONE) => {}
(n, Natural(Small(d))) => n.div_assign_limb(d),
(Natural(Small(_)), _) => *self = Natural::ZERO,
(&mut Natural(Large(ref mut ns)), Natural(Large(ref mut ds))) => {
let ns_len = ns.len();
let ds_len = ds.len();
if ns_len < ds_len {
*self = Natural::ZERO;
} else {
let mut qs = vec![0; ns_len - ds_len + 1];
limbs_div_to_out(&mut qs, ns, ds);
swap(&mut qs, ns);
self.trim();
}
}
}
}
}
impl<'a> DivAssign<&'a Natural> for Natural {
/// Divides a [`Natural`] by another [`Natural`] in place, taking the [`Natural`] on the
/// right-hand side by reference. The quotient is rounded towards negative infinity. The
/// quotient and remainder (which is not computed) satisfy $x = qy + r$ and $0 \leq r < y$.
///
/// # Worst-case complexity
/// $T(n) = O(n \log n \log\log n)$
///
/// $M(n) = O(n \log n)$
///
/// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.
///
/// # Panics
/// Panics if `other` is zero.
///
/// # Examples
/// ```
/// use core::str::FromStr;
/// use malachite_nz::natural::Natural;
///
/// // 2 * 10 + 3 = 23
/// let mut x = Natural::from(23u32);
/// x /= &Natural::from(10u32);
/// assert_eq!(x, 2);
///
/// // 810000006723 * 1234567890987 + 530068894399 = 1000000000000000000000000
/// let mut x = Natural::from_str("1000000000000000000000000").unwrap();
/// x /= &Natural::from_str("1234567890987").unwrap();
/// assert_eq!(x, 810000006723u64);
/// ```
fn div_assign(&mut self, other: &'a Natural) {
match (&mut *self, other) {
(_, &Natural::ZERO) => panic!("division by zero"),
(x, y) if x == y => {
*self = Natural::ONE;
}
(_, &Natural::ONE) => {}
(n, &Natural(Small(d))) => n.div_assign_limb(d),
(Natural(Small(_)), _) => *self = Natural::ZERO,
(&mut Natural(Large(ref mut ns)), Natural(Large(ref ds))) => {
let ns_len = ns.len();
let ds_len = ds.len();
if ns_len < ds_len {
*self = Natural::ZERO;
} else {
let mut qs = vec![0; ns_len - ds_len + 1];
limbs_div_to_out_val_ref(&mut qs, ns, ds);
swap(&mut qs, ns);
self.trim();
}
}
}
}
}
impl CheckedDiv<Natural> for Natural {
type Output = Natural;
/// Divides a [`Natural`] by another [`Natural`], taking both by value. The quotient is rounded
/// towards negative infinity. The quotient and remainder (which is not computed) satisfy $x =
/// qy + r$ and $0 \leq r < y$. Returns `None` when the second [`Natural`] is zero, `Some`
/// otherwise.
///
/// $$
/// f(x, y) = \begin{cases}
/// \operatorname{Some}\left ( \left \lfloor \frac{x}{y} \right \rfloor \right ) &
/// \text{if} \\quad y \neq 0 \\\\
/// \text{None} & \text{otherwise}
/// \end{cases}
/// $$
///
/// # Worst-case complexity
/// $T(n) = O(n \log n \log\log n)$
///
/// $M(n) = O(n \log n)$
///
/// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.
///
/// # Panics
/// Panics if `other` is zero.
///
/// # Examples
/// ```
/// use malachite_base::num::arithmetic::traits::CheckedDiv;
/// use malachite_base::num::basic::traits::{One, Zero};
/// use malachite_base::strings::ToDebugString;
/// use malachite_nz::natural::Natural;
///
/// // 2 * 10 + 3 = 23
/// assert_eq!(
/// Natural::from(23u32)
/// .checked_div(Natural::from(10u32))
/// .to_debug_string(),
/// "Some(2)"
/// );
/// assert_eq!(Natural::ONE.checked_div(Natural::ZERO), None);
/// ```
#[inline]
fn checked_div(self, mut other: Natural) -> Option<Natural> {
match (self, &mut other) {
(_, &mut Natural::ZERO) => None,
(x, y) if x == *y => Some(Natural::ONE),
(n, &mut Natural::ONE) => Some(n),
(mut n, &mut Natural(Small(d))) => {
n.div_assign_limb(d);
Some(n)
}
(Natural(Small(_)), _) => Some(Natural::ZERO),
(Natural(Large(mut ns)), &mut Natural(Large(ref mut ds))) => {
let ns_len = ns.len();
let ds_len = ds.len();
Some(if ns_len < ds_len {
Natural::ZERO
} else {
let mut qs = vec![0; ns_len - ds_len + 1];
limbs_div_to_out(&mut qs, &mut ns, ds);
Natural::from_owned_limbs_asc(qs)
})
}
}
}
}
impl<'a> CheckedDiv<&'a Natural> for Natural {
type Output = Natural;
/// Divides a [`Natural`] by another [`Natural`], taking the first by value and the second by
/// reference. The quotient is rounded towards negative infinity. The quotient and remainder
/// (which is not computed) satisfy $x = qy + r$ and $0 \leq r < y$. Returns `None` when the
/// second [`Natural`] is zero, `Some` otherwise.
///
/// $$
/// f(x, y) = \begin{cases}
/// \operatorname{Some}\left ( \left \lfloor \frac{x}{y} \right \rfloor \right ) &
/// \text{if} \\quad y \neq 0 \\\\
/// \text{None} & \text{otherwise}
/// \end{cases}
/// $$
///
/// # Worst-case complexity
/// $T(n) = O(n \log n \log\log n)$
///
/// $M(n) = O(n \log n)$
///
/// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.
///
/// # Panics
/// Panics if `other` is zero.
///
/// # Examples
/// ```
/// use malachite_base::num::arithmetic::traits::CheckedDiv;
/// use malachite_base::num::basic::traits::{One, Zero};
/// use malachite_base::strings::ToDebugString;
/// use malachite_nz::natural::Natural;
///
/// // 2 * 10 + 3 = 23
/// assert_eq!(
/// Natural::from(23u32)
/// .checked_div(&Natural::from(10u32))
/// .to_debug_string(),
/// "Some(2)"
/// );
/// assert_eq!(Natural::ONE.checked_div(&Natural::ZERO), None);
/// ```
#[inline]
fn checked_div(self, other: &'a Natural) -> Option<Natural> {
match (self, other) {
(_, &Natural::ZERO) => None,
(x, y) if x == *y => Some(Natural::ONE),
(n, &Natural::ONE) => Some(n.clone()),
(mut n, &Natural(Small(d))) => {
n.div_assign_limb(d);
Some(n)
}
(Natural(Small(_)), _) => Some(Natural::ZERO),
(Natural(Large(mut ns)), &Natural(Large(ref ds))) => {
let ns_len = ns.len();
let ds_len = ds.len();
Some(if ns_len < ds_len {
Natural::ZERO
} else {
let mut qs = vec![0; ns_len - ds_len + 1];
limbs_div_to_out_val_ref(&mut qs, &mut ns, ds);
Natural::from_owned_limbs_asc(qs)
})
}
}
}
}
impl<'a> CheckedDiv<Natural> for &'a Natural {
type Output = Natural;
/// Divides a [`Natural`] by another [`Natural`], taking the first by reference and the second
/// by value. The quotient is rounded towards negative infinity. The quotient and remainder
/// (which is not computed) satisfy $x = qy + r$ and $0 \leq r < y$. Returns `None` when the
/// second [`Natural`] is zero, `Some` otherwise.
///
/// $$
/// f(x, y) = \begin{cases}
/// \operatorname{Some}\left ( \left \lfloor \frac{x}{y} \right \rfloor \right ) &
/// \text{if} \\quad y \neq 0 \\\\
/// \text{None} & \text{otherwise}
/// \end{cases}
/// $$
///
/// # Worst-case complexity
/// $T(n) = O(n \log n \log\log n)$
///
/// $M(n) = O(n \log n)$
///
/// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.
///
/// # Panics
/// Panics if `other` is zero.
///
/// # Examples
/// ```
/// use malachite_base::num::arithmetic::traits::CheckedDiv;
/// use malachite_base::num::basic::traits::{One, Zero};
/// use malachite_base::strings::ToDebugString;
/// use malachite_nz::natural::Natural;
///
/// // 2 * 10 + 3 = 23
/// assert_eq!(
/// (&Natural::from(23u32))
/// .checked_div(Natural::from(10u32))
/// .to_debug_string(),
/// "Some(2)"
/// );
/// assert_eq!((&Natural::ONE).checked_div(Natural::ZERO), None);
/// ```
fn checked_div(self, mut other: Natural) -> Option<Natural> {
match (self, &mut other) {
(_, &mut Natural::ZERO) => None,
(x, y) if x == y => Some(Natural::ONE),
(n, &mut Natural::ONE) => Some(n.clone()),
(n, &mut Natural(Small(d))) => Some(n.div_limb_ref(d)),
(Natural(Small(_)), _) => Some(Natural::ZERO),
(&Natural(Large(ref ns)), &mut Natural(Large(ref mut ds))) => {
let ns_len = ns.len();
let ds_len = ds.len();
Some(if ns_len < ds_len {
Natural::ZERO
} else {
let mut qs = vec![0; ns_len - ds_len + 1];
limbs_div_to_out_ref_val(&mut qs, ns, ds);
Natural::from_owned_limbs_asc(qs)
})
}
}
}
}
impl<'a, 'b> CheckedDiv<&'b Natural> for &'a Natural {
type Output = Natural;
/// Divides a [`Natural`] by another [`Natural`], taking both by reference. The quotient is
/// rounded towards negative infinity. The quotient and remainder (which is not computed)
/// satisfy $x = qy + r$ and $0 \leq r < y$. Returns `None` when the second [`Natural`] is zero,
/// `Some` otherwise.
///
/// $$
/// f(x, y) = \begin{cases}
/// \operatorname{Some}\left ( \left \lfloor \frac{x}{y} \right \rfloor \right ) &
/// \text{if} \\quad y \neq 0 \\\\
/// \text{None} & \text{otherwise}
/// \end{cases}
/// $$
///
/// # Worst-case complexity
/// $T(n) = O(n \log n \log\log n)$
///
/// $M(n) = O(n \log n)$
///
/// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.
///
/// # Panics
/// Panics if `other` is zero.
///
/// # Examples
/// ```
/// use malachite_base::num::arithmetic::traits::CheckedDiv;
/// use malachite_base::num::basic::traits::{One, Zero};
/// use malachite_base::strings::ToDebugString;
/// use malachite_nz::natural::Natural;
///
/// // 2 * 10 + 3 = 23
/// assert_eq!(
/// (&Natural::from(23u32))
/// .checked_div(&Natural::from(10u32))
/// .to_debug_string(),
/// "Some(2)"
/// );
/// assert_eq!((&Natural::ONE).checked_div(&Natural::ZERO), None);
/// ```
fn checked_div(self, other: &'b Natural) -> Option<Natural> {
match (self, other) {
(_, &Natural::ZERO) => None,
(x, y) if x == y => Some(Natural::ONE),
(n, &Natural::ONE) => Some(n.clone()),
(n, &Natural(Small(d))) => Some(n.div_limb_ref(d)),
(Natural(Small(_)), _) => Some(Natural::ZERO),
(&Natural(Large(ref ns)), &Natural(Large(ref ds))) => Some(if ns.len() < ds.len() {
Natural::ZERO
} else {
Natural::from_owned_limbs_asc(limbs_div(ns, ds))
}),
}
}
}