]> git.immae.eu Git - perso/Immae/Projets/Cryptomonnaies/BIP39.git/blob - src/js/entropy.js
Card entropy uses unicode suit symbols in cleanStr
[perso/Immae/Projets/Cryptomonnaies/BIP39.git] / src / js / entropy.js
1 /*
2 * Detects entropy from a string.
3 *
4 * Formats include:
5 * binary [0-1]
6 * base 6 [0-5]
7 * dice 6 [1-6]
8 * decimal [0-9]
9 * hexadecimal [0-9A-F]
10 *
11 * Automatically uses lowest entropy to avoid issues such as interpretting 0101
12 * as hexadecimal which would be 16 bits when really it's only 4 bits of binary
13 * entropy.
14 */
15
16 window.Entropy = new (function() {
17
18 // matchers returns an array of the matched events for each type of entropy.
19 // eg
20 // matchers.binary("010") returns ["0", "1", "0"]
21 // matchers.binary("a10") returns ["1", "0"]
22 // matchers.hex("a10") returns ["a", "1", "0"]
23 var matchers = {
24 binary: function(str) {
25 return str.match(/[0-1]/gi) || [];
26 },
27 base6: function(str) {
28 return str.match(/[0-5]/gi) || [];
29 },
30 dice: function(str) {
31 return str.match(/[1-6]/gi) || []; // ie dice numbers
32 },
33 base10: function(str) {
34 return str.match(/[0-9]/gi) || [];
35 },
36 hex: function(str) {
37 return str.match(/[0-9A-F]/gi) || [];
38 },
39 card: function(str) {
40 // Format is NumberSuit, eg
41 // AH ace of hearts
42 // 8C eight of clubs
43 // TD ten of diamonds
44 // JS jack of spades
45 // QH queen of hearts
46 // KC king of clubs
47 return str.match(/([A2-9TJQK][CDHS])/gi) || [];
48 }
49 }
50
51 // Convert array of cards from ["ac", "4d", "ks"]
52 // to numbers between 0 and 51 [0, 16, 51]
53 function convertCardsToInts(cards) {
54 var ints = [];
55 var values = "a23456789tjqk";
56 var suits = "cdhs";
57 for (var i=0; i<cards.length; i++) {
58 var card = cards[i].toLowerCase();
59 var value = card[0];
60 var suit = card[1];
61 var asInt = 13 * suits.indexOf(suit) + values.indexOf(value);
62 ints.push(asInt);
63 }
64 return ints;
65 }
66
67 this.fromString = function(rawEntropyStr) {
68 // Find type of entropy being used (binary, hex, dice etc)
69 var base = getBase(rawEntropyStr);
70 // Convert dice to base6 entropy (ie 1-6 to 0-5)
71 // This is done by changing all 6s to 0s
72 if (base.str == "dice") {
73 var newParts = [];
74 var newInts = [];
75 for (var i=0; i<base.parts.length; i++) {
76 var c = base.parts[i];
77 if ("12345".indexOf(c) > -1) {
78 newParts[i] = base.parts[i];
79 newInts[i] = base.ints[i];
80 }
81 else {
82 newParts[i] = "0";
83 newInts[i] = 0;
84 }
85 }
86 base.str = "base 6 (dice)";
87 base.ints = newInts;
88 base.parts = newParts;
89 base.matcher = matchers.base6;
90 }
91 // Detect empty entropy
92 if (base.parts.length == 0) {
93 return {
94 binaryStr: "",
95 cleanStr: "",
96 base: base,
97 };
98 }
99 // Pull leading zeros off
100 var leadingZeros = [];
101 while (base.ints[0] == "0") {
102 leadingZeros.push("0");
103 base.ints.shift();
104 }
105 // Convert leading zeros to binary equivalent
106 var numBinLeadingZeros = Math.floor(Math.log2(base.asInt) * leadingZeros.length);
107 var binLeadingZeros = "";
108 for (var i=0; i<numBinLeadingZeros; i++) {
109 binLeadingZeros += "0";
110 }
111 // Handle entropy of zero
112 if (base.ints.length == 0) {
113 return {
114 binaryStr: binLeadingZeros,
115 cleanStr: leadingZeros.join(""),
116 base: base,
117 }
118 }
119 // If the first integer is small, it must be padded with zeros.
120 // Otherwise the chance of the first bit being 1 is 100%, which is
121 // obviously incorrect.
122 // This is not perfect for unusual bases, so is only done for bases
123 // of 2^n, eg octal or hexadecimal
124 if (base.asInt == 16) {
125 var firstInt = base.ints[0];
126 var firstIntBits = firstInt.toString(2).length;
127 var maxFirstIntBits = (base.asInt-1).toString(2).length;
128 var missingFirstIntBits = maxFirstIntBits - firstIntBits;
129 for (var i=0; i<missingFirstIntBits; i++) {
130 binLeadingZeros += "0";
131 }
132 }
133 // Convert base.ints to BigInteger.
134 // Due to using unusual bases, eg cards of base52, this is not as simple as
135 // using BigInteger.parse()
136 var entropyInt = BigInteger.ZERO;
137 for (var i=base.ints.length-1; i>=0; i--) {
138 var thisInt = BigInteger.parse(base.ints[i]);
139 var power = (base.ints.length - 1) - i;
140 var additionalEntropy = BigInteger.parse(base.asInt).pow(power).multiply(thisInt);
141 entropyInt = entropyInt.add(additionalEntropy);
142 }
143 // Convert entropy to different formats
144 var entropyBin = binLeadingZeros + entropyInt.toString(2);
145 var entropyClean = base.parts.join("");
146 if (base.asInt == 52) {
147 entropyClean = base.parts.join(" ").toUpperCase();
148 entropyClean = entropyClean.replace(/C/g, "\u2663");
149 entropyClean = entropyClean.replace(/D/g, "\u2666");
150 entropyClean = entropyClean.replace(/H/g, "\u2665");
151 entropyClean = entropyClean.replace(/S/g, "\u2660");
152 }
153 var e = {
154 binaryStr: entropyBin,
155 cleanStr: entropyClean,
156 base: base,
157 }
158 return e;
159 }
160
161 function getBase(str) {
162 // Need to get the lowest base for the supplied entropy.
163 // This prevents interpreting, say, dice rolls as hexadecimal.
164 var binaryMatches = matchers.binary(str);
165 var hexMatches = matchers.hex(str);
166 // Find the lowest base that can be used, whilst ignoring any irrelevant chars
167 if (binaryMatches.length == hexMatches.length && hexMatches.length > 0) {
168 var ints = binaryMatches.map(function(i) { return parseInt(i, 2) });
169 return {
170 ints: ints,
171 parts: binaryMatches,
172 matcher: matchers.binary,
173 asInt: 2,
174 str: "binary",
175 }
176 }
177 var cardMatches = matchers.card(str);
178 if (cardMatches.length >= hexMatches.length / 2) {
179 var ints = convertCardsToInts(cardMatches);
180 return {
181 ints: ints,
182 parts: cardMatches,
183 matcher: matchers.card,
184 asInt: 52,
185 str: "card",
186 }
187 }
188 var diceMatches = matchers.dice(str);
189 if (diceMatches.length == hexMatches.length && hexMatches.length > 0) {
190 var ints = diceMatches.map(function(i) { return parseInt(i) });
191 return {
192 ints: ints,
193 parts: diceMatches,
194 matcher: matchers.dice,
195 asInt: 6,
196 str: "dice",
197 }
198 }
199 var base6Matches = matchers.base6(str);
200 if (base6Matches.length == hexMatches.length && hexMatches.length > 0) {
201 var ints = base6Matches.map(function(i) { return parseInt(i) });
202 return {
203 ints: ints,
204 parts: base6Matches,
205 matcher: matchers.base6,
206 asInt: 6,
207 str: "base 6",
208 }
209 }
210 var base10Matches = matchers.base10(str);
211 if (base10Matches.length == hexMatches.length && hexMatches.length > 0) {
212 var ints = base10Matches.map(function(i) { return parseInt(i) });
213 return {
214 ints: ints,
215 parts: base10Matches,
216 matcher: matchers.base10,
217 asInt: 10,
218 str: "base 10",
219 }
220 }
221 var ints = hexMatches.map(function(i) { return parseInt(i, 16) });
222 return {
223 ints: ints,
224 parts: hexMatches,
225 matcher: matchers.hex,
226 asInt: 16,
227 str: "hexadecimal",
228 }
229 }
230
231 // Polyfill for Math.log2
232 // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/log2#Polyfill
233 Math.log2 = Math.log2 || function(x) {
234 // The polyfill isn't good enough because of the poor accuracy of
235 // Math.LOG2E
236 // log2(8) gave 2.9999999999999996 which when floored causes issues.
237 // So instead use the BigInteger library to get it right.
238 return BigInteger.log(x) / BigInteger.log(2);
239 };
240
241 })();
242
243
244 // BigInteger library included here because
245 // only the entropy library depends on it
246 // so if entropy detection is removed so is the dependency
247
248
249 /*
250 JavaScript BigInteger library version 0.9.1
251 http://silentmatt.com/biginteger/
252
253 Copyright (c) 2009 Matthew Crumley <email@matthewcrumley.com>
254 Copyright (c) 2010,2011 by John Tobey <John.Tobey@gmail.com>
255 Licensed under the MIT license.
256
257 Support for arbitrary internal representation base was added by
258 Vitaly Magerya.
259 */
260
261 /*
262 File: biginteger.js
263
264 Exports:
265
266 <BigInteger>
267 */
268 (function(exports) {
269 "use strict";
270 /*
271 Class: BigInteger
272 An arbitrarily-large integer.
273
274 <BigInteger> objects should be considered immutable. None of the "built-in"
275 methods modify *this* or their arguments. All properties should be
276 considered private.
277
278 All the methods of <BigInteger> instances can be called "statically". The
279 static versions are convenient if you don't already have a <BigInteger>
280 object.
281
282 As an example, these calls are equivalent.
283
284 > BigInteger(4).multiply(5); // returns BigInteger(20);
285 > BigInteger.multiply(4, 5); // returns BigInteger(20);
286
287 > var a = 42;
288 > var a = BigInteger.toJSValue("0b101010"); // Not completely useless...
289 */
290
291 var CONSTRUCT = {}; // Unique token to call "private" version of constructor
292
293 /*
294 Constructor: BigInteger()
295 Convert a value to a <BigInteger>.
296
297 Although <BigInteger()> is the constructor for <BigInteger> objects, it is
298 best not to call it as a constructor. If *n* is a <BigInteger> object, it is
299 simply returned as-is. Otherwise, <BigInteger()> is equivalent to <parse>
300 without a radix argument.
301
302 > var n0 = BigInteger(); // Same as <BigInteger.ZERO>
303 > var n1 = BigInteger("123"); // Create a new <BigInteger> with value 123
304 > var n2 = BigInteger(123); // Create a new <BigInteger> with value 123
305 > var n3 = BigInteger(n2); // Return n2, unchanged
306
307 The constructor form only takes an array and a sign. *n* must be an
308 array of numbers in little-endian order, where each digit is between 0
309 and BigInteger.base. The second parameter sets the sign: -1 for
310 negative, +1 for positive, or 0 for zero. The array is *not copied and
311 may be modified*. If the array contains only zeros, the sign parameter
312 is ignored and is forced to zero.
313
314 > new BigInteger([5], -1): create a new BigInteger with value -5
315
316 Parameters:
317
318 n - Value to convert to a <BigInteger>.
319
320 Returns:
321
322 A <BigInteger> value.
323
324 See Also:
325
326 <parse>, <BigInteger>
327 */
328 function BigInteger(n, s, token) {
329 if (token !== CONSTRUCT) {
330 if (n instanceof BigInteger) {
331 return n;
332 }
333 else if (typeof n === "undefined") {
334 return ZERO;
335 }
336 return BigInteger.parse(n);
337 }
338
339 n = n || []; // Provide the nullary constructor for subclasses.
340 while (n.length && !n[n.length - 1]) {
341 --n.length;
342 }
343 this._d = n;
344 this._s = n.length ? (s || 1) : 0;
345 }
346
347 BigInteger._construct = function(n, s) {
348 return new BigInteger(n, s, CONSTRUCT);
349 };
350
351 // Base-10 speedup hacks in parse, toString, exp10 and log functions
352 // require base to be a power of 10. 10^7 is the largest such power
353 // that won't cause a precision loss when digits are multiplied.
354 var BigInteger_base = 10000000;
355 var BigInteger_base_log10 = 7;
356
357 BigInteger.base = BigInteger_base;
358 BigInteger.base_log10 = BigInteger_base_log10;
359
360 var ZERO = new BigInteger([], 0, CONSTRUCT);
361 // Constant: ZERO
362 // <BigInteger> 0.
363 BigInteger.ZERO = ZERO;
364
365 var ONE = new BigInteger([1], 1, CONSTRUCT);
366 // Constant: ONE
367 // <BigInteger> 1.
368 BigInteger.ONE = ONE;
369
370 var M_ONE = new BigInteger(ONE._d, -1, CONSTRUCT);
371 // Constant: M_ONE
372 // <BigInteger> -1.
373 BigInteger.M_ONE = M_ONE;
374
375 // Constant: _0
376 // Shortcut for <ZERO>.
377 BigInteger._0 = ZERO;
378
379 // Constant: _1
380 // Shortcut for <ONE>.
381 BigInteger._1 = ONE;
382
383 /*
384 Constant: small
385 Array of <BigIntegers> from 0 to 36.
386
387 These are used internally for parsing, but useful when you need a "small"
388 <BigInteger>.
389
390 See Also:
391
392 <ZERO>, <ONE>, <_0>, <_1>
393 */
394 BigInteger.small = [
395 ZERO,
396 ONE,
397 /* Assuming BigInteger_base > 36 */
398 new BigInteger( [2], 1, CONSTRUCT),
399 new BigInteger( [3], 1, CONSTRUCT),
400 new BigInteger( [4], 1, CONSTRUCT),
401 new BigInteger( [5], 1, CONSTRUCT),
402 new BigInteger( [6], 1, CONSTRUCT),
403 new BigInteger( [7], 1, CONSTRUCT),
404 new BigInteger( [8], 1, CONSTRUCT),
405 new BigInteger( [9], 1, CONSTRUCT),
406 new BigInteger([10], 1, CONSTRUCT),
407 new BigInteger([11], 1, CONSTRUCT),
408 new BigInteger([12], 1, CONSTRUCT),
409 new BigInteger([13], 1, CONSTRUCT),
410 new BigInteger([14], 1, CONSTRUCT),
411 new BigInteger([15], 1, CONSTRUCT),
412 new BigInteger([16], 1, CONSTRUCT),
413 new BigInteger([17], 1, CONSTRUCT),
414 new BigInteger([18], 1, CONSTRUCT),
415 new BigInteger([19], 1, CONSTRUCT),
416 new BigInteger([20], 1, CONSTRUCT),
417 new BigInteger([21], 1, CONSTRUCT),
418 new BigInteger([22], 1, CONSTRUCT),
419 new BigInteger([23], 1, CONSTRUCT),
420 new BigInteger([24], 1, CONSTRUCT),
421 new BigInteger([25], 1, CONSTRUCT),
422 new BigInteger([26], 1, CONSTRUCT),
423 new BigInteger([27], 1, CONSTRUCT),
424 new BigInteger([28], 1, CONSTRUCT),
425 new BigInteger([29], 1, CONSTRUCT),
426 new BigInteger([30], 1, CONSTRUCT),
427 new BigInteger([31], 1, CONSTRUCT),
428 new BigInteger([32], 1, CONSTRUCT),
429 new BigInteger([33], 1, CONSTRUCT),
430 new BigInteger([34], 1, CONSTRUCT),
431 new BigInteger([35], 1, CONSTRUCT),
432 new BigInteger([36], 1, CONSTRUCT)
433 ];
434
435 // Used for parsing/radix conversion
436 BigInteger.digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");
437
438 /*
439 Method: toString
440 Convert a <BigInteger> to a string.
441
442 When *base* is greater than 10, letters are upper case.
443
444 Parameters:
445
446 base - Optional base to represent the number in (default is base 10).
447 Must be between 2 and 36 inclusive, or an Error will be thrown.
448
449 Returns:
450
451 The string representation of the <BigInteger>.
452 */
453 BigInteger.prototype.toString = function(base) {
454 base = +base || 10;
455 if (base < 2 || base > 36) {
456 throw new Error("illegal radix " + base + ".");
457 }
458 if (this._s === 0) {
459 return "0";
460 }
461 if (base === 10) {
462 var str = this._s < 0 ? "-" : "";
463 str += this._d[this._d.length - 1].toString();
464 for (var i = this._d.length - 2; i >= 0; i--) {
465 var group = this._d[i].toString();
466 while (group.length < BigInteger_base_log10) group = '0' + group;
467 str += group;
468 }
469 return str;
470 }
471 else {
472 var numerals = BigInteger.digits;
473 base = BigInteger.small[base];
474 var sign = this._s;
475
476 var n = this.abs();
477 var digits = [];
478 var digit;
479
480 while (n._s !== 0) {
481 var divmod = n.divRem(base);
482 n = divmod[0];
483 digit = divmod[1];
484 // TODO: This could be changed to unshift instead of reversing at the end.
485 // Benchmark both to compare speeds.
486 digits.push(numerals[digit.valueOf()]);
487 }
488 return (sign < 0 ? "-" : "") + digits.reverse().join("");
489 }
490 };
491
492 // Verify strings for parsing
493 BigInteger.radixRegex = [
494 /^$/,
495 /^$/,
496 /^[01]*$/,
497 /^[012]*$/,
498 /^[0-3]*$/,
499 /^[0-4]*$/,
500 /^[0-5]*$/,
501 /^[0-6]*$/,
502 /^[0-7]*$/,
503 /^[0-8]*$/,
504 /^[0-9]*$/,
505 /^[0-9aA]*$/,
506 /^[0-9abAB]*$/,
507 /^[0-9abcABC]*$/,
508 /^[0-9a-dA-D]*$/,
509 /^[0-9a-eA-E]*$/,
510 /^[0-9a-fA-F]*$/,
511 /^[0-9a-gA-G]*$/,
512 /^[0-9a-hA-H]*$/,
513 /^[0-9a-iA-I]*$/,
514 /^[0-9a-jA-J]*$/,
515 /^[0-9a-kA-K]*$/,
516 /^[0-9a-lA-L]*$/,
517 /^[0-9a-mA-M]*$/,
518 /^[0-9a-nA-N]*$/,
519 /^[0-9a-oA-O]*$/,
520 /^[0-9a-pA-P]*$/,
521 /^[0-9a-qA-Q]*$/,
522 /^[0-9a-rA-R]*$/,
523 /^[0-9a-sA-S]*$/,
524 /^[0-9a-tA-T]*$/,
525 /^[0-9a-uA-U]*$/,
526 /^[0-9a-vA-V]*$/,
527 /^[0-9a-wA-W]*$/,
528 /^[0-9a-xA-X]*$/,
529 /^[0-9a-yA-Y]*$/,
530 /^[0-9a-zA-Z]*$/
531 ];
532
533 /*
534 Function: parse
535 Parse a string into a <BigInteger>.
536
537 *base* is optional but, if provided, must be from 2 to 36 inclusive. If
538 *base* is not provided, it will be guessed based on the leading characters
539 of *s* as follows:
540
541 - "0x" or "0X": *base* = 16
542 - "0c" or "0C": *base* = 8
543 - "0b" or "0B": *base* = 2
544 - else: *base* = 10
545
546 If no base is provided, or *base* is 10, the number can be in exponential
547 form. For example, these are all valid:
548
549 > BigInteger.parse("1e9"); // Same as "1000000000"
550 > BigInteger.parse("1.234*10^3"); // Same as 1234
551 > BigInteger.parse("56789 * 10 ** -2"); // Same as 567
552
553 If any characters fall outside the range defined by the radix, an exception
554 will be thrown.
555
556 Parameters:
557
558 s - The string to parse.
559 base - Optional radix (default is to guess based on *s*).
560
561 Returns:
562
563 a <BigInteger> instance.
564 */
565 BigInteger.parse = function(s, base) {
566 // Expands a number in exponential form to decimal form.
567 // expandExponential("-13.441*10^5") === "1344100";
568 // expandExponential("1.12300e-1") === "0.112300";
569 // expandExponential(1000000000000000000000000000000) === "1000000000000000000000000000000";
570 function expandExponential(str) {
571 str = str.replace(/\s*[*xX]\s*10\s*(\^|\*\*)\s*/, "e");
572
573 return str.replace(/^([+\-])?(\d+)\.?(\d*)[eE]([+\-]?\d+)$/, function(x, s, n, f, c) {
574 c = +c;
575 var l = c < 0;
576 var i = n.length + c;
577 x = (l ? n : f).length;
578 c = ((c = Math.abs(c)) >= x ? c - x + l : 0);
579 var z = (new Array(c + 1)).join("0");
580 var r = n + f;
581 return (s || "") + (l ? r = z + r : r += z).substr(0, i += l ? z.length : 0) + (i < r.length ? "." + r.substr(i) : "");
582 });
583 }
584
585 s = s.toString();
586 if (typeof base === "undefined" || +base === 10) {
587 s = expandExponential(s);
588 }
589
590 var prefixRE;
591 if (typeof base === "undefined") {
592 prefixRE = '0[xcb]';
593 }
594 else if (base == 16) {
595 prefixRE = '0x';
596 }
597 else if (base == 8) {
598 prefixRE = '0c';
599 }
600 else if (base == 2) {
601 prefixRE = '0b';
602 }
603 else {
604 prefixRE = '';
605 }
606 var parts = new RegExp('^([+\\-]?)(' + prefixRE + ')?([0-9a-z]*)(?:\\.\\d*)?$', 'i').exec(s);
607 if (parts) {
608 var sign = parts[1] || "+";
609 var baseSection = parts[2] || "";
610 var digits = parts[3] || "";
611
612 if (typeof base === "undefined") {
613 // Guess base
614 if (baseSection === "0x" || baseSection === "0X") { // Hex
615 base = 16;
616 }
617 else if (baseSection === "0c" || baseSection === "0C") { // Octal
618 base = 8;
619 }
620 else if (baseSection === "0b" || baseSection === "0B") { // Binary
621 base = 2;
622 }
623 else {
624 base = 10;
625 }
626 }
627 else if (base < 2 || base > 36) {
628 throw new Error("Illegal radix " + base + ".");
629 }
630
631 base = +base;
632
633 // Check for digits outside the range
634 if (!(BigInteger.radixRegex[base].test(digits))) {
635 throw new Error("Bad digit for radix " + base);
636 }
637
638 // Strip leading zeros, and convert to array
639 digits = digits.replace(/^0+/, "").split("");
640 if (digits.length === 0) {
641 return ZERO;
642 }
643
644 // Get the sign (we know it's not zero)
645 sign = (sign === "-") ? -1 : 1;
646
647 // Optimize 10
648 if (base == 10) {
649 var d = [];
650 while (digits.length >= BigInteger_base_log10) {
651 d.push(parseInt(digits.splice(digits.length-BigInteger.base_log10, BigInteger.base_log10).join(''), 10));
652 }
653 d.push(parseInt(digits.join(''), 10));
654 return new BigInteger(d, sign, CONSTRUCT);
655 }
656
657 // Do the conversion
658 var d = ZERO;
659 base = BigInteger.small[base];
660 var small = BigInteger.small;
661 for (var i = 0; i < digits.length; i++) {
662 d = d.multiply(base).add(small[parseInt(digits[i], 36)]);
663 }
664 return new BigInteger(d._d, sign, CONSTRUCT);
665 }
666 else {
667 throw new Error("Invalid BigInteger format: " + s);
668 }
669 };
670
671 /*
672 Function: add
673 Add two <BigIntegers>.
674
675 Parameters:
676
677 n - The number to add to *this*. Will be converted to a <BigInteger>.
678
679 Returns:
680
681 The numbers added together.
682
683 See Also:
684
685 <subtract>, <multiply>, <quotient>, <next>
686 */
687 BigInteger.prototype.add = function(n) {
688 if (this._s === 0) {
689 return BigInteger(n);
690 }
691
692 n = BigInteger(n);
693 if (n._s === 0) {
694 return this;
695 }
696 if (this._s !== n._s) {
697 n = n.negate();
698 return this.subtract(n);
699 }
700
701 var a = this._d;
702 var b = n._d;
703 var al = a.length;
704 var bl = b.length;
705 var sum = new Array(Math.max(al, bl) + 1);
706 var size = Math.min(al, bl);
707 var carry = 0;
708 var digit;
709
710 for (var i = 0; i < size; i++) {
711 digit = a[i] + b[i] + carry;
712 sum[i] = digit % BigInteger_base;
713 carry = (digit / BigInteger_base) | 0;
714 }
715 if (bl > al) {
716 a = b;
717 al = bl;
718 }
719 for (i = size; carry && i < al; i++) {
720 digit = a[i] + carry;
721 sum[i] = digit % BigInteger_base;
722 carry = (digit / BigInteger_base) | 0;
723 }
724 if (carry) {
725 sum[i] = carry;
726 }
727
728 for ( ; i < al; i++) {
729 sum[i] = a[i];
730 }
731
732 return new BigInteger(sum, this._s, CONSTRUCT);
733 };
734
735 /*
736 Function: negate
737 Get the additive inverse of a <BigInteger>.
738
739 Returns:
740
741 A <BigInteger> with the same magnatude, but with the opposite sign.
742
743 See Also:
744
745 <abs>
746 */
747 BigInteger.prototype.negate = function() {
748 return new BigInteger(this._d, (-this._s) | 0, CONSTRUCT);
749 };
750
751 /*
752 Function: abs
753 Get the absolute value of a <BigInteger>.
754
755 Returns:
756
757 A <BigInteger> with the same magnatude, but always positive (or zero).
758
759 See Also:
760
761 <negate>
762 */
763 BigInteger.prototype.abs = function() {
764 return (this._s < 0) ? this.negate() : this;
765 };
766
767 /*
768 Function: subtract
769 Subtract two <BigIntegers>.
770
771 Parameters:
772
773 n - The number to subtract from *this*. Will be converted to a <BigInteger>.
774
775 Returns:
776
777 The *n* subtracted from *this*.
778
779 See Also:
780
781 <add>, <multiply>, <quotient>, <prev>
782 */
783 BigInteger.prototype.subtract = function(n) {
784 if (this._s === 0) {
785 return BigInteger(n).negate();
786 }
787
788 n = BigInteger(n);
789 if (n._s === 0) {
790 return this;
791 }
792 if (this._s !== n._s) {
793 n = n.negate();
794 return this.add(n);
795 }
796
797 var m = this;
798 // negative - negative => -|a| - -|b| => -|a| + |b| => |b| - |a|
799 if (this._s < 0) {
800 m = new BigInteger(n._d, 1, CONSTRUCT);
801 n = new BigInteger(this._d, 1, CONSTRUCT);
802 }
803
804 // Both are positive => a - b
805 var sign = m.compareAbs(n);
806 if (sign === 0) {
807 return ZERO;
808 }
809 else if (sign < 0) {
810 // swap m and n
811 var t = n;
812 n = m;
813 m = t;
814 }
815
816 // a > b
817 var a = m._d;
818 var b = n._d;
819 var al = a.length;
820 var bl = b.length;
821 var diff = new Array(al); // al >= bl since a > b
822 var borrow = 0;
823 var i;
824 var digit;
825
826 for (i = 0; i < bl; i++) {
827 digit = a[i] - borrow - b[i];
828 if (digit < 0) {
829 digit += BigInteger_base;
830 borrow = 1;
831 }
832 else {
833 borrow = 0;
834 }
835 diff[i] = digit;
836 }
837 for (i = bl; i < al; i++) {
838 digit = a[i] - borrow;
839 if (digit < 0) {
840 digit += BigInteger_base;
841 }
842 else {
843 diff[i++] = digit;
844 break;
845 }
846 diff[i] = digit;
847 }
848 for ( ; i < al; i++) {
849 diff[i] = a[i];
850 }
851
852 return new BigInteger(diff, sign, CONSTRUCT);
853 };
854
855 (function() {
856 function addOne(n, sign) {
857 var a = n._d;
858 var sum = a.slice();
859 var carry = true;
860 var i = 0;
861
862 while (true) {
863 var digit = (a[i] || 0) + 1;
864 sum[i] = digit % BigInteger_base;
865 if (digit <= BigInteger_base - 1) {
866 break;
867 }
868 ++i;
869 }
870
871 return new BigInteger(sum, sign, CONSTRUCT);
872 }
873
874 function subtractOne(n, sign) {
875 var a = n._d;
876 var sum = a.slice();
877 var borrow = true;
878 var i = 0;
879
880 while (true) {
881 var digit = (a[i] || 0) - 1;
882 if (digit < 0) {
883 sum[i] = digit + BigInteger_base;
884 }
885 else {
886 sum[i] = digit;
887 break;
888 }
889 ++i;
890 }
891
892 return new BigInteger(sum, sign, CONSTRUCT);
893 }
894
895 /*
896 Function: next
897 Get the next <BigInteger> (add one).
898
899 Returns:
900
901 *this* + 1.
902
903 See Also:
904
905 <add>, <prev>
906 */
907 BigInteger.prototype.next = function() {
908 switch (this._s) {
909 case 0:
910 return ONE;
911 case -1:
912 return subtractOne(this, -1);
913 // case 1:
914 default:
915 return addOne(this, 1);
916 }
917 };
918
919 /*
920 Function: prev
921 Get the previous <BigInteger> (subtract one).
922
923 Returns:
924
925 *this* - 1.
926
927 See Also:
928
929 <next>, <subtract>
930 */
931 BigInteger.prototype.prev = function() {
932 switch (this._s) {
933 case 0:
934 return M_ONE;
935 case -1:
936 return addOne(this, -1);
937 // case 1:
938 default:
939 return subtractOne(this, 1);
940 }
941 };
942 })();
943
944 /*
945 Function: compareAbs
946 Compare the absolute value of two <BigIntegers>.
947
948 Calling <compareAbs> is faster than calling <abs> twice, then <compare>.
949
950 Parameters:
951
952 n - The number to compare to *this*. Will be converted to a <BigInteger>.
953
954 Returns:
955
956 -1, 0, or +1 if *|this|* is less than, equal to, or greater than *|n|*.
957
958 See Also:
959
960 <compare>, <abs>
961 */
962 BigInteger.prototype.compareAbs = function(n) {
963 if (this === n) {
964 return 0;
965 }
966
967 if (!(n instanceof BigInteger)) {
968 if (!isFinite(n)) {
969 return(isNaN(n) ? n : -1);
970 }
971 n = BigInteger(n);
972 }
973
974 if (this._s === 0) {
975 return (n._s !== 0) ? -1 : 0;
976 }
977 if (n._s === 0) {
978 return 1;
979 }
980
981 var l = this._d.length;
982 var nl = n._d.length;
983 if (l < nl) {
984 return -1;
985 }
986 else if (l > nl) {
987 return 1;
988 }
989
990 var a = this._d;
991 var b = n._d;
992 for (var i = l-1; i >= 0; i--) {
993 if (a[i] !== b[i]) {
994 return a[i] < b[i] ? -1 : 1;
995 }
996 }
997
998 return 0;
999 };
1000
1001 /*
1002 Function: compare
1003 Compare two <BigIntegers>.
1004
1005 Parameters:
1006
1007 n - The number to compare to *this*. Will be converted to a <BigInteger>.
1008
1009 Returns:
1010
1011 -1, 0, or +1 if *this* is less than, equal to, or greater than *n*.
1012
1013 See Also:
1014
1015 <compareAbs>, <isPositive>, <isNegative>, <isUnit>
1016 */
1017 BigInteger.prototype.compare = function(n) {
1018 if (this === n) {
1019 return 0;
1020 }
1021
1022 n = BigInteger(n);
1023
1024 if (this._s === 0) {
1025 return -n._s;
1026 }
1027
1028 if (this._s === n._s) { // both positive or both negative
1029 var cmp = this.compareAbs(n);
1030 return cmp * this._s;
1031 }
1032 else {
1033 return this._s;
1034 }
1035 };
1036
1037 /*
1038 Function: isUnit
1039 Return true iff *this* is either 1 or -1.
1040
1041 Returns:
1042
1043 true if *this* compares equal to <BigInteger.ONE> or <BigInteger.M_ONE>.
1044
1045 See Also:
1046
1047 <isZero>, <isNegative>, <isPositive>, <compareAbs>, <compare>,
1048 <BigInteger.ONE>, <BigInteger.M_ONE>
1049 */
1050 BigInteger.prototype.isUnit = function() {
1051 return this === ONE ||
1052 this === M_ONE ||
1053 (this._d.length === 1 && this._d[0] === 1);
1054 };
1055
1056 /*
1057 Function: multiply
1058 Multiply two <BigIntegers>.
1059
1060 Parameters:
1061
1062 n - The number to multiply *this* by. Will be converted to a
1063 <BigInteger>.
1064
1065 Returns:
1066
1067 The numbers multiplied together.
1068
1069 See Also:
1070
1071 <add>, <subtract>, <quotient>, <square>
1072 */
1073 BigInteger.prototype.multiply = function(n) {
1074 // TODO: Consider adding Karatsuba multiplication for large numbers
1075 if (this._s === 0) {
1076 return ZERO;
1077 }
1078
1079 n = BigInteger(n);
1080 if (n._s === 0) {
1081 return ZERO;
1082 }
1083 if (this.isUnit()) {
1084 if (this._s < 0) {
1085 return n.negate();
1086 }
1087 return n;
1088 }
1089 if (n.isUnit()) {
1090 if (n._s < 0) {
1091 return this.negate();
1092 }
1093 return this;
1094 }
1095 if (this === n) {
1096 return this.square();
1097 }
1098
1099 var r = (this._d.length >= n._d.length);
1100 var a = (r ? this : n)._d; // a will be longer than b
1101 var b = (r ? n : this)._d;
1102 var al = a.length;
1103 var bl = b.length;
1104
1105 var pl = al + bl;
1106 var partial = new Array(pl);
1107 var i;
1108 for (i = 0; i < pl; i++) {
1109 partial[i] = 0;
1110 }
1111
1112 for (i = 0; i < bl; i++) {
1113 var carry = 0;
1114 var bi = b[i];
1115 var jlimit = al + i;
1116 var digit;
1117 for (var j = i; j < jlimit; j++) {
1118 digit = partial[j] + bi * a[j - i] + carry;
1119 carry = (digit / BigInteger_base) | 0;
1120 partial[j] = (digit % BigInteger_base) | 0;
1121 }
1122 if (carry) {
1123 digit = partial[j] + carry;
1124 carry = (digit / BigInteger_base) | 0;
1125 partial[j] = digit % BigInteger_base;
1126 }
1127 }
1128 return new BigInteger(partial, this._s * n._s, CONSTRUCT);
1129 };
1130
1131 // Multiply a BigInteger by a single-digit native number
1132 // Assumes that this and n are >= 0
1133 // This is not really intended to be used outside the library itself
1134 BigInteger.prototype.multiplySingleDigit = function(n) {
1135 if (n === 0 || this._s === 0) {
1136 return ZERO;
1137 }
1138 if (n === 1) {
1139 return this;
1140 }
1141
1142 var digit;
1143 if (this._d.length === 1) {
1144 digit = this._d[0] * n;
1145 if (digit >= BigInteger_base) {
1146 return new BigInteger([(digit % BigInteger_base)|0,
1147 (digit / BigInteger_base)|0], 1, CONSTRUCT);
1148 }
1149 return new BigInteger([digit], 1, CONSTRUCT);
1150 }
1151
1152 if (n === 2) {
1153 return this.add(this);
1154 }
1155 if (this.isUnit()) {
1156 return new BigInteger([n], 1, CONSTRUCT);
1157 }
1158
1159 var a = this._d;
1160 var al = a.length;
1161
1162 var pl = al + 1;
1163 var partial = new Array(pl);
1164 for (var i = 0; i < pl; i++) {
1165 partial[i] = 0;
1166 }
1167
1168 var carry = 0;
1169 for (var j = 0; j < al; j++) {
1170 digit = n * a[j] + carry;
1171 carry = (digit / BigInteger_base) | 0;
1172 partial[j] = (digit % BigInteger_base) | 0;
1173 }
1174 if (carry) {
1175 partial[j] = carry;
1176 }
1177
1178 return new BigInteger(partial, 1, CONSTRUCT);
1179 };
1180
1181 /*
1182 Function: square
1183 Multiply a <BigInteger> by itself.
1184
1185 This is slightly faster than regular multiplication, since it removes the
1186 duplicated multiplcations.
1187
1188 Returns:
1189
1190 > this.multiply(this)
1191
1192 See Also:
1193 <multiply>
1194 */
1195 BigInteger.prototype.square = function() {
1196 // Normally, squaring a 10-digit number would take 100 multiplications.
1197 // Of these 10 are unique diagonals, of the remaining 90 (100-10), 45 are repeated.
1198 // This procedure saves (N*(N-1))/2 multiplications, (e.g., 45 of 100 multiplies).
1199 // Based on code by Gary Darby, Intellitech Systems Inc., www.DelphiForFun.org
1200
1201 if (this._s === 0) {
1202 return ZERO;
1203 }
1204 if (this.isUnit()) {
1205 return ONE;
1206 }
1207
1208 var digits = this._d;
1209 var length = digits.length;
1210 var imult1 = new Array(length + length + 1);
1211 var product, carry, k;
1212 var i;
1213
1214 // Calculate diagonal
1215 for (i = 0; i < length; i++) {
1216 k = i * 2;
1217 product = digits[i] * digits[i];
1218 carry = (product / BigInteger_base) | 0;
1219 imult1[k] = product % BigInteger_base;
1220 imult1[k + 1] = carry;
1221 }
1222
1223 // Calculate repeating part
1224 for (i = 0; i < length; i++) {
1225 carry = 0;
1226 k = i * 2 + 1;
1227 for (var j = i + 1; j < length; j++, k++) {
1228 product = digits[j] * digits[i] * 2 + imult1[k] + carry;
1229 carry = (product / BigInteger_base) | 0;
1230 imult1[k] = product % BigInteger_base;
1231 }
1232 k = length + i;
1233 var digit = carry + imult1[k];
1234 carry = (digit / BigInteger_base) | 0;
1235 imult1[k] = digit % BigInteger_base;
1236 imult1[k + 1] += carry;
1237 }
1238
1239 return new BigInteger(imult1, 1, CONSTRUCT);
1240 };
1241
1242 /*
1243 Function: quotient
1244 Divide two <BigIntegers> and truncate towards zero.
1245
1246 <quotient> throws an exception if *n* is zero.
1247
1248 Parameters:
1249
1250 n - The number to divide *this* by. Will be converted to a <BigInteger>.
1251
1252 Returns:
1253
1254 The *this* / *n*, truncated to an integer.
1255
1256 See Also:
1257
1258 <add>, <subtract>, <multiply>, <divRem>, <remainder>
1259 */
1260 BigInteger.prototype.quotient = function(n) {
1261 return this.divRem(n)[0];
1262 };
1263
1264 /*
1265 Function: divide
1266 Deprecated synonym for <quotient>.
1267 */
1268 BigInteger.prototype.divide = BigInteger.prototype.quotient;
1269
1270 /*
1271 Function: remainder
1272 Calculate the remainder of two <BigIntegers>.
1273
1274 <remainder> throws an exception if *n* is zero.
1275
1276 Parameters:
1277
1278 n - The remainder after *this* is divided *this* by *n*. Will be
1279 converted to a <BigInteger>.
1280
1281 Returns:
1282
1283 *this* % *n*.
1284
1285 See Also:
1286
1287 <divRem>, <quotient>
1288 */
1289 BigInteger.prototype.remainder = function(n) {
1290 return this.divRem(n)[1];
1291 };
1292
1293 /*
1294 Function: divRem
1295 Calculate the integer quotient and remainder of two <BigIntegers>.
1296
1297 <divRem> throws an exception if *n* is zero.
1298
1299 Parameters:
1300
1301 n - The number to divide *this* by. Will be converted to a <BigInteger>.
1302
1303 Returns:
1304
1305 A two-element array containing the quotient and the remainder.
1306
1307 > a.divRem(b)
1308
1309 is exactly equivalent to
1310
1311 > [a.quotient(b), a.remainder(b)]
1312
1313 except it is faster, because they are calculated at the same time.
1314
1315 See Also:
1316
1317 <quotient>, <remainder>
1318 */
1319 BigInteger.prototype.divRem = function(n) {
1320 n = BigInteger(n);
1321 if (n._s === 0) {
1322 throw new Error("Divide by zero");
1323 }
1324 if (this._s === 0) {
1325 return [ZERO, ZERO];
1326 }
1327 if (n._d.length === 1) {
1328 return this.divRemSmall(n._s * n._d[0]);
1329 }
1330
1331 // Test for easy cases -- |n1| <= |n2|
1332 switch (this.compareAbs(n)) {
1333 case 0: // n1 == n2
1334 return [this._s === n._s ? ONE : M_ONE, ZERO];
1335 case -1: // |n1| < |n2|
1336 return [ZERO, this];
1337 }
1338
1339 var sign = this._s * n._s;
1340 var a = n.abs();
1341 var b_digits = this._d;
1342 var b_index = b_digits.length;
1343 var digits = n._d.length;
1344 var quot = [];
1345 var guess;
1346
1347 var part = new BigInteger([], 0, CONSTRUCT);
1348
1349 while (b_index) {
1350 part._d.unshift(b_digits[--b_index]);
1351 part = new BigInteger(part._d, 1, CONSTRUCT);
1352
1353 if (part.compareAbs(n) < 0) {
1354 quot.push(0);
1355 continue;
1356 }
1357 if (part._s === 0) {
1358 guess = 0;
1359 }
1360 else {
1361 var xlen = part._d.length, ylen = a._d.length;
1362 var highx = part._d[xlen-1]*BigInteger_base + part._d[xlen-2];
1363 var highy = a._d[ylen-1]*BigInteger_base + a._d[ylen-2];
1364 if (part._d.length > a._d.length) {
1365 // The length of part._d can either match a._d length,
1366 // or exceed it by one.
1367 highx = (highx+1)*BigInteger_base;
1368 }
1369 guess = Math.ceil(highx/highy);
1370 }
1371 do {
1372 var check = a.multiplySingleDigit(guess);
1373 if (check.compareAbs(part) <= 0) {
1374 break;
1375 }
1376 guess--;
1377 } while (guess);
1378
1379 quot.push(guess);
1380 if (!guess) {
1381 continue;
1382 }
1383 var diff = part.subtract(check);
1384 part._d = diff._d.slice();
1385 }
1386
1387 return [new BigInteger(quot.reverse(), sign, CONSTRUCT),
1388 new BigInteger(part._d, this._s, CONSTRUCT)];
1389 };
1390
1391 // Throws an exception if n is outside of (-BigInteger.base, -1] or
1392 // [1, BigInteger.base). It's not necessary to call this, since the
1393 // other division functions will call it if they are able to.
1394 BigInteger.prototype.divRemSmall = function(n) {
1395 var r;
1396 n = +n;
1397 if (n === 0) {
1398 throw new Error("Divide by zero");
1399 }
1400
1401 var n_s = n < 0 ? -1 : 1;
1402 var sign = this._s * n_s;
1403 n = Math.abs(n);
1404
1405 if (n < 1 || n >= BigInteger_base) {
1406 throw new Error("Argument out of range");
1407 }
1408
1409 if (this._s === 0) {
1410 return [ZERO, ZERO];
1411 }
1412
1413 if (n === 1 || n === -1) {
1414 return [(sign === 1) ? this.abs() : new BigInteger(this._d, sign, CONSTRUCT), ZERO];
1415 }
1416
1417 // 2 <= n < BigInteger_base
1418
1419 // divide a single digit by a single digit
1420 if (this._d.length === 1) {
1421 var q = new BigInteger([(this._d[0] / n) | 0], 1, CONSTRUCT);
1422 r = new BigInteger([(this._d[0] % n) | 0], 1, CONSTRUCT);
1423 if (sign < 0) {
1424 q = q.negate();
1425 }
1426 if (this._s < 0) {
1427 r = r.negate();
1428 }
1429 return [q, r];
1430 }
1431
1432 var digits = this._d.slice();
1433 var quot = new Array(digits.length);
1434 var part = 0;
1435 var diff = 0;
1436 var i = 0;
1437 var guess;
1438
1439 while (digits.length) {
1440 part = part * BigInteger_base + digits[digits.length - 1];
1441 if (part < n) {
1442 quot[i++] = 0;
1443 digits.pop();
1444 diff = BigInteger_base * diff + part;
1445 continue;
1446 }
1447 if (part === 0) {
1448 guess = 0;
1449 }
1450 else {
1451 guess = (part / n) | 0;
1452 }
1453
1454 var check = n * guess;
1455 diff = part - check;
1456 quot[i++] = guess;
1457 if (!guess) {
1458 digits.pop();
1459 continue;
1460 }
1461
1462 digits.pop();
1463 part = diff;
1464 }
1465
1466 r = new BigInteger([diff], 1, CONSTRUCT);
1467 if (this._s < 0) {
1468 r = r.negate();
1469 }
1470 return [new BigInteger(quot.reverse(), sign, CONSTRUCT), r];
1471 };
1472
1473 /*
1474 Function: isEven
1475 Return true iff *this* is divisible by two.
1476
1477 Note that <BigInteger.ZERO> is even.
1478
1479 Returns:
1480
1481 true if *this* is even, false otherwise.
1482
1483 See Also:
1484
1485 <isOdd>
1486 */
1487 BigInteger.prototype.isEven = function() {
1488 var digits = this._d;
1489 return this._s === 0 || digits.length === 0 || (digits[0] % 2) === 0;
1490 };
1491
1492 /*
1493 Function: isOdd
1494 Return true iff *this* is not divisible by two.
1495
1496 Returns:
1497
1498 true if *this* is odd, false otherwise.
1499
1500 See Also:
1501
1502 <isEven>
1503 */
1504 BigInteger.prototype.isOdd = function() {
1505 return !this.isEven();
1506 };
1507
1508 /*
1509 Function: sign
1510 Get the sign of a <BigInteger>.
1511
1512 Returns:
1513
1514 * -1 if *this* < 0
1515 * 0 if *this* == 0
1516 * +1 if *this* > 0
1517
1518 See Also:
1519
1520 <isZero>, <isPositive>, <isNegative>, <compare>, <BigInteger.ZERO>
1521 */
1522 BigInteger.prototype.sign = function() {
1523 return this._s;
1524 };
1525
1526 /*
1527 Function: isPositive
1528 Return true iff *this* > 0.
1529
1530 Returns:
1531
1532 true if *this*.compare(<BigInteger.ZERO>) == 1.
1533
1534 See Also:
1535
1536 <sign>, <isZero>, <isNegative>, <isUnit>, <compare>, <BigInteger.ZERO>
1537 */
1538 BigInteger.prototype.isPositive = function() {
1539 return this._s > 0;
1540 };
1541
1542 /*
1543 Function: isNegative
1544 Return true iff *this* < 0.
1545
1546 Returns:
1547
1548 true if *this*.compare(<BigInteger.ZERO>) == -1.
1549
1550 See Also:
1551
1552 <sign>, <isPositive>, <isZero>, <isUnit>, <compare>, <BigInteger.ZERO>
1553 */
1554 BigInteger.prototype.isNegative = function() {
1555 return this._s < 0;
1556 };
1557
1558 /*
1559 Function: isZero
1560 Return true iff *this* == 0.
1561
1562 Returns:
1563
1564 true if *this*.compare(<BigInteger.ZERO>) == 0.
1565
1566 See Also:
1567
1568 <sign>, <isPositive>, <isNegative>, <isUnit>, <BigInteger.ZERO>
1569 */
1570 BigInteger.prototype.isZero = function() {
1571 return this._s === 0;
1572 };
1573
1574 /*
1575 Function: exp10
1576 Multiply a <BigInteger> by a power of 10.
1577
1578 This is equivalent to, but faster than
1579
1580 > if (n >= 0) {
1581 > return this.multiply(BigInteger("1e" + n));
1582 > }
1583 > else { // n <= 0
1584 > return this.quotient(BigInteger("1e" + -n));
1585 > }
1586
1587 Parameters:
1588
1589 n - The power of 10 to multiply *this* by. *n* is converted to a
1590 javascipt number and must be no greater than <BigInteger.MAX_EXP>
1591 (0x7FFFFFFF), or an exception will be thrown.
1592
1593 Returns:
1594
1595 *this* * (10 ** *n*), truncated to an integer if necessary.
1596
1597 See Also:
1598
1599 <pow>, <multiply>
1600 */
1601 BigInteger.prototype.exp10 = function(n) {
1602 n = +n;
1603 if (n === 0) {
1604 return this;
1605 }
1606 if (Math.abs(n) > Number(MAX_EXP)) {
1607 throw new Error("exponent too large in BigInteger.exp10");
1608 }
1609 // Optimization for this == 0. This also keeps us from having to trim zeros in the positive n case
1610 if (this._s === 0) {
1611 return ZERO;
1612 }
1613 if (n > 0) {
1614 var k = new BigInteger(this._d.slice(), this._s, CONSTRUCT);
1615
1616 for (; n >= BigInteger_base_log10; n -= BigInteger_base_log10) {
1617 k._d.unshift(0);
1618 }
1619 if (n == 0)
1620 return k;
1621 k._s = 1;
1622 k = k.multiplySingleDigit(Math.pow(10, n));
1623 return (this._s < 0 ? k.negate() : k);
1624 } else if (-n >= this._d.length*BigInteger_base_log10) {
1625 return ZERO;
1626 } else {
1627 var k = new BigInteger(this._d.slice(), this._s, CONSTRUCT);
1628
1629 for (n = -n; n >= BigInteger_base_log10; n -= BigInteger_base_log10) {
1630 k._d.shift();
1631 }
1632 return (n == 0) ? k : k.divRemSmall(Math.pow(10, n))[0];
1633 }
1634 };
1635
1636 /*
1637 Function: pow
1638 Raise a <BigInteger> to a power.
1639
1640 In this implementation, 0**0 is 1.
1641
1642 Parameters:
1643
1644 n - The exponent to raise *this* by. *n* must be no greater than
1645 <BigInteger.MAX_EXP> (0x7FFFFFFF), or an exception will be thrown.
1646
1647 Returns:
1648
1649 *this* raised to the *nth* power.
1650
1651 See Also:
1652
1653 <modPow>
1654 */
1655 BigInteger.prototype.pow = function(n) {
1656 if (this.isUnit()) {
1657 if (this._s > 0) {
1658 return this;
1659 }
1660 else {
1661 return BigInteger(n).isOdd() ? this : this.negate();
1662 }
1663 }
1664
1665 n = BigInteger(n);
1666 if (n._s === 0) {
1667 return ONE;
1668 }
1669 else if (n._s < 0) {
1670 if (this._s === 0) {
1671 throw new Error("Divide by zero");
1672 }
1673 else {
1674 return ZERO;
1675 }
1676 }
1677 if (this._s === 0) {
1678 return ZERO;
1679 }
1680 if (n.isUnit()) {
1681 return this;
1682 }
1683
1684 if (n.compareAbs(MAX_EXP) > 0) {
1685 throw new Error("exponent too large in BigInteger.pow");
1686 }
1687 var x = this;
1688 var aux = ONE;
1689 var two = BigInteger.small[2];
1690
1691 while (n.isPositive()) {
1692 if (n.isOdd()) {
1693 aux = aux.multiply(x);
1694 if (n.isUnit()) {
1695 return aux;
1696 }
1697 }
1698 x = x.square();
1699 n = n.quotient(two);
1700 }
1701
1702 return aux;
1703 };
1704
1705 /*
1706 Function: modPow
1707 Raise a <BigInteger> to a power (mod m).
1708
1709 Because it is reduced by a modulus, <modPow> is not limited by
1710 <BigInteger.MAX_EXP> like <pow>.
1711
1712 Parameters:
1713
1714 exponent - The exponent to raise *this* by. Must be positive.
1715 modulus - The modulus.
1716
1717 Returns:
1718
1719 *this* ^ *exponent* (mod *modulus*).
1720
1721 See Also:
1722
1723 <pow>, <mod>
1724 */
1725 BigInteger.prototype.modPow = function(exponent, modulus) {
1726 var result = ONE;
1727 var base = this;
1728
1729 while (exponent.isPositive()) {
1730 if (exponent.isOdd()) {
1731 result = result.multiply(base).remainder(modulus);
1732 }
1733
1734 exponent = exponent.quotient(BigInteger.small[2]);
1735 if (exponent.isPositive()) {
1736 base = base.square().remainder(modulus);
1737 }
1738 }
1739
1740 return result;
1741 };
1742
1743 /*
1744 Function: log
1745 Get the natural logarithm of a <BigInteger> as a native JavaScript number.
1746
1747 This is equivalent to
1748
1749 > Math.log(this.toJSValue())
1750
1751 but handles values outside of the native number range.
1752
1753 Returns:
1754
1755 log( *this* )
1756
1757 See Also:
1758
1759 <toJSValue>
1760 */
1761 BigInteger.prototype.log = function() {
1762 switch (this._s) {
1763 case 0: return -Infinity;
1764 case -1: return NaN;
1765 default: // Fall through.
1766 }
1767
1768 var l = this._d.length;
1769
1770 if (l*BigInteger_base_log10 < 30) {
1771 return Math.log(this.valueOf());
1772 }
1773
1774 var N = Math.ceil(30/BigInteger_base_log10);
1775 var firstNdigits = this._d.slice(l - N);
1776 return Math.log((new BigInteger(firstNdigits, 1, CONSTRUCT)).valueOf()) + (l - N) * Math.log(BigInteger_base);
1777 };
1778
1779 /*
1780 Function: valueOf
1781 Convert a <BigInteger> to a native JavaScript integer.
1782
1783 This is called automatically by JavaScipt to convert a <BigInteger> to a
1784 native value.
1785
1786 Returns:
1787
1788 > parseInt(this.toString(), 10)
1789
1790 See Also:
1791
1792 <toString>, <toJSValue>
1793 */
1794 BigInteger.prototype.valueOf = function() {
1795 return parseInt(this.toString(), 10);
1796 };
1797
1798 /*
1799 Function: toJSValue
1800 Convert a <BigInteger> to a native JavaScript integer.
1801
1802 This is the same as valueOf, but more explicitly named.
1803
1804 Returns:
1805
1806 > parseInt(this.toString(), 10)
1807
1808 See Also:
1809
1810 <toString>, <valueOf>
1811 */
1812 BigInteger.prototype.toJSValue = function() {
1813 return parseInt(this.toString(), 10);
1814 };
1815
1816 var MAX_EXP = BigInteger(0x7FFFFFFF);
1817 // Constant: MAX_EXP
1818 // The largest exponent allowed in <pow> and <exp10> (0x7FFFFFFF or 2147483647).
1819 BigInteger.MAX_EXP = MAX_EXP;
1820
1821 (function() {
1822 function makeUnary(fn) {
1823 return function(a) {
1824 return fn.call(BigInteger(a));
1825 };
1826 }
1827
1828 function makeBinary(fn) {
1829 return function(a, b) {
1830 return fn.call(BigInteger(a), BigInteger(b));
1831 };
1832 }
1833
1834 function makeTrinary(fn) {
1835 return function(a, b, c) {
1836 return fn.call(BigInteger(a), BigInteger(b), BigInteger(c));
1837 };
1838 }
1839
1840 (function() {
1841 var i, fn;
1842 var unary = "toJSValue,isEven,isOdd,sign,isZero,isNegative,abs,isUnit,square,negate,isPositive,toString,next,prev,log".split(",");
1843 var binary = "compare,remainder,divRem,subtract,add,quotient,divide,multiply,pow,compareAbs".split(",");
1844 var trinary = ["modPow"];
1845
1846 for (i = 0; i < unary.length; i++) {
1847 fn = unary[i];
1848 BigInteger[fn] = makeUnary(BigInteger.prototype[fn]);
1849 }
1850
1851 for (i = 0; i < binary.length; i++) {
1852 fn = binary[i];
1853 BigInteger[fn] = makeBinary(BigInteger.prototype[fn]);
1854 }
1855
1856 for (i = 0; i < trinary.length; i++) {
1857 fn = trinary[i];
1858 BigInteger[fn] = makeTrinary(BigInteger.prototype[fn]);
1859 }
1860
1861 BigInteger.exp10 = function(x, n) {
1862 return BigInteger(x).exp10(n);
1863 };
1864 })();
1865 })();
1866
1867 exports.BigInteger = BigInteger;
1868 })(typeof exports !== 'undefined' ? exports : this);