BigInt.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  1. // BigInt, a suite of routines for performing multiple-precision arithmetic in
  2. // JavaScript.
  3. //
  4. // Copyright 1998-2005 David Shapiro.
  5. //
  6. // You may use, re-use, abuse,
  7. // copy, and modify this code to your liking, but please keep this header.
  8. // Thanks!
  9. //
  10. // Dave Shapiro
  11. // dave@ohdave.com
  12. // IMPORTANT THING: Be sure to set maxDigits according to your precision
  13. // needs. Use the setMaxDigits() function to do this. See comments below.
  14. //
  15. // Tweaked by Ian Bunning
  16. // Alterations:
  17. // Fix bug in function biFromHex(s) to allow
  18. // parsing of strings of length != 0 (mod 4)
  19. // Changes made by Dave Shapiro as of 12/30/2004:
  20. //
  21. // The BigInt() constructor doesn't take a string anymore. If you want to
  22. // create a BigInt from a string, use biFromDecimal() for base-10
  23. // representations, biFromHex() for base-16 representations, or
  24. // biFromString() for base-2-to-36 representations.
  25. //
  26. // biFromArray() has been removed. Use biCopy() instead, passing a BigInt
  27. // instead of an array.
  28. //
  29. // The BigInt() constructor now only constructs a zeroed-out array.
  30. // Alternatively, if you pass <true>, it won't construct any array. See the
  31. // biCopy() method for an example of this.
  32. //
  33. // Be sure to set maxDigits depending on your precision needs. The default
  34. // zeroed-out array ZERO_ARRAY is constructed inside the setMaxDigits()
  35. // function. So use this function to set the variable. DON'T JUST SET THE
  36. // VALUE. USE THE FUNCTION.
  37. //
  38. // ZERO_ARRAY exists to hopefully speed up construction of BigInts(). By
  39. // precalculating the zero array, we can just use slice(0) to make copies of
  40. // it. Presumably this calls faster native code, as opposed to setting the
  41. // elements one at a time. I have not done any timing tests to verify this
  42. // claim.
  43. // Max number = 10^16 - 2 = 9999999999999998;
  44. // 2^53 = 9007199254740992;
  45. var biRadixBase = 2;
  46. var biRadixBits = 16;
  47. var bitsPerDigit = biRadixBits;
  48. var biRadix = 1 << 16; // = 2^16 = 65536
  49. var biHalfRadix = biRadix >>> 1;
  50. var biRadixSquared = biRadix * biRadix;
  51. var maxDigitVal = biRadix - 1;
  52. var maxInteger = 9999999999999998;
  53. // maxDigits:
  54. // Change this to accommodate your largest number size. Use setMaxDigits()
  55. // to change it!
  56. //
  57. // In general, if you're working with numbers of size N bits, you'll need 2*N
  58. // bits of storage. Each digit holds 16 bits. So, a 1024-bit key will need
  59. //
  60. // 1024 * 2 / 16 = 128 digits of storage.
  61. //
  62. var maxDigits;
  63. var ZERO_ARRAY;
  64. var bigZero, bigOne;
  65. function setMaxDigits(value)
  66. {
  67. maxDigits = value;
  68. ZERO_ARRAY = new Array(maxDigits);
  69. for (var iza = 0; iza < ZERO_ARRAY.length; iza++) ZERO_ARRAY[iza] = 0;
  70. bigZero = new BigInt();
  71. bigOne = new BigInt();
  72. bigOne.digits[0] = 1;
  73. }
  74. setMaxDigits(20);
  75. // The maximum number of digits in base 10 you can convert to an
  76. // integer without JavaScript throwing up on you.
  77. var dpl10 = 15;
  78. // lr10 = 10 ^ dpl10
  79. var lr10 = biFromNumber(1000000000000000);
  80. function BigInt(flag)
  81. {
  82. if (typeof flag == "boolean" && flag == true) {
  83. this.digits = null;
  84. }
  85. else {
  86. this.digits = ZERO_ARRAY.slice(0);
  87. }
  88. this.isNeg = false;
  89. }
  90. function biFromDecimal(s)
  91. {
  92. var isNeg = s.charAt(0) == '-';
  93. var i = isNeg ? 1 : 0;
  94. var result;
  95. // Skip leading zeros.
  96. while (i < s.length && s.charAt(i) == '0') ++i;
  97. if (i == s.length) {
  98. result = new BigInt();
  99. }
  100. else {
  101. var digitCount = s.length - i;
  102. var fgl = digitCount % dpl10;
  103. if (fgl == 0) fgl = dpl10;
  104. result = biFromNumber(Number(s.substr(i, fgl)));
  105. i += fgl;
  106. while (i < s.length) {
  107. result = biAdd(biMultiply(result, lr10),
  108. biFromNumber(Number(s.substr(i, dpl10))));
  109. i += dpl10;
  110. }
  111. result.isNeg = isNeg;
  112. }
  113. return result;
  114. }
  115. function biCopy(bi)
  116. {
  117. var result = new BigInt(true);
  118. result.digits = bi.digits.slice(0);
  119. result.isNeg = bi.isNeg;
  120. return result;
  121. }
  122. function biFromNumber(i)
  123. {
  124. var result = new BigInt();
  125. result.isNeg = i < 0;
  126. i = Math.abs(i);
  127. var j = 0;
  128. while (i > 0) {
  129. result.digits[j++] = i & maxDigitVal;
  130. i = Math.floor(i / biRadix);
  131. }
  132. return result;
  133. }
  134. function reverseStr(s)
  135. {
  136. var result = "";
  137. for (var i = s.length - 1; i > -1; --i) {
  138. result += s.charAt(i);
  139. }
  140. return result;
  141. }
  142. var hexatrigesimalToChar = new Array(
  143. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  144. 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
  145. 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
  146. 'u', 'v', 'w', 'x', 'y', 'z'
  147. );
  148. function biToString(x, radix)
  149. // 2 <= radix <= 36
  150. {
  151. var b = new BigInt();
  152. b.digits[0] = radix;
  153. var qr = biDivideModulo(x, b);
  154. var result = hexatrigesimalToChar[qr[1].digits[0]];
  155. while (biCompare(qr[0], bigZero) == 1) {
  156. qr = biDivideModulo(qr[0], b);
  157. digit = qr[1].digits[0];
  158. result += hexatrigesimalToChar[qr[1].digits[0]];
  159. }
  160. return (x.isNeg ? "-" : "") + reverseStr(result);
  161. }
  162. function biToDecimal(x)
  163. {
  164. var b = new BigInt();
  165. b.digits[0] = 10;
  166. var qr = biDivideModulo(x, b);
  167. var result = String(qr[1].digits[0]);
  168. while (biCompare(qr[0], bigZero) == 1) {
  169. qr = biDivideModulo(qr[0], b);
  170. result += String(qr[1].digits[0]);
  171. }
  172. return (x.isNeg ? "-" : "") + reverseStr(result);
  173. }
  174. var hexToChar = new Array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  175. 'a', 'b', 'c', 'd', 'e', 'f');
  176. function digitToHex(n)
  177. {
  178. var mask = 0xf;
  179. var result = "";
  180. for (i = 0; i < 4; ++i) {
  181. result += hexToChar[n & mask];
  182. n >>>= 4;
  183. }
  184. return reverseStr(result);
  185. }
  186. function biToHex(x)
  187. {
  188. var result = "";
  189. var n = biHighIndex(x);
  190. for (var i = biHighIndex(x); i > -1; --i) {
  191. result += digitToHex(x.digits[i]);
  192. }
  193. return result;
  194. }
  195. function charToHex(c)
  196. {
  197. var ZERO = 48;
  198. var NINE = ZERO + 9;
  199. var littleA = 97;
  200. var littleZ = littleA + 25;
  201. var bigA = 65;
  202. var bigZ = 65 + 25;
  203. var result;
  204. if (c >= ZERO && c <= NINE) {
  205. result = c - ZERO;
  206. } else if (c >= bigA && c <= bigZ) {
  207. result = 10 + c - bigA;
  208. } else if (c >= littleA && c <= littleZ) {
  209. result = 10 + c - littleA;
  210. } else {
  211. result = 0;
  212. }
  213. return result;
  214. }
  215. function hexToDigit(s)
  216. {
  217. var result = 0;
  218. var sl = Math.min(s.length, 4);
  219. for (var i = 0; i < sl; ++i) {
  220. result <<= 4;
  221. result |= charToHex(s.charCodeAt(i))
  222. }
  223. return result;
  224. }
  225. function biFromHex(s)
  226. {
  227. var result = new BigInt();
  228. var sl = s.length;
  229. for (var i = sl, j = 0; i > 0; i -= 4, ++j) {
  230. result.digits[j] = hexToDigit(s.substr(Math.max(i - 4, 0), Math.min(i, 4)));
  231. }
  232. return result;
  233. }
  234. function biFromString(s, radix)
  235. {
  236. var isNeg = s.charAt(0) == '-';
  237. var istop = isNeg ? 1 : 0;
  238. var result = new BigInt();
  239. var place = new BigInt();
  240. place.digits[0] = 1; // radix^0
  241. for (var i = s.length - 1; i >= istop; i--) {
  242. var c = s.charCodeAt(i);
  243. var digit = charToHex(c);
  244. var biDigit = biMultiplyDigit(place, digit);
  245. result = biAdd(result, biDigit);
  246. place = biMultiplyDigit(place, radix);
  247. }
  248. result.isNeg = isNeg;
  249. return result;
  250. }
  251. function biDump(b)
  252. {
  253. return (b.isNeg ? "-" : "") + b.digits.join(" ");
  254. }
  255. function biAdd(x, y)
  256. {
  257. var result;
  258. if (x.isNeg != y.isNeg) {
  259. y.isNeg = !y.isNeg;
  260. result = biSubtract(x, y);
  261. y.isNeg = !y.isNeg;
  262. }
  263. else {
  264. result = new BigInt();
  265. var c = 0;
  266. var n;
  267. for (var i = 0; i < x.digits.length; ++i) {
  268. n = x.digits[i] + y.digits[i] + c;
  269. result.digits[i] = n % biRadix;
  270. c = Number(n >= biRadix);
  271. }
  272. result.isNeg = x.isNeg;
  273. }
  274. return result;
  275. }
  276. function biSubtract(x, y)
  277. {
  278. var result;
  279. if (x.isNeg != y.isNeg) {
  280. y.isNeg = !y.isNeg;
  281. result = biAdd(x, y);
  282. y.isNeg = !y.isNeg;
  283. } else {
  284. result = new BigInt();
  285. var n, c;
  286. c = 0;
  287. for (var i = 0; i < x.digits.length; ++i) {
  288. n = x.digits[i] - y.digits[i] + c;
  289. result.digits[i] = n % biRadix;
  290. // Stupid non-conforming modulus operation.
  291. if (result.digits[i] < 0) result.digits[i] += biRadix;
  292. c = 0 - Number(n < 0);
  293. }
  294. // Fix up the negative sign, if any.
  295. if (c == -1) {
  296. c = 0;
  297. for (var i = 0; i < x.digits.length; ++i) {
  298. n = 0 - result.digits[i] + c;
  299. result.digits[i] = n % biRadix;
  300. // Stupid non-conforming modulus operation.
  301. if (result.digits[i] < 0) result.digits[i] += biRadix;
  302. c = 0 - Number(n < 0);
  303. }
  304. // Result is opposite sign of arguments.
  305. result.isNeg = !x.isNeg;
  306. } else {
  307. // Result is same sign.
  308. result.isNeg = x.isNeg;
  309. }
  310. }
  311. return result;
  312. }
  313. function biHighIndex(x)
  314. {
  315. var result = x.digits.length - 1;
  316. while (result > 0 && x.digits[result] == 0) --result;
  317. return result;
  318. }
  319. function biNumBits(x)
  320. {
  321. var n = biHighIndex(x);
  322. var d = x.digits[n];
  323. var m = (n + 1) * bitsPerDigit;
  324. var result;
  325. for (result = m; result > m - bitsPerDigit; --result) {
  326. if ((d & 0x8000) != 0) break;
  327. d <<= 1;
  328. }
  329. return result;
  330. }
  331. function biMultiply(x, y)
  332. {
  333. var result = new BigInt();
  334. var c;
  335. var n = biHighIndex(x);
  336. var t = biHighIndex(y);
  337. var u, uv, k;
  338. for (var i = 0; i <= t; ++i) {
  339. c = 0;
  340. k = i;
  341. for (j = 0; j <= n; ++j, ++k) {
  342. uv = result.digits[k] + x.digits[j] * y.digits[i] + c;
  343. result.digits[k] = uv & maxDigitVal;
  344. c = uv >>> biRadixBits;
  345. //c = Math.floor(uv / biRadix);
  346. }
  347. result.digits[i + n + 1] = c;
  348. }
  349. // Someone give me a logical xor, please.
  350. result.isNeg = x.isNeg != y.isNeg;
  351. return result;
  352. }
  353. function biMultiplyDigit(x, y)
  354. {
  355. var n, c, uv;
  356. result = new BigInt();
  357. n = biHighIndex(x);
  358. c = 0;
  359. for (var j = 0; j <= n; ++j) {
  360. uv = result.digits[j] + x.digits[j] * y + c;
  361. result.digits[j] = uv & maxDigitVal;
  362. c = uv >>> biRadixBits;
  363. //c = Math.floor(uv / biRadix);
  364. }
  365. result.digits[1 + n] = c;
  366. return result;
  367. }
  368. function arrayCopy(src, srcStart, dest, destStart, n)
  369. {
  370. var m = Math.min(srcStart + n, src.length);
  371. for (var i = srcStart, j = destStart; i < m; ++i, ++j) {
  372. dest[j] = src[i];
  373. }
  374. }
  375. var highBitMasks = new Array(0x0000, 0x8000, 0xC000, 0xE000, 0xF000, 0xF800,
  376. 0xFC00, 0xFE00, 0xFF00, 0xFF80, 0xFFC0, 0xFFE0,
  377. 0xFFF0, 0xFFF8, 0xFFFC, 0xFFFE, 0xFFFF);
  378. function biShiftLeft(x, n)
  379. {
  380. var digitCount = Math.floor(n / bitsPerDigit);
  381. var result = new BigInt();
  382. arrayCopy(x.digits, 0, result.digits, digitCount,
  383. result.digits.length - digitCount);
  384. var bits = n % bitsPerDigit;
  385. var rightBits = bitsPerDigit - bits;
  386. for (var i = result.digits.length - 1, i1 = i - 1; i > 0; --i, --i1) {
  387. result.digits[i] = ((result.digits[i] << bits) & maxDigitVal) |
  388. ((result.digits[i1] & highBitMasks[bits]) >>>
  389. (rightBits));
  390. }
  391. result.digits[0] = ((result.digits[i] << bits) & maxDigitVal);
  392. result.isNeg = x.isNeg;
  393. return result;
  394. }
  395. var lowBitMasks = new Array(0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F,
  396. 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF,
  397. 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF);
  398. function biShiftRight(x, n)
  399. {
  400. var digitCount = Math.floor(n / bitsPerDigit);
  401. var result = new BigInt();
  402. arrayCopy(x.digits, digitCount, result.digits, 0,
  403. x.digits.length - digitCount);
  404. var bits = n % bitsPerDigit;
  405. var leftBits = bitsPerDigit - bits;
  406. for (var i = 0, i1 = i + 1; i < result.digits.length - 1; ++i, ++i1) {
  407. result.digits[i] = (result.digits[i] >>> bits) |
  408. ((result.digits[i1] & lowBitMasks[bits]) << leftBits);
  409. }
  410. result.digits[result.digits.length - 1] >>>= bits;
  411. result.isNeg = x.isNeg;
  412. return result;
  413. }
  414. function biMultiplyByRadixPower(x, n)
  415. {
  416. var result = new BigInt();
  417. arrayCopy(x.digits, 0, result.digits, n, result.digits.length - n);
  418. return result;
  419. }
  420. function biDivideByRadixPower(x, n)
  421. {
  422. var result = new BigInt();
  423. arrayCopy(x.digits, n, result.digits, 0, result.digits.length - n);
  424. return result;
  425. }
  426. function biModuloByRadixPower(x, n)
  427. {
  428. var result = new BigInt();
  429. arrayCopy(x.digits, 0, result.digits, 0, n);
  430. return result;
  431. }
  432. function biCompare(x, y)
  433. {
  434. if (x.isNeg != y.isNeg) {
  435. return 1 - 2 * Number(x.isNeg);
  436. }
  437. for (var i = x.digits.length - 1; i >= 0; --i) {
  438. if (x.digits[i] != y.digits[i]) {
  439. if (x.isNeg) {
  440. return 1 - 2 * Number(x.digits[i] > y.digits[i]);
  441. } else {
  442. return 1 - 2 * Number(x.digits[i] < y.digits[i]);
  443. }
  444. }
  445. }
  446. return 0;
  447. }
  448. function biDivideModulo(x, y)
  449. {
  450. var nb = biNumBits(x);
  451. var tb = biNumBits(y);
  452. var origYIsNeg = y.isNeg;
  453. var q, r;
  454. if (nb < tb) {
  455. // |x| < |y|
  456. if (x.isNeg) {
  457. q = biCopy(bigOne);
  458. q.isNeg = !y.isNeg;
  459. x.isNeg = false;
  460. y.isNeg = false;
  461. r = biSubtract(y, x);
  462. // Restore signs, 'cause they're references.
  463. x.isNeg = true;
  464. y.isNeg = origYIsNeg;
  465. } else {
  466. q = new BigInt();
  467. r = biCopy(x);
  468. }
  469. return new Array(q, r);
  470. }
  471. q = new BigInt();
  472. r = x;
  473. // Normalize Y.
  474. var t = Math.ceil(tb / bitsPerDigit) - 1;
  475. var lambda = 0;
  476. while (y.digits[t] < biHalfRadix) {
  477. y = biShiftLeft(y, 1);
  478. ++lambda;
  479. ++tb;
  480. t = Math.ceil(tb / bitsPerDigit) - 1;
  481. }
  482. // Shift r over to keep the quotient constant. We'll shift the
  483. // remainder back at the end.
  484. r = biShiftLeft(r, lambda);
  485. nb += lambda; // Update the bit count for x.
  486. var n = Math.ceil(nb / bitsPerDigit) - 1;
  487. var b = biMultiplyByRadixPower(y, n - t);
  488. while (biCompare(r, b) != -1) {
  489. ++q.digits[n - t];
  490. r = biSubtract(r, b);
  491. }
  492. for (var i = n; i > t; --i) {
  493. var ri = (i >= r.digits.length) ? 0 : r.digits[i];
  494. var ri1 = (i - 1 >= r.digits.length) ? 0 : r.digits[i - 1];
  495. var ri2 = (i - 2 >= r.digits.length) ? 0 : r.digits[i - 2];
  496. var yt = (t >= y.digits.length) ? 0 : y.digits[t];
  497. var yt1 = (t - 1 >= y.digits.length) ? 0 : y.digits[t - 1];
  498. if (ri == yt) {
  499. q.digits[i - t - 1] = maxDigitVal;
  500. } else {
  501. q.digits[i - t - 1] = Math.floor((ri * biRadix + ri1) / yt);
  502. }
  503. var c1 = q.digits[i - t - 1] * ((yt * biRadix) + yt1);
  504. var c2 = (ri * biRadixSquared) + ((ri1 * biRadix) + ri2);
  505. while (c1 > c2) {
  506. --q.digits[i - t - 1];
  507. c1 = q.digits[i - t - 1] * ((yt * biRadix) | yt1);
  508. c2 = (ri * biRadix * biRadix) + ((ri1 * biRadix) + ri2);
  509. }
  510. b = biMultiplyByRadixPower(y, i - t - 1);
  511. r = biSubtract(r, biMultiplyDigit(b, q.digits[i - t - 1]));
  512. if (r.isNeg) {
  513. r = biAdd(r, b);
  514. --q.digits[i - t - 1];
  515. }
  516. }
  517. r = biShiftRight(r, lambda);
  518. // Fiddle with the signs and stuff to make sure that 0 <= r < y.
  519. q.isNeg = x.isNeg != origYIsNeg;
  520. if (x.isNeg) {
  521. if (origYIsNeg) {
  522. q = biAdd(q, bigOne);
  523. } else {
  524. q = biSubtract(q, bigOne);
  525. }
  526. y = biShiftRight(y, lambda);
  527. r = biSubtract(y, r);
  528. }
  529. // Check for the unbelievably stupid degenerate case of r == -0.
  530. if (r.digits[0] == 0 && biHighIndex(r) == 0) r.isNeg = false;
  531. return new Array(q, r);
  532. }
  533. function biDivide(x, y)
  534. {
  535. return biDivideModulo(x, y)[0];
  536. }
  537. function biModulo(x, y)
  538. {
  539. return biDivideModulo(x, y)[1];
  540. }
  541. function biMultiplyMod(x, y, m)
  542. {
  543. return biModulo(biMultiply(x, y), m);
  544. }
  545. function biPow(x, y)
  546. {
  547. var result = bigOne;
  548. var a = x;
  549. while (true) {
  550. if ((y & 1) != 0) result = biMultiply(result, a);
  551. y >>= 1;
  552. if (y == 0) break;
  553. a = biMultiply(a, a);
  554. }
  555. return result;
  556. }
  557. function biPowMod(x, y, m)
  558. {
  559. var result = bigOne;
  560. var a = x;
  561. var k = y;
  562. while (true) {
  563. if ((k.digits[0] & 1) != 0) result = biMultiplyMod(result, a, m);
  564. k = biShiftRight(k, 1);
  565. if (k.digits[0] == 0 && biHighIndex(k) == 0) break;
  566. a = biMultiplyMod(a, a, m);
  567. }
  568. return result;
  569. }