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
|
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*=============================================================================
**
** Struct: BigInteger
**
** Purpose: Represents an arbitrary precision integer.
**
=============================================================================*/
using System;
using System.Diagnostics.Contracts;
using System.Collections.Generic;
using System.Globalization;
using System.Numerics;
using System.Text;
using Conditional = System.Diagnostics.ConditionalAttribute;
namespace System.Numerics
{
#if !SILVERLIGHT
[Serializable]
#endif // !SILVERLIGHT
public struct BigInteger : IFormattable, IComparable, IComparable<BigInteger>, IEquatable<BigInteger>
{
// ---- SECTION: members supporting exposed properties -------------*
#region members supporting exposed properties
private const int knMaskHighBit = int.MinValue;
private const uint kuMaskHighBit = unchecked((uint)int.MinValue);
private const int kcbitUint = 32;
private const int kcbitUlong = 64;
private const int DecimalScaleFactorMask = 0x00FF0000;
private const int DecimalSignMask = unchecked((int)0x80000000);
// For values int.MinValue < n <= int.MaxValue, the value is stored in sign
// and _bits is null. For all other values, sign is +1 or -1 and the bits are in _bits
internal int _sign;
internal uint[] _bits;
// We have to make a choice of how to represent int.MinValue. This is the one
// value that fits in an int, but whose negation does not fit in an int.
// We choose to use a large representation, so we're symmetric with respect to negation.
private static readonly BigInteger s_bnMinInt = new BigInteger(-1, new uint[] { kuMaskHighBit });
private static readonly BigInteger s_bnOneInt = new BigInteger(1);
private static readonly BigInteger s_bnZeroInt = new BigInteger(0);
private static readonly BigInteger s_bnMinusOneInt = new BigInteger(-1);
#if CONTRACTS_FULL
[ContractInvariantMethod]
private void ObjectInvariant()
{
Contract.Invariant((_bits == null) ? _sign > Int32.MinValue :
((_sign == 1 || _sign == -1) && Length(_bits) > 0));
Contract.Invariant(_bits == null || Length(_bits) > 1 || _bits[0] >= kuMaskHighBit
, "One element array stores integers whose absolute value is between 0x80000000 and 0xFFFFFFFF");
}
#endif
[Conditional("DEBUG")]
private void AssertValid()
{
if (_bits != null)
{
Contract.Assert(_sign == 1 || _sign == -1 /*, "_sign must be +1 or -1 when _bits is non-null"*/);
Contract.Assert(Length(_bits) > 0 /*, "_bits must contain at least 1 element or be null"*/);
if (Length(_bits) == 1)
Contract.Assert(_bits[0] >= kuMaskHighBit /*, "Wasted space _bits[0] could have been packed into _sign"*/);
}
else
Contract.Assert(_sign > int.MinValue /*, "Int32.MinValue should not be stored in the _sign field"*/);
}
#endregion members supporting exposed properties
// ---- SECTION: public properties --------------*
#region public properties
public static BigInteger Zero
{
get { return s_bnZeroInt; }
}
public static BigInteger One
{
get { return s_bnOneInt; }
}
public static BigInteger MinusOne
{
get { return s_bnMinusOneInt; }
}
public bool IsPowerOfTwo
{
get
{
AssertValid();
if (_bits == null)
return (_sign & (_sign - 1)) == 0 && _sign != 0;
if (_sign != 1)
return false;
int iu = Length(_bits) - 1;
if ((_bits[iu] & (_bits[iu] - 1)) != 0)
return false;
while (--iu >= 0)
{
if (_bits[iu] != 0)
return false;
}
return true;
}
}
public bool IsZero { get { AssertValid(); return _sign == 0; } }
public bool IsOne { get { AssertValid(); return _sign == 1 && _bits == null; } }
public bool IsEven { get { AssertValid(); return _bits == null ? (_sign & 1) == 0 : (_bits[0] & 1) == 0; } }
public int Sign
{
get { AssertValid(); return (_sign >> (kcbitUint - 1)) - (-_sign >> (kcbitUint - 1)); }
}
#endregion public properties
// ---- SECTION: public instance methods --------------*
#region public instance methods
public override bool Equals(object obj)
{
AssertValid();
if (!(obj is BigInteger))
return false;
return Equals((BigInteger)obj);
}
public override int GetHashCode()
{
AssertValid();
if (_bits == null)
return _sign;
int hash = _sign;
for (int iv = Length(_bits); --iv >= 0; )
hash = NumericsHelpers.CombineHash(hash, (int)_bits[iv]);
return hash;
}
public bool Equals(Int64 other)
{
AssertValid();
if (_bits == null)
return _sign == other;
int cu;
if ((_sign ^ other) < 0 || (cu = Length(_bits)) > 2)
return false;
ulong uu = other < 0 ? (ulong)-other : (ulong)other;
if (cu == 1)
return _bits[0] == uu;
return NumericsHelpers.MakeUlong(_bits[1], _bits[0]) == uu;
}
[CLSCompliant(false)]
public bool Equals(UInt64 other)
{
AssertValid();
if (_sign < 0)
return false;
if (_bits == null)
return (ulong)_sign == other;
int cu = Length(_bits);
if (cu > 2)
return false;
if (cu == 1)
return _bits[0] == other;
return NumericsHelpers.MakeUlong(_bits[1], _bits[0]) == other;
}
public bool Equals(BigInteger other)
{
AssertValid();
other.AssertValid();
if (_sign != other._sign)
return false;
if (_bits == other._bits)
// _sign == other._sign && _bits == null && other._bits == null
return true;
if (_bits == null || other._bits == null)
return false;
int cu = Length(_bits);
if (cu != Length(other._bits))
return false;
int cuDiff = GetDiffLength(_bits, other._bits, cu);
return cuDiff == 0;
}
public int CompareTo(Int64 other)
{
AssertValid();
if (_bits == null)
return ((long)_sign).CompareTo(other);
int cu;
if ((_sign ^ other) < 0 || (cu = Length(_bits)) > 2)
return _sign;
ulong uu = other < 0 ? (ulong)-other : (ulong)other;
ulong uuTmp = cu == 2 ? NumericsHelpers.MakeUlong(_bits[1], _bits[0]) : _bits[0];
return _sign * uuTmp.CompareTo(uu);
}
[CLSCompliant(false)]
public int CompareTo(UInt64 other)
{
AssertValid();
if (_sign < 0)
return -1;
if (_bits == null)
return ((ulong)_sign).CompareTo(other);
int cu = Length(_bits);
if (cu > 2)
return +1;
ulong uuTmp = cu == 2 ? NumericsHelpers.MakeUlong(_bits[1], _bits[0]) : _bits[0];
return uuTmp.CompareTo(other);
}
public int CompareTo(BigInteger other)
{
AssertValid();
other.AssertValid();
if ((_sign ^ other._sign) < 0)
{
// Different signs, so the comparison is easy.
return _sign < 0 ? -1 : +1;
}
// Same signs
if (_bits == null)
{
if (other._bits == null)
return _sign < other._sign ? -1 : _sign > other._sign ? +1 : 0;
return -other._sign;
}
int cuThis, cuOther;
if (other._bits == null || (cuThis = Length(_bits)) > (cuOther = Length(other._bits)))
return _sign;
if (cuThis < cuOther)
return -_sign;
int cuDiff = GetDiffLength(_bits, other._bits, cuThis);
if (cuDiff == 0)
return 0;
return _bits[cuDiff - 1] < other._bits[cuDiff - 1] ? -_sign : _sign;
}
public int CompareTo(Object obj)
{
if (obj == null)
return 1;
if (!(obj is BigInteger))
throw new ArgumentException(SR.GetString(SR.Argument_MustBeBigInt));
return this.CompareTo((BigInteger)obj);
}
// Return the value of this BigInteger as a little-endian twos-complement
// byte array, using the fewest number of bytes possible. If the value is zero,
// return an array of one byte whose element is 0x00.
public byte[] ToByteArray() {
if (_bits == null && _sign == 0)
return new byte[] { 0 };
// We could probably make this more efficient by eliminating one of the passes.
// The current code does one pass for uint array -> byte array conversion,
// and then another pass to remove unneeded bytes at the top of the array.
uint[] dwords;
byte highByte;
if (_bits == null) {
dwords = new uint[] { (uint)_sign };
highByte = (byte)((_sign < 0) ? 0xff : 0x00);
}
else if(_sign == -1) {
dwords = (uint[])_bits.Clone();
NumericsHelpers.DangerousMakeTwosComplement(dwords); // mutates dwords
highByte = 0xff;
} else {
dwords = _bits;
highByte = 0x00;
}
byte[] bytes = new byte[checked(4 * dwords.Length)];
int curByte = 0;
uint dword;
for (int i = 0; i < dwords.Length; i++) {
dword = dwords[i];
for (int j = 0; j < 4; j++) {
bytes[curByte++] = (byte)(dword & 0xff);
dword >>= 8;
}
}
// find highest significant byte
int msb;
for (msb = bytes.Length - 1; msb > 0; msb--) {
if (bytes[msb] != highByte) break;
}
// ensure high bit is 0 if positive, 1 if negative
bool needExtraByte = (bytes[msb] & 0x80) != (highByte & 0x80);
byte[] trimmedBytes = new byte[msb + 1 + (needExtraByte ? 1 : 0)];
Array.Copy(bytes, trimmedBytes, msb + 1);
if (needExtraByte) trimmedBytes[trimmedBytes.Length - 1] = highByte;
return trimmedBytes;
}
// Return the value of this BigInteger as a little-endian twos-complement
// uint array, using the fewest number of uints possible. If the value is zero,
// return an array of one uint whose element is 0.
private UInt32[] ToUInt32Array() {
if (_bits == null && _sign == 0)
return new uint[] { 0 };
uint[] dwords;
uint highDWord;
if (_bits == null) {
dwords = new uint[] { (uint)_sign };
highDWord = (_sign < 0) ? UInt32.MaxValue : 0;
}
else if(_sign == -1) {
dwords = (uint[])_bits.Clone();
NumericsHelpers.DangerousMakeTwosComplement(dwords); // mutates dwords
highDWord = UInt32.MaxValue;
} else {
dwords = _bits;
highDWord = 0;
}
// find highest significant byte
int msb;
for (msb = dwords.Length - 1; msb > 0; msb--) {
if (dwords[msb] != highDWord) break;
}
// ensure high bit is 0 if positive, 1 if negative
bool needExtraByte = (dwords[msb] & 0x80000000) != (highDWord & 0x80000000);
uint[] trimmed = new uint[msb + 1 + (needExtraByte ? 1 : 0)];
Array.Copy(dwords, trimmed, msb + 1);
if (needExtraByte) trimmed[trimmed.Length - 1] = highDWord;
return trimmed;
}
public override String ToString() {
return BigNumber.FormatBigInteger(this, null, NumberFormatInfo.CurrentInfo);
}
public String ToString(IFormatProvider provider) {
return BigNumber.FormatBigInteger(this, null, NumberFormatInfo.GetInstance(provider));
}
public String ToString(String format) {
return BigNumber.FormatBigInteger(this, format, NumberFormatInfo.CurrentInfo);
}
public String ToString(String format, IFormatProvider provider) {
return BigNumber.FormatBigInteger(this, format, NumberFormatInfo.GetInstance(provider));
}
#endregion public instance methods
// -------- SECTION: constructors -----------------*
#region constructors
public BigInteger(int value)
{
if (value == Int32.MinValue)
this = s_bnMinInt;
else {
_sign = value;
_bits = null;
}
AssertValid();
}
[CLSCompliant(false)]
public BigInteger(uint value)
{
if (value <= Int32.MaxValue)
{
_sign = (int)value;
_bits = null;
}
else
{
_sign = +1;
_bits = new uint[1];
_bits[0] = value;
}
AssertValid();
}
public BigInteger(Int64 value)
{
if (Int32.MinValue <= value && value <= Int32.MaxValue)
{
if (value == Int32.MinValue)
this = s_bnMinInt;
else
{
_sign = (int)value;
_bits = null;
}
AssertValid();
return;
}
ulong x = 0;
if (value < 0)
{
x = (ulong)-value;
_sign = -1;
}
else
{
Contract.Assert(value != 0);
x = (ulong)value;
_sign = +1;
}
_bits = new uint[2];
_bits[0] = (uint)x;
_bits[1] = (uint)(x >> kcbitUint);
AssertValid();
}
[CLSCompliant(false)]
public BigInteger(UInt64 value)
{
if (value <= Int32.MaxValue)
{
_sign = (int)value;
_bits = null;
}
else
{
_sign = +1;
_bits = new uint[2];
_bits[0] = (uint)value;
_bits[1] = (uint)(value >> kcbitUint);
}
AssertValid();
}
public BigInteger(Single value)
{
if (Single.IsInfinity(value))
throw new OverflowException(SR.GetString(SR.Overflow_BigIntInfinity));
if (Single.IsNaN(value))
throw new OverflowException(SR.GetString(SR.Overflow_NotANumber));
Contract.EndContractBlock();
_sign = 0;
_bits = null;
SetBitsFromDouble(value);
AssertValid();
}
public BigInteger(Double value)
{
if (Double.IsInfinity(value))
throw new OverflowException(SR.GetString(SR.Overflow_BigIntInfinity));
if (Double.IsNaN(value))
throw new OverflowException(SR.GetString(SR.Overflow_NotANumber));
Contract.EndContractBlock();
_sign = 0;
_bits = null;
SetBitsFromDouble(value);
AssertValid();
}
public BigInteger(Decimal value)
{
// First truncate to get scale to 0 and extract bits
int[] bits = Decimal.GetBits(Decimal.Truncate(value));
Contract.Assert(bits.Length == 4 && (bits[3] & DecimalScaleFactorMask) == 0);
int size = 3;
while (size > 0 && bits[size - 1] == 0)
size--;
if (size == 0) {
this = s_bnZeroInt;
}
else if (size == 1 && bits[0] > 0) {
// bits[0] is the absolute value of this decimal
// if bits[0] < 0 then it is too large to be packed into _sign
_sign = bits[0];
_sign *= ((bits[3] & DecimalSignMask) != 0) ? -1 : +1;
_bits = null;
}
else {
_bits = new UInt32[size];
_bits[0] = (UInt32)bits[0];
if (size > 1)
_bits[1] = (UInt32)bits[1];
if (size > 2)
_bits[2] = (UInt32)bits[2];
_sign = ((bits[3] & DecimalSignMask) != 0) ? -1 : +1;
}
AssertValid();
}
[CLSCompliant(false)]
//
// Create a BigInteger from a little-endian twos-complement byte array
//
public BigInteger(Byte[] value)
{
if (value == null)
throw new ArgumentNullException("value");
Contract.EndContractBlock();
int byteCount = value.Length;
bool isNegative = byteCount > 0 && ((value[byteCount - 1] & 0x80) == 0x80);
// Try to conserve space as much as possible by checking for wasted leading byte[] entries
while (byteCount > 0 && value[byteCount-1] == 0) byteCount--;
if (byteCount == 0)
{
// BigInteger.Zero
_sign = 0;
_bits = null;
AssertValid();
return;
}
if (byteCount <= 4)
{
if (isNegative)
_sign = unchecked((int)0xffffffff);
else
_sign = 0;
for (int i = byteCount - 1; i >= 0; i--)
{
_sign <<= 8;
_sign |= value[i];
}
_bits = null;
if (_sign < 0 && !isNegative)
{
// int32 overflow
// example: Int64 value 2362232011 (0xCB, 0xCC, 0xCC, 0x8C, 0x0)
// can be naively packed into 4 bytes (due to the leading 0x0)
// it overflows into the int32 sign bit
_bits = new uint[1];
_bits[0] = (uint)_sign;
_sign = +1;
}
if (_sign == Int32.MinValue)
this = s_bnMinInt;
}
else
{
int unalignedBytes = byteCount % 4;
int dwordCount = byteCount / 4 + (unalignedBytes == 0 ? 0 : 1);
bool isZero = true;
uint[] val = new uint[dwordCount];
// Copy all dwords, except but don't do the last one if it's not a full four bytes
int curDword, curByte, byteInDword;
curByte = 3;
for (curDword = 0; curDword < dwordCount - (unalignedBytes == 0 ? 0 : 1); curDword++) {
byteInDword = 0;
while (byteInDword < 4) {
if (value[curByte] != 0x00) isZero = false;
val[curDword] <<= 8;
val[curDword] |= value[curByte];
curByte--;
byteInDword++;
}
curByte += 8;
}
// Copy the last dword specially if it's not aligned
if (unalignedBytes != 0) {
if (isNegative) val[dwordCount - 1] = 0xffffffff;
for (curByte = byteCount - 1; curByte >= byteCount - unalignedBytes; curByte--) {
if (value[curByte] != 0x00) isZero = false;
val[curDword] <<= 8;
val[curDword] |= value[curByte];
}
}
if (isZero) {
this = s_bnZeroInt;
}
else if (isNegative) {
NumericsHelpers.DangerousMakeTwosComplement(val); // mutates val
// pack _bits to remove any wasted space after the twos complement
int len = val.Length;
while (len > 0 && val[len - 1] == 0)
len--;
if (len == 1 && ((int)(val[0])) > 0) {
if (val[0] == 1 /* abs(-1) */) {
this = s_bnMinusOneInt;
}
else if (val[0] == kuMaskHighBit /* abs(Int32.MinValue) */) {
this = s_bnMinInt;
}
else {
_sign = (-1) * ((int)val[0]);
_bits = null;
}
}
else if (len != val.Length) {
_sign = -1;
_bits = new uint[len];
Array.Copy(val, _bits, len);
}
else {
_sign = -1;
_bits = val;
}
}
else
{
_sign = +1;
_bits = val;
}
}
AssertValid();
}
internal BigInteger(int n, uint[] rgu)
{
_sign = n;
_bits = rgu;
AssertValid();
}
//
// BigInteger(uint[] value, bool negative)
//
// Constructor used during bit manipulation and arithmetic
//
// The uint[] value is expected to be the absolute value of the number
// with the bool negative indicating the Sign of the value.
//
// When possible the uint[] will be packed into _sign to conserve space
//
internal BigInteger(uint[] value, bool negative)
{
if (value == null)
throw new ArgumentNullException("value");
Contract.EndContractBlock();
int len;
// Try to conserve space as much as possible by checking for wasted leading uint[] entries
// sometimes the uint[] has leading zeros from bit manipulation operations & and ^
for(len = value.Length; len > 0 && value[len-1] == 0; len--);
if (len == 0)
this = s_bnZeroInt;
// values like (Int32.MaxValue+1) are stored as "0x80000000" and as such cannot be packed into _sign
else if (len == 1 && value[0] < kuMaskHighBit)
{
_sign = (negative ? -(int)value[0] : (int)value[0]);
_bits = null;
// Although Int32.MinValue fits in _sign, we represent this case differently for negate
if (_sign == Int32.MinValue)
this = s_bnMinInt;
}
else
{
_sign = negative ? -1 : +1;
_bits = new uint[len];
Array.Copy(value, _bits, len);
}
AssertValid();
}
//
// Create a BigInteger from a little-endian twos-complement UInt32 array
// When possible, value is assigned directly to this._bits without an array copy
// so use this ctor with care
//
private BigInteger(uint[] value)
{
if (value == null)
throw new ArgumentNullException("value");
int dwordCount = value.Length;
bool isNegative = dwordCount > 0 && ((value[dwordCount - 1] & 0x80000000) == 0x80000000);
// Try to conserve space as much as possible by checking for wasted leading uint[] entries
while (dwordCount > 0 && value[dwordCount-1] == 0) dwordCount--;
if (dwordCount == 0)
{
// BigInteger.Zero
this = s_bnZeroInt;
AssertValid();
return;
}
if (dwordCount == 1)
{
if ((int)value[0] < 0 && !isNegative) {
_bits = new uint[1];
_bits[0] = value[0];
_sign = +1;
}
// handle the special cases where the BigInteger likely fits into _sign
else if (Int32.MinValue == (int)value[0]) {
this = s_bnMinInt;
}
else {
_sign = (int)value[0];
_bits = null;
}
AssertValid();
return;
}
if (!isNegative) {
// handle the simple postive value cases where the input is already in sign magnitude
if (dwordCount != value.Length) {
_sign = +1;
_bits = new uint[dwordCount];
Array.Copy(value, _bits, dwordCount);
}
// no trimming is possible. Assign value directly to _bits.
else {
_sign = +1;
_bits = value;
}
AssertValid();
return;
}
// finally handle the more complex cases where we must transform the input into sign magnitude
NumericsHelpers.DangerousMakeTwosComplement(value); // mutates val
// pack _bits to remove any wasted space after the twos complement
int len = value.Length;
while (len > 0 && value[len - 1] == 0) len--;
// the number is represented by a single dword
if (len == 1 && ((int)(value[0])) > 0) {
if (value[0] == 1 /* abs(-1) */) {
this = s_bnMinusOneInt;
}
else if (value[0] == kuMaskHighBit /* abs(Int32.MinValue) */) {
this = s_bnMinInt;
}
else {
_sign = (-1) * ((int)value[0]);
_bits = null;
}
}
// the number is represented by multiple dwords
// trim off any wasted uint values when possible
else if (len != value.Length) {
_sign = -1;
_bits = new uint[len];
Array.Copy(value, _bits, len);
}
// no trimming is possible. Assign value directly to _bits.
else {
_sign = -1;
_bits = value;
}
AssertValid();
return;
}
#endregion constructors
// -------- SECTION: public static methods -----------------*
#region public static methods
#if !SILVERLIGHT || FEATURE_NETCORE
public static BigInteger Parse(String value) {
return BigNumber.ParseBigInteger(value, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
}
public static BigInteger Parse(String value, NumberStyles style) {
return BigNumber.ParseBigInteger(value, style, NumberFormatInfo.CurrentInfo);
}
public static BigInteger Parse(String value, IFormatProvider provider) {
return BigNumber.ParseBigInteger(value, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider));
}
public static BigInteger Parse(String value, NumberStyles style, IFormatProvider provider) {
return BigNumber.ParseBigInteger(value, style, NumberFormatInfo.GetInstance(provider));
}
public static Boolean TryParse(String value, out BigInteger result) {
return BigNumber.TryParseBigInteger(value, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
}
public static Boolean TryParse(String value, NumberStyles style, IFormatProvider provider, out BigInteger result) {
return BigNumber.TryParseBigInteger(value, style, NumberFormatInfo.GetInstance(provider), out result);
}
#endif //!SILVERLIGHT || FEATURE_NETCORE
public static Int32 Compare(BigInteger left, BigInteger right)
{
return left.CompareTo(right);
}
public static BigInteger Abs(BigInteger value)
{
return (value >= BigInteger.Zero) ? value : -value;
}
public static BigInteger Add(BigInteger left, BigInteger right)
{
return left + right;
}
public static BigInteger Subtract(BigInteger left, BigInteger right)
{
return left - right;
}
public static BigInteger Multiply(BigInteger left, BigInteger right)
{
return left * right;
}
public static BigInteger Divide(BigInteger dividend, BigInteger divisor)
{
return dividend / divisor;
}
public static BigInteger Remainder(BigInteger dividend, BigInteger divisor)
{
return dividend % divisor;
}
public static BigInteger DivRem(BigInteger dividend, BigInteger divisor, out BigInteger remainder)
{
dividend.AssertValid();
divisor.AssertValid();
int signNum = +1;
int signDen = +1;
BigIntegerBuilder regNum = new BigIntegerBuilder(dividend, ref signNum);
BigIntegerBuilder regDen = new BigIntegerBuilder(divisor, ref signDen);
BigIntegerBuilder regQuo = new BigIntegerBuilder();
// regNum and regQuo are overwritten with the remainder and quotient, respectively
regNum.ModDiv(ref regDen, ref regQuo);
remainder = regNum.GetInteger(signNum);
return regQuo.GetInteger(signNum * signDen);
}
public static BigInteger Negate(BigInteger value)
{
return -value;
}
// Returns the natural (base e) logarithm of a specified number.
public static Double Log(BigInteger value)
{
return BigInteger.Log(value, Math.E);
}
public static Double Log(BigInteger value, Double baseValue)
{
if (value._sign < 0 || baseValue == 1.0D)
return Double.NaN;
if (baseValue == Double.PositiveInfinity)
return value.IsOne ? 0.0D : Double.NaN;
if (baseValue == 0.0D && !value.IsOne)
return Double.NaN;
if (value._bits == null)
return Math.Log((double)value._sign, baseValue);
Double c = 0, d = 0.5D;
const Double log2 = 0.69314718055994529D;
int uintLength = Length(value._bits);
int topbits = BitLengthOfUInt(value._bits[uintLength - 1]);
int bitlen = (uintLength - 1) * kcbitUint + topbits;
uint indbit = (uint)(1 << (topbits - 1));
for(int index = uintLength -1; index >= 0; --index)
{
while (indbit != 0)
{
if ((value._bits[index] & indbit) != 0)
c += d;
d *= 0.5;
indbit >>= 1;
}
indbit = 0x80000000;
}
return (Math.Log(c) + log2 * bitlen) / Math.Log(baseValue);
}
public static Double Log10(BigInteger value)
{
return BigInteger.Log(value, 10);
}
public static BigInteger GreatestCommonDivisor(BigInteger left, BigInteger right)
{
left.AssertValid();
right.AssertValid();
// gcd(0, 0) = 0
// gcd(a, 0) = |a|, for a != 0, since any number is a divisor of 0, and the greatest divisor of a is |a|
if (left._sign == 0) return BigInteger.Abs(right);
if (right._sign == 0) return BigInteger.Abs(left);
BigIntegerBuilder reg1 = new BigIntegerBuilder(left);
BigIntegerBuilder reg2 = new BigIntegerBuilder(right);
BigIntegerBuilder.GCD(ref reg1, ref reg2);
return reg1.GetInteger(+1);
}
public static BigInteger Max(BigInteger left, BigInteger right)
{
if (left.CompareTo(right) < 0)
return right;
return left;
}
public static BigInteger Min(BigInteger left, BigInteger right)
{
if (left.CompareTo(right) <= 0)
return left;
return right;
}
private static void ModPowUpdateResult(ref BigIntegerBuilder regRes, ref BigIntegerBuilder regVal, ref BigIntegerBuilder regMod, ref BigIntegerBuilder regTmp)
{
NumericsHelpers.Swap(ref regRes, ref regTmp);
regRes.Mul(ref regTmp, ref regVal); // result = result * value;
regRes.Mod(ref regMod); // result = result % modulus;
}
private static void ModPowSquareModValue(ref BigIntegerBuilder regVal, ref BigIntegerBuilder regMod, ref BigIntegerBuilder regTmp)
{
NumericsHelpers.Swap(ref regVal, ref regTmp);
regVal.Mul(ref regTmp, ref regTmp); // value = value * value;
regVal.Mod(ref regMod); // value = value % modulus;
}
private static void ModPowInner(uint exp, ref BigIntegerBuilder regRes, ref BigIntegerBuilder regVal, ref BigIntegerBuilder regMod, ref BigIntegerBuilder regTmp)
{
while (exp != 0) // !(Exponent.IsZero)
{
if ((exp & 1) == 1) // !(Exponent.IsEven)
ModPowUpdateResult(ref regRes, ref regVal, ref regMod, ref regTmp);
if (exp == 1) // Exponent.IsOne - we can exit early
break;
ModPowSquareModValue(ref regVal, ref regMod, ref regTmp);
exp >>= 1;
}
}
private static void ModPowInner32(uint exp, ref BigIntegerBuilder regRes, ref BigIntegerBuilder regVal, ref BigIntegerBuilder regMod, ref BigIntegerBuilder regTmp)
{
for (int i = 0; i < 32; i++)
{
if ((exp & 1) == 1) // !(Exponent.IsEven)
ModPowUpdateResult(ref regRes, ref regVal, ref regMod, ref regTmp);
ModPowSquareModValue(ref regVal, ref regMod, ref regTmp);
exp >>= 1;
}
}
public static BigInteger ModPow(BigInteger value, BigInteger exponent, BigInteger modulus)
{
if (exponent.Sign < 0)
throw new ArgumentOutOfRangeException("exponent", SR.GetString(SR.ArgumentOutOfRange_MustBeNonNeg));
Contract.EndContractBlock();
value.AssertValid();
exponent.AssertValid();
modulus.AssertValid();
int signRes = +1;
int signVal = +1;
int signMod = +1;
bool expIsEven = exponent.IsEven;
BigIntegerBuilder regRes = new BigIntegerBuilder(BigInteger.One, ref signRes);
BigIntegerBuilder regVal = new BigIntegerBuilder(value, ref signVal);
BigIntegerBuilder regMod = new BigIntegerBuilder(modulus, ref signMod);
BigIntegerBuilder regTmp = new BigIntegerBuilder(regVal.Size);
regRes.Mod(ref regMod); // Handle special case of exponent=0, modulus=1
if (exponent._bits == null)
{ // exponent fits into an Int32
ModPowInner((uint) exponent._sign, ref regRes, ref regVal, ref regMod, ref regTmp);
}
else
{ // very large exponent
int len = Length(exponent._bits);
for (int i = 0; i < len - 1; i++)
{
uint exp = exponent._bits[i];
ModPowInner32(exp, ref regRes, ref regVal, ref regMod, ref regTmp);
}
ModPowInner(exponent._bits[len - 1], ref regRes, ref regVal, ref regMod, ref regTmp);
}
return regRes.GetInteger(value._sign > 0 ? +1 : expIsEven ? +1 : -1);
}
public static BigInteger Pow(BigInteger value, Int32 exponent)
{
if (exponent < 0)
throw new ArgumentOutOfRangeException("exponent", SR.GetString(SR.ArgumentOutOfRange_MustBeNonNeg));
Contract.EndContractBlock();
value.AssertValid();
if (exponent == 0)
return BigInteger.One;
if (exponent == 1)
return value;
if (value._bits == null)
{
if (value._sign == 1)
return value;
if (value._sign == -1)
return (exponent & 1) != 0 ? value : 1;
if (value._sign == 0)
return value;
}
int sign = +1;
BigIntegerBuilder regSquare = new BigIntegerBuilder(value, ref sign);
// Get an estimate of the size needed for regSquare and regRes, so we can minimize allocations.
int cuSquareMin = regSquare.Size;
int cuSquareMax = cuSquareMin;
uint uSquareMin = regSquare.High;
uint uSquareMax = uSquareMin + 1;
if (uSquareMax == 0)
{
cuSquareMax++;
uSquareMax = 1;
}
int cuResMin = 1;
int cuResMax = 1;
uint uResMin = 1;
uint uResMax = 1;
for (int expTmp = exponent; ; )
{
if ((expTmp & 1) != 0)
{
MulUpper(ref uResMax, ref cuResMax, uSquareMax, cuSquareMax);
MulLower(ref uResMin, ref cuResMin, uSquareMin, cuSquareMin);
}
if ((expTmp >>= 1) == 0)
break;
MulUpper(ref uSquareMax, ref cuSquareMax, uSquareMax, cuSquareMax);
MulLower(ref uSquareMin, ref cuSquareMin, uSquareMin, cuSquareMin);
}
if (cuResMax > 1)
regSquare.EnsureWritable(cuResMax, 0);
BigIntegerBuilder regTmp = new BigIntegerBuilder(cuResMax);
BigIntegerBuilder regRes = new BigIntegerBuilder(cuResMax);
regRes.Set(1);
if ((exponent & 1) == 0)
sign = +1;
for (int expTmp = exponent; ; )
{
if ((expTmp & 1) != 0)
{
NumericsHelpers.Swap(ref regRes, ref regTmp);
regRes.Mul(ref regSquare, ref regTmp);
}
if ((expTmp >>= 1) == 0)
break;
NumericsHelpers.Swap(ref regSquare, ref regTmp);
regSquare.Mul(ref regTmp, ref regTmp);
}
return regRes.GetInteger(sign);
}
#endregion public static methods
// -------- SECTION: public static operators -----------------*
#region public static operators
public static implicit operator BigInteger(Byte value)
{
return new BigInteger(value);
}
[CLSCompliant(false)]
public static implicit operator BigInteger(SByte value)
{
return new BigInteger(value);
}
public static implicit operator BigInteger(Int16 value)
{
return new BigInteger(value);
}
[CLSCompliant(false)]
public static implicit operator BigInteger(UInt16 value)
{
return new BigInteger(value);
}
public static implicit operator BigInteger(int value)
{
return new BigInteger(value);
}
[CLSCompliant(false)]
public static implicit operator BigInteger(uint value)
{
return new BigInteger(value);
}
public static implicit operator BigInteger(long value)
{
return new BigInteger(value);
}
[CLSCompliant(false)]
public static implicit operator BigInteger(ulong value)
{
return new BigInteger(value);
}
public static explicit operator BigInteger(Single value)
{
return new BigInteger(value);
}
public static explicit operator BigInteger(Double value)
{
return new BigInteger(value);
}
public static explicit operator BigInteger(Decimal value)
{
return new BigInteger(value);
}
public static explicit operator Byte(BigInteger value)
{
return checked((byte)((int)value));
}
[CLSCompliant(false)]
public static explicit operator SByte(BigInteger value)
{
return checked((sbyte)((int)value));
}
public static explicit operator Int16(BigInteger value)
{
return checked((short)((int)value));
}
[CLSCompliant(false)]
public static explicit operator UInt16(BigInteger value)
{
return checked((ushort)((int)value));
}
public static explicit operator Int32(BigInteger value)
{
value.AssertValid();
if (value._bits == null) {
return value._sign; // value packed into int32 sign
}
else if (Length(value._bits) > 1) { // more than 32 bits
throw new OverflowException(SR.GetString(SR.Overflow_Int32));
}
else if (value._sign > 0) {
return checked((int)value._bits[0]);
}
else {
if (value._bits[0] > kuMaskHighBit) { // value > Int32.MinValue
throw new OverflowException(SR.GetString(SR.Overflow_Int32));
}
return unchecked(-(int)value._bits[0]);
}
}
[CLSCompliant(false)]
public static explicit operator UInt32(BigInteger value)
{
value.AssertValid();
if (value._bits == null) {
return checked((uint)value._sign);
}
else if (Length(value._bits) > 1 || value._sign < 0) {
throw new OverflowException(SR.GetString(SR.Overflow_UInt32));
}
else {
return value._bits[0];
}
}
public static explicit operator Int64(BigInteger value)
{
value.AssertValid();
if (value._bits == null) {
return value._sign;
}
int len = Length(value._bits);
if (len > 2) {
throw new OverflowException(SR.GetString(SR.Overflow_Int64));
}
ulong uu;
if (len > 1) {
uu = NumericsHelpers.MakeUlong(value._bits[1], value._bits[0]);
}
else {
uu = (ulong)value._bits[0];
}
long ll = value._sign > 0 ? (long)uu : -(long)uu;
if ((ll > 0 && value._sign > 0) || (ll < 0 && value._sign < 0)) {
// signs match, no overflow
return ll;
}
throw new OverflowException(SR.GetString(SR.Overflow_Int64));
}
[CLSCompliant(false)]
public static explicit operator UInt64(BigInteger value)
{
value.AssertValid();
if (value._bits == null) {
return checked((ulong)value._sign);
}
int len = Length(value._bits);
if (len > 2 || value._sign < 0) {
throw new OverflowException(SR.GetString(SR.Overflow_UInt64));
}
if (len > 1) {
return NumericsHelpers.MakeUlong(value._bits[1], value._bits[0]);
}
else {
return value._bits[0];
}
}
public static explicit operator Single(BigInteger value)
{
return (Single)((Double)value);
}
public static explicit operator Double(BigInteger value)
{
value.AssertValid();
if (value._bits == null)
return value._sign;
ulong man;
int exp;
int sign = +1;
BigIntegerBuilder reg = new BigIntegerBuilder(value, ref sign);
reg.GetApproxParts(out exp, out man);
return NumericsHelpers.GetDoubleFromParts(sign, exp, man);
}
public static explicit operator Decimal(BigInteger value)
{
value.AssertValid();
if (value._bits == null)
return (Decimal)value._sign;
int length = Length(value._bits);
if (length > 3) throw new OverflowException(SR.GetString(SR.Overflow_Decimal));
int lo = 0, mi = 0, hi = 0;
if (length > 2) hi = (Int32)value._bits[2];
if (length > 1) mi = (Int32)value._bits[1];
if (length > 0) lo = (Int32)value._bits[0];
return new Decimal(lo, mi, hi, value._sign < 0, 0);
}
public static BigInteger operator &(BigInteger left, BigInteger right) {
if (left.IsZero || right.IsZero) {
return BigInteger.Zero;
}
uint[] x = left.ToUInt32Array();
uint[] y = right.ToUInt32Array();
uint[] z = new uint[Math.Max(x.Length, y.Length)];
uint xExtend = (left._sign < 0) ? UInt32.MaxValue : 0;
uint yExtend = (right._sign < 0) ? UInt32.MaxValue : 0;
for (int i = 0; i < z.Length; i++) {
uint xu = (i < x.Length) ? x[i] : xExtend;
uint yu = (i < y.Length) ? y[i] : yExtend;
z[i] = xu & yu;
}
return new BigInteger(z);
}
public static BigInteger operator |(BigInteger left, BigInteger right) {
if (left.IsZero)
return right;
if (right.IsZero)
return left;
uint[] x = left.ToUInt32Array();
uint[] y = right.ToUInt32Array();
uint[] z = new uint[Math.Max(x.Length, y.Length)];
uint xExtend = (left._sign < 0) ? UInt32.MaxValue : 0;
uint yExtend = (right._sign < 0) ? UInt32.MaxValue : 0;
for (int i = 0; i < z.Length; i++) {
uint xu = (i < x.Length) ? x[i] : xExtend;
uint yu = (i < y.Length) ? y[i] : yExtend;
z[i] = xu | yu;
}
return new BigInteger(z);
}
public static BigInteger operator ^(BigInteger left, BigInteger right) {
uint[] x = left.ToUInt32Array();
uint[] y = right.ToUInt32Array();
uint[] z = new uint[Math.Max(x.Length, y.Length)];
uint xExtend = (left._sign < 0) ? UInt32.MaxValue : 0;
uint yExtend = (right._sign < 0) ? UInt32.MaxValue : 0;
for (int i = 0; i < z.Length; i++) {
uint xu = (i < x.Length) ? x[i] : xExtend;
uint yu = (i < y.Length) ? y[i] : yExtend;
z[i] = xu ^ yu;
}
return new BigInteger(z);
}
public static BigInteger operator <<(BigInteger value, int shift) {
if (shift == 0) return value;
else if (shift == Int32.MinValue) return ((value >> Int32.MaxValue) >> 1);
else if (shift < 0) return value >> -shift;
int digitShift = shift / kcbitUint;
int smallShift = shift - (digitShift * kcbitUint);
uint[] xd; int xl; bool negx;
negx = GetPartsForBitManipulation(ref value, out xd, out xl);
int zl = xl + digitShift + 1;
uint[] zd = new uint[zl];
if (smallShift == 0) {
for (int i = 0; i < xl; i++) {
zd[i + digitShift] = xd[i];
}
} else {
int carryShift = kcbitUint - smallShift;
uint carry = 0;
int i;
for (i = 0; i < xl; i++) {
uint rot = xd[i];
zd[i + digitShift] = rot << smallShift | carry;
carry = rot >> carryShift;
}
zd[i + digitShift] = carry;
}
return new BigInteger(zd, negx);
}
public static BigInteger operator >>(BigInteger value, int shift) {
if (shift == 0) return value;
else if (shift == Int32.MinValue) return ((value << Int32.MaxValue) << 1);
else if (shift < 0) return value << -shift;
int digitShift = shift / kcbitUint;
int smallShift = shift - (digitShift * kcbitUint);
uint[] xd; int xl; bool negx;
negx = GetPartsForBitManipulation(ref value, out xd, out xl);
if (negx) {
if (shift >= (kcbitUint * xl)) {
return BigInteger.MinusOne;
}
uint[] temp = new uint[xl];
Array.Copy(xd /* sourceArray */, temp /* destinationArray */, xl /* length */); // make a copy of immutable value._bits
xd = temp;
NumericsHelpers.DangerousMakeTwosComplement(xd); // mutates xd
}
int zl = xl - digitShift;
if (zl < 0) zl = 0;
uint[] zd = new uint[zl];
if (smallShift == 0) {
for (int i = xl - 1; i >= digitShift; i--) {
zd[i - digitShift] = xd[i];
}
} else {
int carryShift = kcbitUint - smallShift;
uint carry = 0;
for (int i = xl - 1; i >= digitShift; i--) {
uint rot = xd[i];
if (negx && i == xl - 1)
// sign-extend the first shift for negative ints then let the carry propagate
zd[i - digitShift] = (rot >> smallShift) | (0xFFFFFFFF << carryShift);
else
zd[i - digitShift] = (rot >> smallShift) | carry;
carry = rot << carryShift;
}
}
if (negx) {
NumericsHelpers.DangerousMakeTwosComplement(zd); // mutates zd
}
return new BigInteger(zd, negx);
}
public static BigInteger operator ~(BigInteger value) {
return -(value + BigInteger.One);
}
public static BigInteger operator -(BigInteger value)
{
value.AssertValid();
value._sign = -value._sign;
value.AssertValid();
return value;
}
public static BigInteger operator +(BigInteger value)
{
value.AssertValid();
return value;
}
public static BigInteger operator ++(BigInteger value)
{
return value + BigInteger.One;
}
public static BigInteger operator --(BigInteger value)
{
return value - BigInteger.One;
}
public static BigInteger operator +(BigInteger left, BigInteger right)
{
left.AssertValid();
right.AssertValid();
if (right.IsZero) return left;
if (left.IsZero) return right;
int sign1 = +1;
int sign2 = +1;
BigIntegerBuilder reg1 = new BigIntegerBuilder(left, ref sign1);
BigIntegerBuilder reg2 = new BigIntegerBuilder(right, ref sign2);
if (sign1 == sign2)
reg1.Add(ref reg2);
else
reg1.Sub(ref sign1, ref reg2);
return reg1.GetInteger(sign1);
}
public static BigInteger operator -(BigInteger left, BigInteger right)
{
left.AssertValid();
right.AssertValid();
if (right.IsZero) return left;
if (left.IsZero) return -right;
int sign1 = +1;
int sign2 = -1;
BigIntegerBuilder reg1 = new BigIntegerBuilder(left, ref sign1);
BigIntegerBuilder reg2 = new BigIntegerBuilder(right, ref sign2);
if (sign1 == sign2)
reg1.Add(ref reg2);
else
reg1.Sub(ref sign1, ref reg2);
return reg1.GetInteger(sign1);
}
public static BigInteger operator *(BigInteger left, BigInteger right)
{
left.AssertValid();
right.AssertValid();
int sign = +1;
BigIntegerBuilder reg1 = new BigIntegerBuilder(left, ref sign);
BigIntegerBuilder reg2 = new BigIntegerBuilder(right, ref sign);
reg1.Mul(ref reg2);
return reg1.GetInteger(sign);
}
public static BigInteger operator /(BigInteger dividend, BigInteger divisor)
{
dividend.AssertValid();
divisor.AssertValid();
int sign = +1;
BigIntegerBuilder regNum = new BigIntegerBuilder(dividend, ref sign);
BigIntegerBuilder regDen = new BigIntegerBuilder(divisor, ref sign);
regNum.Div(ref regDen);
return regNum.GetInteger(sign);
}
public static BigInteger operator %(BigInteger dividend, BigInteger divisor)
{
dividend.AssertValid();
divisor.AssertValid();
int signNum = +1;
int signDen = +1;
BigIntegerBuilder regNum = new BigIntegerBuilder(dividend, ref signNum);
BigIntegerBuilder regDen = new BigIntegerBuilder(divisor, ref signDen);
regNum.Mod(ref regDen);
return regNum.GetInteger(signNum);
}
public static bool operator <(BigInteger left, BigInteger right)
{
return left.CompareTo(right) < 0;
}
public static bool operator <=(BigInteger left, BigInteger right)
{
return left.CompareTo(right) <= 0;
}
public static bool operator >(BigInteger left, BigInteger right)
{
return left.CompareTo(right) > 0;
}
public static bool operator >=(BigInteger left, BigInteger right)
{
return left.CompareTo(right) >= 0;
}
public static bool operator ==(BigInteger left, BigInteger right)
{
return left.Equals(right);
}
public static bool operator !=(BigInteger left, BigInteger right)
{
return !left.Equals(right);
}
public static bool operator <(BigInteger left, Int64 right)
{
return left.CompareTo(right) < 0;
}
public static bool operator <=(BigInteger left, Int64 right)
{
return left.CompareTo(right) <= 0;
}
public static bool operator >(BigInteger left, Int64 right)
{
return left.CompareTo(right) > 0;
}
public static bool operator >=(BigInteger left, Int64 right)
{
return left.CompareTo(right) >= 0;
}
public static bool operator ==(BigInteger left, Int64 right)
{
return left.Equals(right);
}
public static bool operator !=(BigInteger left, Int64 right)
{
return !left.Equals(right);
}
public static bool operator <(Int64 left, BigInteger right)
{
return right.CompareTo(left) > 0;
}
public static bool operator <=(Int64 left, BigInteger right)
{
return right.CompareTo(left) >= 0;
}
public static bool operator >(Int64 left, BigInteger right)
{
return right.CompareTo(left) < 0;
}
public static bool operator >=(Int64 left, BigInteger right)
{
return right.CompareTo(left) <= 0;
}
public static bool operator ==(Int64 left, BigInteger right)
{
return right.Equals(left);
}
public static bool operator !=(Int64 left, BigInteger right)
{
return !right.Equals(left);
}
[CLSCompliant(false)]
public static bool operator <(BigInteger left, UInt64 right)
{
return left.CompareTo(right) < 0;
}
[CLSCompliant(false)]
public static bool operator <=(BigInteger left, UInt64 right)
{
return left.CompareTo(right) <= 0;
}
[CLSCompliant(false)]
public static bool operator >(BigInteger left, UInt64 right)
{
return left.CompareTo(right) > 0;
}
[CLSCompliant(false)]
public static bool operator >=(BigInteger left, UInt64 right)
{
return left.CompareTo(right) >= 0;
}
[CLSCompliant(false)]
public static bool operator ==(BigInteger left, UInt64 right)
{
return left.Equals(right);
}
[CLSCompliant(false)]
public static bool operator !=(BigInteger left, UInt64 right)
{
return !left.Equals(right);
}
[CLSCompliant(false)]
public static bool operator <(UInt64 left, BigInteger right)
{
return right.CompareTo(left) > 0;
}
[CLSCompliant(false)]
public static bool operator <=(UInt64 left, BigInteger right)
{
return right.CompareTo(left) >= 0;
}
[CLSCompliant(false)]
public static bool operator >(UInt64 left, BigInteger right)
{
return right.CompareTo(left) < 0;
}
[CLSCompliant(false)]
public static bool operator >=(UInt64 left, BigInteger right)
{
return right.CompareTo(left) <= 0;
}
[CLSCompliant(false)]
public static bool operator ==(UInt64 left, BigInteger right)
{
return right.Equals(left);
}
[CLSCompliant(false)]
public static bool operator !=(UInt64 left, BigInteger right)
{
return !right.Equals(left);
}
#endregion public static operators
// ----- SECTION: private serialization instance methods ----------------
#region private serialization instance methods
#endregion private serialization instance methods
// ----- SECTION: internal instance utility methods ----------------*
#region internal instance utility methods
private void SetBitsFromDouble(Double value)
{
int sign, exp;
ulong man;
bool fFinite;
NumericsHelpers.GetDoubleParts(value, out sign, out exp, out man, out fFinite);
Contract.Assert(sign == +1 || sign == -1);
if (man == 0)
{
this = BigInteger.Zero;
return;
}
Contract.Assert(man < (1UL << 53));
Contract.Assert(exp <= 0 || man >= (1UL << 52));
if (exp <= 0)
{
if (exp <= -kcbitUlong)
{
this = BigInteger.Zero;
return;
}
this = man >> -exp;
if (sign < 0)
_sign = -_sign;
}
else if (exp <= 11)
{
this = man << exp;
if (sign < 0)
_sign = -_sign;
}
else
{
// Overflow into at least 3 uints.
// Move the leading 1 to the high bit.
man <<= 11;
exp -= 11;
// Compute cu and cbit so that exp == 32 * cu - cbit and 0 <= cbit < 32.
int cu = (exp - 1) / kcbitUint + 1;
int cbit = cu * kcbitUint - exp;
Contract.Assert(0 <= cbit && cbit < kcbitUint);
Contract.Assert(cu >= 1);
// Populate the uints.
_bits = new uint[cu + 2];
_bits[cu + 1] = (uint)(man >> (cbit + kcbitUint));
_bits[cu] = (uint)(man >> cbit);
if (cbit > 0)
_bits[cu - 1] = (uint)man << (kcbitUint - cbit);
_sign = sign;
}
}
#endregion internal instance utility methods
// ----- SECTION: internal static utility methods ----------------*
#region internal static utility methods
[Pure]
internal static int Length(uint[] rgu)
{
int cu = rgu.Length;
if (rgu[cu - 1] != 0)
return cu;
Contract.Assert(cu >= 2 && rgu[cu - 2] != 0);
return cu - 1;
}
internal int _Sign { get { return _sign; } }
internal uint[] _Bits { get { return _bits; } }
internal static int BitLengthOfUInt(uint x)
{
int numBits = 0;
while (x > 0)
{
x >>= 1;
numBits++;
}
return numBits;
}
//
// GetPartsForBitManipulation -
//
// Encapsulate the logic of normalizing the "small" and "large" forms of BigInteger
// into the "large" form so that Bit Manipulation algorithms can be simplified
//
// uint[] xd = the UInt32 array containing the entire big integer in "large" (denormalized) form
// E.g., the number one (1) and negative one (-1) are both stored as 0x00000001
// BigInteger values Int32.MinValue < x <= Int32.MaxValue are converted to this
// format for convenience.
// int xl = the length of xd
// return bool = true for negative numbers
//
private static bool GetPartsForBitManipulation(ref BigInteger x, out uint[] xd, out int xl) {
if (x._bits == null) {
if (x._sign < 0) {
xd = new uint[] {(uint)-x._sign};
}
else {
xd = new uint[] {(uint)x._sign};
}
}
else {
xd = x._bits;
}
xl = (x._bits == null ? 1 : x._bits.Length);
return x._sign < 0;
}
// Gets an upper bound on the product of uHiRes * (2^32)^(cuRes-1) and uHiMul * (2^32)^(cuMul-1).
// The result is put int uHiRes and cuRes.
private static void MulUpper(ref uint uHiRes, ref int cuRes, uint uHiMul, int cuMul)
{
ulong uu = (ulong)uHiRes * uHiMul;
uint uHi = NumericsHelpers.GetHi(uu);
if (uHi != 0)
{
if (NumericsHelpers.GetLo(uu) != 0 && ++uHi == 0)
{
uHi = 1;
cuRes++;
}
uHiRes = uHi;
cuRes += cuMul;
}
else
{
uHiRes = NumericsHelpers.GetLo(uu);
cuRes += cuMul - 1;
}
}
// Gets a lower bound on the product of uHiRes * (2^32)^(cuRes-1) and uHiMul * (2^32)^(cuMul-1).
// The result is put int uHiRes and cuRes.
private static void MulLower(ref uint uHiRes, ref int cuRes, uint uHiMul, int cuMul)
{
ulong uu = (ulong)uHiRes * uHiMul;
uint uHi = NumericsHelpers.GetHi(uu);
if (uHi != 0)
{
uHiRes = uHi;
cuRes += cuMul;
}
else
{
uHiRes = NumericsHelpers.GetLo(uu);
cuRes += cuMul - 1;
}
}
internal static int GetDiffLength(uint[] rgu1, uint[] rgu2, int cu)
{
for (int iv = cu; --iv >= 0; )
{
if (rgu1[iv] != rgu2[iv])
return iv + 1;
}
return 0;
}
#endregion internal static utility methods
}
}
|