PageRenderTime 66ms CodeModel.GetById 27ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/otp.net/Otp/Erlang/BigInteger.cs

https://github.com/bmizerany/jungerl
C# | 3333 lines | 1919 code | 721 blank | 693 comment | 674 complexity | 75c7f6133aee4dce19b6a0a13598d502 MD5 | raw file
Possible License(s): LGPL-2.1, BSD-3-Clause, AGPL-1.0

Large files files are truncated, but you can click here to view the full file

  1. //************************************************************************************
  2. // BigInteger Class Version 1.03
  3. //
  4. // Copyright (c) 2002 Chew Keong TAN
  5. // All rights reserved.
  6. //
  7. // Permission is hereby granted, free of charge, to any person obtaining a
  8. // copy of this software and associated documentation files (the
  9. // "Software"), to deal in the Software without restriction, including
  10. // without limitation the rights to use, copy, modify, merge, publish,
  11. // distribute, and/or sell copies of the Software, and to permit persons
  12. // to whom the Software is furnished to do so, provided that the above
  13. // copyright notice(s) and this permission notice appear in all copies of
  14. // the Software and that both the above copyright notice(s) and this
  15. // permission notice appear in supporting documentation.
  16. //
  17. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  18. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  19. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
  20. // OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
  21. // HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
  22. // INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
  23. // FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
  24. // NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
  25. // WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  26. //
  27. //
  28. // Disclaimer
  29. // ----------
  30. // Although reasonable care has been taken to ensure the correctness of this
  31. // implementation, this code should never be used in any application without
  32. // proper verification and testing. I disclaim all liability and responsibility
  33. // to any person or entity with respect to any loss or damage caused, or alleged
  34. // to be caused, directly or indirectly, by the use of this BigInteger class.
  35. //
  36. // Comments, bugs and suggestions to
  37. // (http://www.codeproject.com/csharp/biginteger.asp)
  38. //
  39. //
  40. // Overloaded Operators +, -, *, /, %, >>, <<, ==, !=, >, <, >=, <=, &, |, ^, ++, --, ~
  41. //
  42. // Features
  43. // --------
  44. // 1) Arithmetic operations involving large signed integers (2's complement).
  45. // 2) Primality test using Fermat little theorm, Rabin Miller's method,
  46. // Solovay Strassen's method and Lucas strong pseudoprime.
  47. // 3) Modulo exponential with Barrett's reduction.
  48. // 4) Inverse modulo.
  49. // 5) Pseudo prime generation.
  50. // 6) Co-prime generation.
  51. //
  52. //
  53. // Known Problem
  54. // -------------
  55. // This pseudoprime passes my implementation of
  56. // primality test but failed in JDK's isProbablePrime test.
  57. //
  58. // byte[] pseudoPrime1 = { (byte)0x00,
  59. // (byte)0x85, (byte)0x84, (byte)0x64, (byte)0xFD, (byte)0x70, (byte)0x6A,
  60. // (byte)0x9F, (byte)0xF0, (byte)0x94, (byte)0x0C, (byte)0x3E, (byte)0x2C,
  61. // (byte)0x74, (byte)0x34, (byte)0x05, (byte)0xC9, (byte)0x55, (byte)0xB3,
  62. // (byte)0x85, (byte)0x32, (byte)0x98, (byte)0x71, (byte)0xF9, (byte)0x41,
  63. // (byte)0x21, (byte)0x5F, (byte)0x02, (byte)0x9E, (byte)0xEA, (byte)0x56,
  64. // (byte)0x8D, (byte)0x8C, (byte)0x44, (byte)0xCC, (byte)0xEE, (byte)0xEE,
  65. // (byte)0x3D, (byte)0x2C, (byte)0x9D, (byte)0x2C, (byte)0x12, (byte)0x41,
  66. // (byte)0x1E, (byte)0xF1, (byte)0xC5, (byte)0x32, (byte)0xC3, (byte)0xAA,
  67. // (byte)0x31, (byte)0x4A, (byte)0x52, (byte)0xD8, (byte)0xE8, (byte)0xAF,
  68. // (byte)0x42, (byte)0xF4, (byte)0x72, (byte)0xA1, (byte)0x2A, (byte)0x0D,
  69. // (byte)0x97, (byte)0xB1, (byte)0x31, (byte)0xB3,
  70. // };
  71. //
  72. //
  73. // Change Log
  74. // ----------
  75. // 1) September 23, 2002 (Version 1.03)
  76. // - Fixed operator- to give correct data length.
  77. // - Added Lucas sequence generation.
  78. // - Added Strong Lucas Primality test.
  79. // - Added integer square root method.
  80. // - Added setBit/unsetBit methods.
  81. // - New isProbablePrime() method which do not require the
  82. // confident parameter.
  83. //
  84. // 2) August 29, 2002 (Version 1.02)
  85. // - Fixed bug in the exponentiation of negative numbers.
  86. // - Faster modular exponentiation using Barrett reduction.
  87. // - Added getBytes() method.
  88. // - Fixed bug in ToHexString method.
  89. // - Added overloading of ^ operator.
  90. // - Faster computation of Jacobi symbol.
  91. //
  92. // 3) August 19, 2002 (Version 1.01)
  93. // - Big integer is stored and manipulated as unsigned integers (4 bytes) instead of
  94. // individual bytes this gives significant performance improvement.
  95. // - Updated Fermat's Little Theorem test to use a^(p-1) mod p = 1
  96. // - Added isProbablePrime method.
  97. // - Updated documentation.
  98. //
  99. // 4) August 9, 2002 (Version 1.0)
  100. // - Initial Release.
  101. //
  102. //
  103. // References
  104. // [1] D. E. Knuth, "Seminumerical Algorithms", The Art of Computer Programming Vol. 2,
  105. // 3rd Edition, Addison-Wesley, 1998.
  106. //
  107. // [2] K. H. Rosen, "Elementary Number Theory and Its Applications", 3rd Ed,
  108. // Addison-Wesley, 1993.
  109. //
  110. // [3] B. Schneier, "Applied Cryptography", 2nd Ed, John Wiley & Sons, 1996.
  111. //
  112. // [4] A. Menezes, P. van Oorschot, and S. Vanstone, "Handbook of Applied Cryptography",
  113. // CRC Press, 1996, www.cacr.math.uwaterloo.ca/hac
  114. //
  115. // [5] A. Bosselaers, R. Govaerts, and J. Vandewalle, "Comparison of Three Modular
  116. // Reduction Functions," Proc. CRYPTO'93, pp.175-186.
  117. //
  118. // [6] R. Baillie and S. S. Wagstaff Jr, "Lucas Pseudoprimes", Mathematics of Computation,
  119. // Vol. 35, No. 152, Oct 1980, pp. 1391-1417.
  120. //
  121. // [7] H. C. Williams, "Édouard Lucas and Primality Testing", Canadian Mathematical
  122. // Society Series of Monographs and Advance Texts, vol. 22, John Wiley & Sons, New York,
  123. // NY, 1998.
  124. //
  125. // [8] P. Ribenboim, "The new book of prime number records", 3rd edition, Springer-Verlag,
  126. // New York, NY, 1995.
  127. //
  128. // [9] M. Joye and J.-J. Quisquater, "Efficient computation of full Lucas sequences",
  129. // Electronics Letters, 32(6), 1996, pp 537-538.
  130. //
  131. //************************************************************************************
  132. using System;
  133. public class BigInteger
  134. {
  135. // maximum length of the BigInteger in uint (4 bytes)
  136. // change this to suit the required level of precision.
  137. private const int maxLength = 70;
  138. // primes smaller than 2000 to test the generated prime number
  139. public static readonly int[] primesBelow2000 = {
  140. 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97,
  141. 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199,
  142. 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293,
  143. 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397,
  144. 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499,
  145. 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599,
  146. 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691,
  147. 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797,
  148. 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887,
  149. 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997,
  150. 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097,
  151. 1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163, 1171, 1181, 1187, 1193,
  152. 1201, 1213, 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291, 1297,
  153. 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399,
  154. 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499,
  155. 1511, 1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583, 1597,
  156. 1601, 1607, 1609, 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667, 1669, 1693, 1697, 1699,
  157. 1709, 1721, 1723, 1733, 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789,
  158. 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877, 1879, 1889,
  159. 1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997, 1999 };
  160. private uint[] data = null; // stores bytes from the Big Integer
  161. public int dataLength; // number of actual chars used
  162. //***********************************************************************
  163. // Constructor (Default value for BigInteger is 0
  164. //***********************************************************************
  165. public BigInteger()
  166. {
  167. data = new uint[maxLength];
  168. dataLength = 1;
  169. }
  170. //***********************************************************************
  171. // Constructor (Default value provided by long)
  172. //***********************************************************************
  173. public BigInteger(long value)
  174. {
  175. data = new uint[maxLength];
  176. long tempVal = value;
  177. // copy bytes from long to BigInteger without any assumption of
  178. // the length of the long datatype
  179. dataLength = 0;
  180. while(value != 0 && dataLength < maxLength)
  181. {
  182. data[dataLength] = (uint)(value & 0xFFFFFFFF);
  183. value >>= 32;
  184. dataLength++;
  185. }
  186. if(tempVal > 0) // overflow check for +ve value
  187. {
  188. if(value != 0 || (data[maxLength-1] & 0x80000000) != 0)
  189. throw(new ArithmeticException("Positive overflow in constructor."));
  190. }
  191. else if(tempVal < 0) // underflow check for -ve value
  192. {
  193. if(value != -1 || (data[dataLength-1] & 0x80000000) == 0)
  194. throw(new ArithmeticException("Negative underflow in constructor."));
  195. }
  196. if(dataLength == 0)
  197. dataLength = 1;
  198. }
  199. //***********************************************************************
  200. // Constructor (Default value provided by ulong)
  201. //***********************************************************************
  202. public BigInteger(ulong value)
  203. {
  204. data = new uint[maxLength];
  205. // copy bytes from ulong to BigInteger without any assumption of
  206. // the length of the ulong datatype
  207. dataLength = 0;
  208. while(value != 0 && dataLength < maxLength)
  209. {
  210. data[dataLength] = (uint)(value & 0xFFFFFFFF);
  211. value >>= 32;
  212. dataLength++;
  213. }
  214. if(value != 0 || (data[maxLength-1] & 0x80000000) != 0)
  215. throw(new ArithmeticException("Positive overflow in constructor."));
  216. if(dataLength == 0)
  217. dataLength = 1;
  218. }
  219. //***********************************************************************
  220. // Constructor (Default value provided by BigInteger)
  221. //***********************************************************************
  222. public BigInteger(BigInteger bi)
  223. {
  224. data = new uint[maxLength];
  225. dataLength = bi.dataLength;
  226. for(int i = 0; i < dataLength; i++)
  227. data[i] = bi.data[i];
  228. }
  229. //***********************************************************************
  230. // Constructor (Default value provided by a string of digits of the
  231. // specified base)
  232. //
  233. // Example (base 10)
  234. // -----------------
  235. // To initialize "a" with the default value of 1234 in base 10
  236. // BigInteger a = new BigInteger("1234", 10)
  237. //
  238. // To initialize "a" with the default value of -1234
  239. // BigInteger a = new BigInteger("-1234", 10)
  240. //
  241. // Example (base 16)
  242. // -----------------
  243. // To initialize "a" with the default value of 0x1D4F in base 16
  244. // BigInteger a = new BigInteger("1D4F", 16)
  245. //
  246. // To initialize "a" with the default value of -0x1D4F
  247. // BigInteger a = new BigInteger("-1D4F", 16)
  248. //
  249. // Note that string values are specified in the <sign><magnitude>
  250. // format.
  251. //
  252. //***********************************************************************
  253. public BigInteger(string value, int radix)
  254. {
  255. BigInteger multiplier = new BigInteger(1);
  256. BigInteger result = new BigInteger();
  257. value = (value.ToUpper()).Trim();
  258. int limit = 0;
  259. if(value[0] == '-')
  260. limit = 1;
  261. for(int i = value.Length - 1; i >= limit ; i--)
  262. {
  263. int posVal = (int)value[i];
  264. if(posVal >= '0' && posVal <= '9')
  265. posVal -= '0';
  266. else if(posVal >= 'A' && posVal <= 'Z')
  267. posVal = (posVal - 'A') + 10;
  268. else
  269. posVal = 9999999; // arbitrary large
  270. if(posVal >= radix)
  271. throw(new ArithmeticException("Invalid string in constructor."));
  272. else
  273. {
  274. if(value[0] == '-')
  275. posVal = -posVal;
  276. result = result + (multiplier * posVal);
  277. if((i - 1) >= limit)
  278. multiplier = multiplier * radix;
  279. }
  280. }
  281. if(value[0] == '-') // negative values
  282. {
  283. if((result.data[maxLength-1] & 0x80000000) == 0)
  284. throw(new ArithmeticException("Negative underflow in constructor."));
  285. }
  286. else // positive values
  287. {
  288. if((result.data[maxLength-1] & 0x80000000) != 0)
  289. throw(new ArithmeticException("Positive overflow in constructor."));
  290. }
  291. data = new uint[maxLength];
  292. for(int i = 0; i < result.dataLength; i++)
  293. data[i] = result.data[i];
  294. dataLength = result.dataLength;
  295. }
  296. //***********************************************************************
  297. // Constructor (Default value provided by an array of bytes)
  298. //
  299. // The lowest index of the input byte array (i.e [0]) should contain the
  300. // most significant byte of the number, and the highest index should
  301. // contain the least significant byte.
  302. //
  303. // E.g.
  304. // To initialize "a" with the default value of 0x1D4F in base 16
  305. // byte[] temp = { 0x1D, 0x4F };
  306. // BigInteger a = new BigInteger(temp)
  307. //
  308. // Note that this method of initialization does not allow the
  309. // sign to be specified.
  310. //
  311. //***********************************************************************
  312. public BigInteger(byte[] inData)
  313. {
  314. dataLength = inData.Length >> 2;
  315. int leftOver = inData.Length & 0x3;
  316. if(leftOver != 0) // length not multiples of 4
  317. dataLength++;
  318. if(dataLength > maxLength)
  319. throw(new ArithmeticException("Byte overflow in constructor."));
  320. data = new uint[maxLength];
  321. for(int i = inData.Length - 1, j = 0; i >= 3; i -= 4, j++)
  322. {
  323. data[j] = (uint)((inData[i-3] << 24) + (inData[i-2] << 16) +
  324. (inData[i-1] << 8) + inData[i]);
  325. }
  326. if(leftOver == 1)
  327. data[dataLength-1] = (uint)inData[0];
  328. else if(leftOver == 2)
  329. data[dataLength-1] = (uint)((inData[0] << 8) + inData[1]);
  330. else if(leftOver == 3)
  331. data[dataLength-1] = (uint)((inData[0] << 16) + (inData[1] << 8) + inData[2]);
  332. while(dataLength > 1 && data[dataLength-1] == 0)
  333. dataLength--;
  334. //Console.WriteLine("Len = " + dataLength);
  335. }
  336. //***********************************************************************
  337. // Constructor (Default value provided by an array of bytes of the
  338. // specified length.)
  339. //***********************************************************************
  340. public BigInteger(byte[] inData, int inLen)
  341. {
  342. dataLength = inLen >> 2;
  343. int leftOver = inLen & 0x3;
  344. if(leftOver != 0) // length not multiples of 4
  345. dataLength++;
  346. if(dataLength > maxLength || inLen > inData.Length)
  347. throw(new ArithmeticException("Byte overflow in constructor."));
  348. data = new uint[maxLength];
  349. for(int i = inLen - 1, j = 0; i >= 3; i -= 4, j++)
  350. {
  351. data[j] = (uint)((inData[i-3] << 24) + (inData[i-2] << 16) +
  352. (inData[i-1] << 8) + inData[i]);
  353. }
  354. if(leftOver == 1)
  355. data[dataLength-1] = (uint)inData[0];
  356. else if(leftOver == 2)
  357. data[dataLength-1] = (uint)((inData[0] << 8) + inData[1]);
  358. else if(leftOver == 3)
  359. data[dataLength-1] = (uint)((inData[0] << 16) + (inData[1] << 8) + inData[2]);
  360. if(dataLength == 0)
  361. dataLength = 1;
  362. while(dataLength > 1 && data[dataLength-1] == 0)
  363. dataLength--;
  364. //Console.WriteLine("Len = " + dataLength);
  365. }
  366. //***********************************************************************
  367. // Constructor (Default value provided by an array of unsigned integers)
  368. //*********************************************************************
  369. public BigInteger(uint[] inData)
  370. {
  371. dataLength = inData.Length;
  372. if(dataLength > maxLength)
  373. throw(new ArithmeticException("Byte overflow in constructor."));
  374. data = new uint[maxLength];
  375. for(int i = dataLength - 1, j = 0; i >= 0; i--, j++)
  376. data[j] = inData[i];
  377. while(dataLength > 1 && data[dataLength-1] == 0)
  378. dataLength--;
  379. //Console.WriteLine("Len = " + dataLength);
  380. }
  381. //***********************************************************************
  382. // Overloading of the typecast operator.
  383. // For BigInteger bi = 10;
  384. //***********************************************************************
  385. public static implicit operator BigInteger(long value)
  386. {
  387. return (new BigInteger(value));
  388. }
  389. public static implicit operator BigInteger(ulong value)
  390. {
  391. return (new BigInteger(value));
  392. }
  393. public static implicit operator BigInteger(int value)
  394. {
  395. return (new BigInteger((long)value));
  396. }
  397. public static implicit operator BigInteger(uint value)
  398. {
  399. return (new BigInteger((ulong)value));
  400. }
  401. //***********************************************************************
  402. // Overloading of addition operator
  403. //***********************************************************************
  404. public static BigInteger operator +(BigInteger bi1, BigInteger bi2)
  405. {
  406. BigInteger result = new BigInteger();
  407. result.dataLength = (bi1.dataLength > bi2.dataLength) ? bi1.dataLength : bi2.dataLength;
  408. long carry = 0;
  409. for(int i = 0; i < result.dataLength; i++)
  410. {
  411. long sum = (long)bi1.data[i] + (long)bi2.data[i] + carry;
  412. carry = sum >> 32;
  413. result.data[i] = (uint)(sum & 0xFFFFFFFF);
  414. }
  415. if(carry != 0 && result.dataLength < maxLength)
  416. {
  417. result.data[result.dataLength] = (uint)(carry);
  418. result.dataLength++;
  419. }
  420. while(result.dataLength > 1 && result.data[result.dataLength-1] == 0)
  421. result.dataLength--;
  422. // overflow check
  423. int lastPos = maxLength - 1;
  424. if((bi1.data[lastPos] & 0x80000000) == (bi2.data[lastPos] & 0x80000000) &&
  425. (result.data[lastPos] & 0x80000000) != (bi1.data[lastPos] & 0x80000000))
  426. {
  427. throw (new ArithmeticException());
  428. }
  429. return result;
  430. }
  431. //***********************************************************************
  432. // Overloading of the unary ++ operator
  433. //***********************************************************************
  434. public static BigInteger operator ++(BigInteger bi1)
  435. {
  436. BigInteger result = new BigInteger(bi1);
  437. long val, carry = 1;
  438. int index = 0;
  439. while(carry != 0 && index < maxLength)
  440. {
  441. val = (long)(result.data[index]);
  442. val++;
  443. result.data[index] = (uint)(val & 0xFFFFFFFF);
  444. carry = val >> 32;
  445. index++;
  446. }
  447. if(index > result.dataLength)
  448. result.dataLength = index;
  449. else
  450. {
  451. while(result.dataLength > 1 && result.data[result.dataLength-1] == 0)
  452. result.dataLength--;
  453. }
  454. // overflow check
  455. int lastPos = maxLength - 1;
  456. // overflow if initial value was +ve but ++ caused a sign
  457. // change to negative.
  458. if((bi1.data[lastPos] & 0x80000000) == 0 &&
  459. (result.data[lastPos] & 0x80000000) != (bi1.data[lastPos] & 0x80000000))
  460. {
  461. throw (new ArithmeticException("Overflow in ++."));
  462. }
  463. return result;
  464. }
  465. //***********************************************************************
  466. // Overloading of subtraction operator
  467. //***********************************************************************
  468. public static BigInteger operator -(BigInteger bi1, BigInteger bi2)
  469. {
  470. BigInteger result = new BigInteger();
  471. result.dataLength = (bi1.dataLength > bi2.dataLength) ? bi1.dataLength : bi2.dataLength;
  472. long carryIn = 0;
  473. for(int i = 0; i < result.dataLength; i++)
  474. {
  475. long diff;
  476. diff = (long)bi1.data[i] - (long)bi2.data[i] - carryIn;
  477. result.data[i] = (uint)(diff & 0xFFFFFFFF);
  478. if(diff < 0)
  479. carryIn = 1;
  480. else
  481. carryIn = 0;
  482. }
  483. // roll over to negative
  484. if(carryIn != 0)
  485. {
  486. for(int i = result.dataLength; i < maxLength; i++)
  487. result.data[i] = 0xFFFFFFFF;
  488. result.dataLength = maxLength;
  489. }
  490. // fixed in v1.03 to give correct datalength for a - (-b)
  491. while(result.dataLength > 1 && result.data[result.dataLength-1] == 0)
  492. result.dataLength--;
  493. // overflow check
  494. int lastPos = maxLength - 1;
  495. if((bi1.data[lastPos] & 0x80000000) != (bi2.data[lastPos] & 0x80000000) &&
  496. (result.data[lastPos] & 0x80000000) != (bi1.data[lastPos] & 0x80000000))
  497. {
  498. throw (new ArithmeticException());
  499. }
  500. return result;
  501. }
  502. //***********************************************************************
  503. // Overloading of the unary -- operator
  504. //***********************************************************************
  505. public static BigInteger operator --(BigInteger bi1)
  506. {
  507. BigInteger result = new BigInteger(bi1);
  508. long val;
  509. bool carryIn = true;
  510. int index = 0;
  511. while(carryIn && index < maxLength)
  512. {
  513. val = (long)(result.data[index]);
  514. val--;
  515. result.data[index] = (uint)(val & 0xFFFFFFFF);
  516. if(val >= 0)
  517. carryIn = false;
  518. index++;
  519. }
  520. if(index > result.dataLength)
  521. result.dataLength = index;
  522. while(result.dataLength > 1 && result.data[result.dataLength-1] == 0)
  523. result.dataLength--;
  524. // overflow check
  525. int lastPos = maxLength - 1;
  526. // overflow if initial value was -ve but -- caused a sign
  527. // change to positive.
  528. if((bi1.data[lastPos] & 0x80000000) != 0 &&
  529. (result.data[lastPos] & 0x80000000) != (bi1.data[lastPos] & 0x80000000))
  530. {
  531. throw (new ArithmeticException("Underflow in --."));
  532. }
  533. return result;
  534. }
  535. //***********************************************************************
  536. // Overloading of multiplication operator
  537. //***********************************************************************
  538. public static BigInteger operator *(BigInteger bi1, BigInteger bi2)
  539. {
  540. int lastPos = maxLength-1;
  541. bool bi1Neg = false, bi2Neg = false;
  542. // take the absolute value of the inputs
  543. try
  544. {
  545. if((bi1.data[lastPos] & 0x80000000) != 0) // bi1 negative
  546. {
  547. bi1Neg = true; bi1 = -bi1;
  548. }
  549. if((bi2.data[lastPos] & 0x80000000) != 0) // bi2 negative
  550. {
  551. bi2Neg = true; bi2 = -bi2;
  552. }
  553. }
  554. catch(Exception) {}
  555. BigInteger result = new BigInteger();
  556. // multiply the absolute values
  557. try
  558. {
  559. for(int i = 0; i < bi1.dataLength; i++)
  560. {
  561. if(bi1.data[i] == 0) continue;
  562. ulong mcarry = 0;
  563. for(int j = 0, k = i; j < bi2.dataLength; j++, k++)
  564. {
  565. // k = i + j
  566. ulong val = ((ulong)bi1.data[i] * (ulong)bi2.data[j]) +
  567. (ulong)result.data[k] + mcarry;
  568. result.data[k] = (uint)(val & 0xFFFFFFFF);
  569. mcarry = (val >> 32);
  570. }
  571. if(mcarry != 0)
  572. result.data[i+bi2.dataLength] = (uint)mcarry;
  573. }
  574. }
  575. catch(Exception)
  576. {
  577. throw(new ArithmeticException("Multiplication overflow."));
  578. }
  579. result.dataLength = bi1.dataLength + bi2.dataLength;
  580. if(result.dataLength > maxLength)
  581. result.dataLength = maxLength;
  582. while(result.dataLength > 1 && result.data[result.dataLength-1] == 0)
  583. result.dataLength--;
  584. // overflow check (result is -ve)
  585. if((result.data[lastPos] & 0x80000000) != 0)
  586. {
  587. if(bi1Neg != bi2Neg && result.data[lastPos] == 0x80000000) // different sign
  588. {
  589. // handle the special case where multiplication produces
  590. // a max negative number in 2's complement.
  591. if(result.dataLength == 1)
  592. return result;
  593. else
  594. {
  595. bool isMaxNeg = true;
  596. for(int i = 0; i < result.dataLength - 1 && isMaxNeg; i++)
  597. {
  598. if(result.data[i] != 0)
  599. isMaxNeg = false;
  600. }
  601. if(isMaxNeg)
  602. return result;
  603. }
  604. }
  605. throw(new ArithmeticException("Multiplication overflow."));
  606. }
  607. // if input has different signs, then result is -ve
  608. if(bi1Neg != bi2Neg)
  609. return -result;
  610. return result;
  611. }
  612. //***********************************************************************
  613. // Overloading of unary << operators
  614. //***********************************************************************
  615. public static BigInteger operator <<(BigInteger bi1, int shiftVal)
  616. {
  617. BigInteger result = new BigInteger(bi1);
  618. result.dataLength = shiftLeft(result.data, shiftVal);
  619. return result;
  620. }
  621. // least significant bits at lower part of buffer
  622. private static int shiftLeft(uint[] buffer, int shiftVal)
  623. {
  624. int shiftAmount = 32;
  625. int bufLen = buffer.Length;
  626. while(bufLen > 1 && buffer[bufLen-1] == 0)
  627. bufLen--;
  628. for(int count = shiftVal; count > 0;)
  629. {
  630. if(count < shiftAmount)
  631. shiftAmount = count;
  632. //Console.WriteLine("shiftAmount = {0}", shiftAmount);
  633. ulong carry = 0;
  634. for(int i = 0; i < bufLen; i++)
  635. {
  636. ulong val = ((ulong)buffer[i]) << shiftAmount;
  637. val |= carry;
  638. buffer[i] = (uint)(val & 0xFFFFFFFF);
  639. carry = val >> 32;
  640. }
  641. if(carry != 0)
  642. {
  643. if(bufLen + 1 <= buffer.Length)
  644. {
  645. buffer[bufLen] = (uint)carry;
  646. bufLen++;
  647. }
  648. }
  649. count -= shiftAmount;
  650. }
  651. return bufLen;
  652. }
  653. //***********************************************************************
  654. // Overloading of unary >> operators
  655. //***********************************************************************
  656. public static BigInteger operator >>(BigInteger bi1, int shiftVal)
  657. {
  658. BigInteger result = new BigInteger(bi1);
  659. result.dataLength = shiftRight(result.data, shiftVal);
  660. if((bi1.data[maxLength-1] & 0x80000000) != 0) // negative
  661. {
  662. for(int i = maxLength - 1; i >= result.dataLength; i--)
  663. result.data[i] = 0xFFFFFFFF;
  664. uint mask = 0x80000000;
  665. for(int i = 0; i < 32; i++)
  666. {
  667. if((result.data[result.dataLength-1] & mask) != 0)
  668. break;
  669. result.data[result.dataLength-1] |= mask;
  670. mask >>= 1;
  671. }
  672. result.dataLength = maxLength;
  673. }
  674. return result;
  675. }
  676. private static int shiftRight(uint[] buffer, int shiftVal)
  677. {
  678. int shiftAmount = 32;
  679. int invShift = 0;
  680. int bufLen = buffer.Length;
  681. while(bufLen > 1 && buffer[bufLen-1] == 0)
  682. bufLen--;
  683. //Console.WriteLine("bufLen = " + bufLen + " buffer.Length = " + buffer.Length);
  684. for(int count = shiftVal; count > 0;)
  685. {
  686. if(count < shiftAmount)
  687. {
  688. shiftAmount = count;
  689. invShift = 32 - shiftAmount;
  690. }
  691. //Console.WriteLine("shiftAmount = {0}", shiftAmount);
  692. ulong carry = 0;
  693. for(int i = bufLen - 1; i >= 0; i--)
  694. {
  695. ulong val = ((ulong)buffer[i]) >> shiftAmount;
  696. val |= carry;
  697. carry = ((ulong)buffer[i]) << invShift;
  698. buffer[i] = (uint)(val);
  699. }
  700. count -= shiftAmount;
  701. }
  702. while(bufLen > 1 && buffer[bufLen-1] == 0)
  703. bufLen--;
  704. return bufLen;
  705. }
  706. //***********************************************************************
  707. // Overloading of the NOT operator (1's complement)
  708. //***********************************************************************
  709. public static BigInteger operator ~(BigInteger bi1)
  710. {
  711. BigInteger result = new BigInteger(bi1);
  712. for(int i = 0; i < maxLength; i++)
  713. result.data[i] = (uint)(~(bi1.data[i]));
  714. result.dataLength = maxLength;
  715. while(result.dataLength > 1 && result.data[result.dataLength-1] == 0)
  716. result.dataLength--;
  717. return result;
  718. }
  719. //***********************************************************************
  720. // Overloading of the NEGATE operator (2's complement)
  721. //***********************************************************************
  722. public static BigInteger operator -(BigInteger bi1)
  723. {
  724. // handle neg of zero separately since it'll cause an overflow
  725. // if we proceed.
  726. if(bi1.dataLength == 1 && bi1.data[0] == 0)
  727. return (new BigInteger());
  728. BigInteger result = new BigInteger(bi1);
  729. // 1's complement
  730. for(int i = 0; i < maxLength; i++)
  731. result.data[i] = (uint)(~(bi1.data[i]));
  732. // add one to result of 1's complement
  733. long val, carry = 1;
  734. int index = 0;
  735. while(carry != 0 && index < maxLength)
  736. {
  737. val = (long)(result.data[index]);
  738. val++;
  739. result.data[index] = (uint)(val & 0xFFFFFFFF);
  740. carry = val >> 32;
  741. index++;
  742. }
  743. if((bi1.data[maxLength-1] & 0x80000000) == (result.data[maxLength-1] & 0x80000000))
  744. throw (new ArithmeticException("Overflow in negation.\n"));
  745. result.dataLength = maxLength;
  746. while(result.dataLength > 1 && result.data[result.dataLength-1] == 0)
  747. result.dataLength--;
  748. return result;
  749. }
  750. //***********************************************************************
  751. // Overloading of equality operator
  752. //***********************************************************************
  753. public static bool operator ==(BigInteger bi1, BigInteger bi2)
  754. {
  755. return bi1.Equals(bi2);
  756. }
  757. public static bool operator !=(BigInteger bi1, BigInteger bi2)
  758. {
  759. return !(bi1.Equals(bi2));
  760. }
  761. public override bool Equals(object o)
  762. {
  763. BigInteger bi = (BigInteger)o;
  764. if(this.dataLength != bi.dataLength)
  765. return false;
  766. for(int i = 0; i < this.dataLength; i++)
  767. {
  768. if(this.data[i] != bi.data[i])
  769. return false;
  770. }
  771. return true;
  772. }
  773. public override int GetHashCode()
  774. {
  775. return this.ToString().GetHashCode();
  776. }
  777. //***********************************************************************
  778. // Overloading of inequality operator
  779. //***********************************************************************
  780. public static bool operator >(BigInteger bi1, BigInteger bi2)
  781. {
  782. int pos = maxLength - 1;
  783. // bi1 is negative, bi2 is positive
  784. if((bi1.data[pos] & 0x80000000) != 0 && (bi2.data[pos] & 0x80000000) == 0)
  785. return false;
  786. // bi1 is positive, bi2 is negative
  787. else if((bi1.data[pos] & 0x80000000) == 0 && (bi2.data[pos] & 0x80000000) != 0)
  788. return true;
  789. // same sign
  790. int len = (bi1.dataLength > bi2.dataLength) ? bi1.dataLength : bi2.dataLength;
  791. for(pos = len - 1; pos >= 0 && bi1.data[pos] == bi2.data[pos]; pos--);
  792. if(pos >= 0)
  793. {
  794. if(bi1.data[pos] > bi2.data[pos])
  795. return true;
  796. return false;
  797. }
  798. return false;
  799. }
  800. public static bool operator <(BigInteger bi1, BigInteger bi2)
  801. {
  802. int pos = maxLength - 1;
  803. // bi1 is negative, bi2 is positive
  804. if((bi1.data[pos] & 0x80000000) != 0 && (bi2.data[pos] & 0x80000000) == 0)
  805. return true;
  806. // bi1 is positive, bi2 is negative
  807. else if((bi1.data[pos] & 0x80000000) == 0 && (bi2.data[pos] & 0x80000000) != 0)
  808. return false;
  809. // same sign
  810. int len = (bi1.dataLength > bi2.dataLength) ? bi1.dataLength : bi2.dataLength;
  811. for(pos = len - 1; pos >= 0 && bi1.data[pos] == bi2.data[pos]; pos--);
  812. if(pos >= 0)
  813. {
  814. if(bi1.data[pos] < bi2.data[pos])
  815. return true;
  816. return false;
  817. }
  818. return false;
  819. }
  820. public static bool operator >=(BigInteger bi1, BigInteger bi2)
  821. {
  822. return (bi1 == bi2 || bi1 > bi2);
  823. }
  824. public static bool operator <=(BigInteger bi1, BigInteger bi2)
  825. {
  826. return (bi1 == bi2 || bi1 < bi2);
  827. }
  828. //***********************************************************************
  829. // Private function that supports the division of two numbers with
  830. // a divisor that has more than 1 digit.
  831. //
  832. // Algorithm taken from [1]
  833. //***********************************************************************
  834. private static void multiByteDivide(BigInteger bi1, BigInteger bi2,
  835. BigInteger outQuotient, BigInteger outRemainder)
  836. {
  837. uint[] result = new uint[maxLength];
  838. int remainderLen = bi1.dataLength + 1;
  839. uint[] remainder = new uint[remainderLen];
  840. uint mask = 0x80000000;
  841. uint val = bi2.data[bi2.dataLength - 1];
  842. int shift = 0, resultPos = 0;
  843. while(mask != 0 && (val & mask) == 0)
  844. {
  845. shift++; mask >>= 1;
  846. }
  847. //Console.WriteLine("shift = {0}", shift);
  848. //Console.WriteLine("Before bi1 Len = {0}, bi2 Len = {1}", bi1.dataLength, bi2.dataLength);
  849. for(int i = 0; i < bi1.dataLength; i++)
  850. remainder[i] = bi1.data[i];
  851. shiftLeft(remainder, shift);
  852. bi2 = bi2 << shift;
  853. /*
  854. Console.WriteLine("bi1 Len = {0}, bi2 Len = {1}", bi1.dataLength, bi2.dataLength);
  855. Console.WriteLine("dividend = " + bi1 + "\ndivisor = " + bi2);
  856. for(int q = remainderLen - 1; q >= 0; q--)
  857. Console.Write("{0:x2}", remainder[q]);
  858. Console.WriteLine();
  859. */
  860. int j = remainderLen - bi2.dataLength;
  861. int pos = remainderLen - 1;
  862. ulong firstDivisorByte = bi2.data[bi2.dataLength-1];
  863. ulong secondDivisorByte = bi2.data[bi2.dataLength-2];
  864. int divisorLen = bi2.dataLength + 1;
  865. uint[] dividendPart = new uint[divisorLen];
  866. while(j > 0)
  867. {
  868. ulong dividend = ((ulong)remainder[pos] << 32) + (ulong)remainder[pos-1];
  869. //Console.WriteLine("dividend = {0}", dividend);
  870. ulong q_hat = dividend / firstDivisorByte;
  871. ulong r_hat = dividend % firstDivisorByte;
  872. //Console.WriteLine("q_hat = {0:X}, r_hat = {1:X}", q_hat, r_hat);
  873. bool done = false;
  874. while(!done)
  875. {
  876. done = true;
  877. if(q_hat == 0x100000000 ||
  878. (q_hat * secondDivisorByte) > ((r_hat << 32) + remainder[pos-2]))
  879. {
  880. q_hat--;
  881. r_hat += firstDivisorByte;
  882. if(r_hat < 0x100000000)
  883. done = false;
  884. }
  885. }
  886. for(int h = 0; h < divisorLen; h++)
  887. dividendPart[h] = remainder[pos-h];
  888. BigInteger kk = new BigInteger(dividendPart);
  889. BigInteger ss = bi2 * (long)q_hat;
  890. //Console.WriteLine("ss before = " + ss);
  891. while(ss > kk)
  892. {
  893. q_hat--;
  894. ss -= bi2;
  895. //Console.WriteLine(ss);
  896. }
  897. BigInteger yy = kk - ss;
  898. //Console.WriteLine("ss = " + ss);
  899. //Console.WriteLine("kk = " + kk);
  900. //Console.WriteLine("yy = " + yy);
  901. for(int h = 0; h < divisorLen; h++)
  902. remainder[pos-h] = yy.data[bi2.dataLength-h];
  903. /*
  904. Console.WriteLine("dividend = ");
  905. for(int q = remainderLen - 1; q >= 0; q--)
  906. Console.Write("{0:x2}", remainder[q]);
  907. Console.WriteLine("\n************ q_hat = {0:X}\n", q_hat);
  908. */
  909. result[resultPos++] = (uint)q_hat;
  910. pos--;
  911. j--;
  912. }
  913. outQuotient.dataLength = resultPos;
  914. int y = 0;
  915. for(int x = outQuotient.dataLength - 1; x >= 0; x--, y++)
  916. outQuotient.data[y] = result[x];
  917. for(; y < maxLength; y++)
  918. outQuotient.data[y] = 0;
  919. while(outQuotient.dataLength > 1 && outQuotient.data[outQuotient.dataLength-1] == 0)
  920. outQuotient.dataLength--;
  921. if(outQuotient.dataLength == 0)
  922. outQuotient.dataLength = 1;
  923. outRemainder.dataLength = shiftRight(remainder, shift);
  924. for(y = 0; y < outRemainder.dataLength; y++)
  925. outRemainder.data[y] = remainder[y];
  926. for(; y < maxLength; y++)
  927. outRemainder.data[y] = 0;
  928. }
  929. //***********************************************************************
  930. // Private function that supports the division of two numbers with
  931. // a divisor that has only 1 digit.
  932. //***********************************************************************
  933. private static void singleByteDivide(BigInteger bi1, BigInteger bi2,
  934. BigInteger outQuotient, BigInteger outRemainder)
  935. {
  936. uint[] result = new uint[maxLength];
  937. int resultPos = 0;
  938. // copy dividend to reminder
  939. for(int i = 0; i < maxLength; i++)
  940. outRemainder.data[i] = bi1.data[i];
  941. outRemainder.dataLength = bi1.dataLength;
  942. while(outRemainder.dataLength > 1 && outRemainder.data[outRemainder.dataLength-1] == 0)
  943. outRemainder.dataLength--;
  944. ulong divisor = (ulong)bi2.data[0];
  945. int pos = outRemainder.dataLength - 1;
  946. ulong dividend = (ulong)outRemainder.data[pos];
  947. //Console.WriteLine("divisor = " + divisor + " dividend = " + dividend);
  948. //Console.WriteLine("divisor = " + bi2 + "\ndividend = " + bi1);
  949. if(dividend >= divisor)
  950. {
  951. ulong quotient = dividend / divisor;
  952. result[resultPos++] = (uint)quotient;
  953. outRemainder.data[pos] = (uint)(dividend % divisor);
  954. }
  955. pos--;
  956. while(pos >= 0)
  957. {
  958. //Console.WriteLine(pos);
  959. dividend = ((ulong)outRemainder.data[pos+1] << 32) + (ulong)outRemainder.data[pos];
  960. ulong quotient = dividend / divisor;
  961. result[resultPos++] = (uint)quotient;
  962. outRemainder.data[pos+1] = 0;
  963. outRemainder.data[pos--] = (uint)(dividend % divisor);
  964. //Console.WriteLine(">>>> " + bi1);
  965. }
  966. outQuotient.dataLength = resultPos;
  967. int j = 0;
  968. for(int i = outQuotient.dataLength - 1; i >= 0; i--, j++)
  969. outQuotient.data[j] = result[i];
  970. for(; j < maxLength; j++)
  971. outQuotient.data[j] = 0;
  972. while(outQuotient.dataLength > 1 && outQuotient.data[outQuotient.dataLength-1] == 0)
  973. outQuotient.dataLength--;
  974. if(outQuotient.dataLength == 0)
  975. outQuotient.dataLength = 1;
  976. while(outRemainder.dataLength > 1 && outRemainder.data[outRemainder.dataLength-1] == 0)
  977. outRemainder.dataLength--;
  978. }
  979. //***********************************************************************
  980. // Overloading of division operator
  981. //***********************************************************************
  982. public static BigInteger operator /(BigInteger bi1, BigInteger bi2)
  983. {
  984. BigInteger quotient = new BigInteger();
  985. BigInteger remainder = new BigInteger();
  986. int lastPos = maxLength-1;
  987. bool divisorNeg = false, dividendNeg = false;
  988. if((bi1.data[lastPos] & 0x80000000) != 0) // bi1 negative
  989. {
  990. bi1 = -bi1;
  991. dividendNeg = true;
  992. }
  993. if((bi2.data[lastPos] & 0x80000000) != 0) // bi2 negative
  994. {
  995. bi2 = -bi2;
  996. divisorNeg = true;
  997. }
  998. if(bi1 < bi2)
  999. {
  1000. return quotient;
  1001. }
  1002. else
  1003. {
  1004. if(bi2.dataLength == 1)
  1005. singleByteDivide(bi1, bi2, quotient, remainder);
  1006. else
  1007. multiByteDivide(bi1, bi2, quotient, remainder);
  1008. if(dividendNeg != divisorNeg)
  1009. return -quotient;
  1010. return quotient;
  1011. }
  1012. }
  1013. //***********************************************************************
  1014. // Overloading of modulus operator
  1015. //***********************************************************************
  1016. public static BigInteger operator %(BigInteger bi1, BigInteger bi2)
  1017. …

Large files files are truncated, but you can click here to view the full file