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