]>
git.immae.eu Git - perso/Immae/Projets/Cryptomonnaies/BIP39.git/blob - src/js/entropy.js
2 * Detects entropy from a string.
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
16 window
.Entropy
= new (function() {
18 // matchers returns an array of the matched events for each type of entropy.
20 // matchers.binary("010") returns ["0", "1", "0"]
21 // matchers.binary("a10") returns ["1", "0"]
22 // matchers.hex("a10") returns ["a", "1", "0"]
24 binary: function(str
) {
25 return str
.match(/[0-1]/gi) || [];
27 base6: function(str
) {
28 return str
.match(/[0-5]/gi) || [];
31 return str
.match(/[1-6]/gi) || []; // ie dice numbers
33 base10: function(str
) {
34 return str
.match(/[0-9]/gi) || [];
37 return str
.match(/[0-9A-F]/gi) || [];
40 // Format is NumberSuit, eg
47 return str
.match(/([A2-9TJQK][CDHS])/gi) || [];
51 // Convert array of cards from ["ac", "4d", "ks"]
52 // to numbers between 0 and 51 [0, 16, 51]
53 function convertCardsToInts(cards
) {
55 var values
= "a23456789tjqk";
57 for (var i
=0; i
<cards
.length
; i
++) {
58 var card
= cards
[i
].toLowerCase();
61 var asInt
= 13 * suits
.indexOf(suit
) + values
.indexOf(value
);
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") {
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
];
86 base
.str
= "base 6 (dice)";
88 base
.parts
= newParts
;
89 base
.matcher
= matchers
.base6
;
91 // Detect empty entropy
92 if (base
.parts
.length
== 0) {
100 // Convert base.ints to BigInteger.
101 // Due to using unusual bases, eg cards of base52, this is not as simple as
102 // using BigInteger.parse()
103 var entropyInt
= BigInteger
.ZERO
;
104 for (var i
=base
.ints
.length
-1; i
>=0; i
--) {
105 var thisInt
= BigInteger
.parse(base
.ints
[i
]);
106 var power
= (base
.ints
.length
- 1) - i
;
107 var additionalEntropy
= BigInteger
.parse(base
.asInt
).pow(power
).multiply(thisInt
);
108 entropyInt
= entropyInt
.add(additionalEntropy
);
110 // Convert entropy to binary
111 var entropyBin
= entropyInt
.toString(2);
112 // If the first integer is small, it must be padded with zeros.
113 // Otherwise the chance of the first bit being 1 is 100%, which is
114 // obviously incorrect.
115 // This is not perfect for non-2^n bases.
116 var expectedBits
= Math
.floor(base
.parts
.length
* Math
.log2(base
.asInt
));
117 while (entropyBin
.length
< expectedBits
) {
118 entropyBin
= "0" + entropyBin
;
120 // Supply a 'filtered' entropy string for display purposes
121 var entropyClean
= base
.parts
.join("");
122 var entropyHtml
= base
.parts
.join("");
123 if (base
.asInt
== 52) {
124 entropyClean
= base
.parts
.join(" ").toUpperCase();
125 entropyClean
= entropyClean
.replace(/C
/g
, "\u2663");
126 entropyClean
= entropyClean
.replace(/D
/g
, "\u2666");
127 entropyClean
= entropyClean
.replace(/H
/g
, "\u2665");
128 entropyClean
= entropyClean
.replace(/S
/g
, "\u2660");
129 entropyHtml
= base
.parts
.join(" ").toUpperCase();
130 entropyHtml
= entropyHtml
.replace(/C
/g
, "<span class='card-suit club'>\u2663</span>");
131 entropyHtml
= entropyHtml
.replace(/D
/g
, "<span class='card-suit diamond'>\u2666</span>");
132 entropyHtml
= entropyHtml
.replace(/H
/g
, "<span class='card-suit heart'>\u2665</span>");
133 entropyHtml
= entropyHtml
.replace(/S
/g
, "<span class='card-suit spade'>\u2660</span>");
136 binaryStr: entropyBin
,
137 cleanStr: entropyClean
,
138 cleanHtml: entropyHtml
,
144 function getBase(str
) {
145 // Need to get the lowest base for the supplied entropy.
146 // This prevents interpreting, say, dice rolls as hexadecimal.
147 var binaryMatches
= matchers
.binary(str
);
148 var hexMatches
= matchers
.hex(str
);
149 // Find the lowest base that can be used, whilst ignoring any irrelevant chars
150 if (binaryMatches
.length
== hexMatches
.length
&& hexMatches
.length
> 0) {
151 var ints
= binaryMatches
.map(function(i
) { return parseInt(i
, 2) });
154 parts: binaryMatches
,
155 matcher: matchers
.binary
,
160 var cardMatches
= matchers
.card(str
);
161 if (cardMatches
.length
>= hexMatches
.length
/ 2) {
162 var ints
= convertCardsToInts(cardMatches
);
166 matcher: matchers
.card
,
171 var diceMatches
= matchers
.dice(str
);
172 if (diceMatches
.length
== hexMatches
.length
&& hexMatches
.length
> 0) {
173 var ints
= diceMatches
.map(function(i
) { return parseInt(i
) });
177 matcher: matchers
.dice
,
182 var base6Matches
= matchers
.base6(str
);
183 if (base6Matches
.length
== hexMatches
.length
&& hexMatches
.length
> 0) {
184 var ints
= base6Matches
.map(function(i
) { return parseInt(i
) });
188 matcher: matchers
.base6
,
193 var base10Matches
= matchers
.base10(str
);
194 if (base10Matches
.length
== hexMatches
.length
&& hexMatches
.length
> 0) {
195 var ints
= base10Matches
.map(function(i
) { return parseInt(i
) });
198 parts: base10Matches
,
199 matcher: matchers
.base10
,
204 var ints
= hexMatches
.map(function(i
) { return parseInt(i
, 16) });
208 matcher: matchers
.hex
,
214 // Polyfill for Math.log2
215 // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/log2#Polyfill
216 Math
.log2
= Math
.log2
|| function(x
) {
217 // The polyfill isn't good enough because of the poor accuracy of
219 // log2(8) gave 2.9999999999999996 which when floored causes issues.
220 // So instead use the BigInteger library to get it right.
221 return BigInteger
.log(x
) / BigInteger
.log(2);
227 // BigInteger library included here because
228 // only the entropy library depends on it
229 // so if entropy detection is removed so is the dependency
233 JavaScript BigInteger library version 0.9.1
234 http://silentmatt.com/biginteger/
236 Copyright (c) 2009 Matthew Crumley <email@matthewcrumley.com>
237 Copyright (c) 2010,2011 by John Tobey <John.Tobey@gmail.com>
238 Licensed under the MIT license.
240 Support for arbitrary internal representation base was added by
255 An arbitrarily-large integer.
257 <BigInteger> objects should be considered immutable. None of the "built-in"
258 methods modify *this* or their arguments. All properties should be
261 All the methods of <BigInteger> instances can be called "statically". The
262 static versions are convenient if you don't already have a <BigInteger>
265 As an example, these calls are equivalent.
267 > BigInteger(4).multiply(5); // returns BigInteger(20);
268 > BigInteger.multiply(4, 5); // returns BigInteger(20);
271 > var a = BigInteger.toJSValue("0b101010"); // Not completely useless...
274 var CONSTRUCT
= {}; // Unique token to call "private" version of constructor
277 Constructor: BigInteger()
278 Convert a value to a <BigInteger>.
280 Although <BigInteger()> is the constructor for <BigInteger> objects, it is
281 best not to call it as a constructor. If *n* is a <BigInteger> object, it is
282 simply returned as-is. Otherwise, <BigInteger()> is equivalent to <parse>
283 without a radix argument.
285 > var n0 = BigInteger(); // Same as <BigInteger.ZERO>
286 > var n1 = BigInteger("123"); // Create a new <BigInteger> with value 123
287 > var n2 = BigInteger(123); // Create a new <BigInteger> with value 123
288 > var n3 = BigInteger(n2); // Return n2, unchanged
290 The constructor form only takes an array and a sign. *n* must be an
291 array of numbers in little-endian order, where each digit is between 0
292 and BigInteger.base. The second parameter sets the sign: -1 for
293 negative, +1 for positive, or 0 for zero. The array is *not copied and
294 may be modified*. If the array contains only zeros, the sign parameter
295 is ignored and is forced to zero.
297 > new BigInteger([5], -1): create a new BigInteger with value -5
301 n - Value to convert to a <BigInteger>.
305 A <BigInteger> value.
309 <parse>, <BigInteger>
311 function BigInteger(n
, s
, token
) {
312 if (token
!== CONSTRUCT
) {
313 if (n
instanceof BigInteger
) {
316 else if (typeof n
=== "undefined") {
319 return BigInteger
.parse(n
);
322 n
= n
|| []; // Provide the nullary constructor for subclasses.
323 while (n
.length
&& !n
[n
.length
- 1]) {
327 this._s
= n
.length
? (s
|| 1) : 0;
330 BigInteger
._construct = function(n
, s
) {
331 return new BigInteger(n
, s
, CONSTRUCT
);
334 // Base-10 speedup hacks in parse, toString, exp10 and log functions
335 // require base to be a power of 10. 10^7 is the largest such power
336 // that won't cause a precision loss when digits are multiplied.
337 var BigInteger_base
= 10000000;
338 var BigInteger_base_log10
= 7;
340 BigInteger
.base
= BigInteger_base
;
341 BigInteger
.base_log10
= BigInteger_base_log10
;
343 var ZERO
= new BigInteger([], 0, CONSTRUCT
);
346 BigInteger
.ZERO
= ZERO
;
348 var ONE
= new BigInteger([1], 1, CONSTRUCT
);
351 BigInteger
.ONE
= ONE
;
353 var M_ONE
= new BigInteger(ONE
._d
, -1, CONSTRUCT
);
356 BigInteger
.M_ONE
= M_ONE
;
359 // Shortcut for <ZERO>.
360 BigInteger
._0
= ZERO
;
363 // Shortcut for <ONE>.
368 Array of <BigIntegers> from 0 to 36.
370 These are used internally for parsing, but useful when you need a "small"
375 <ZERO>, <ONE>, <_0>, <_1>
380 /* Assuming BigInteger_base > 36 */
381 new BigInteger( [2], 1, CONSTRUCT
),
382 new BigInteger( [3], 1, CONSTRUCT
),
383 new BigInteger( [4], 1, CONSTRUCT
),
384 new BigInteger( [5], 1, CONSTRUCT
),
385 new BigInteger( [6], 1, CONSTRUCT
),
386 new BigInteger( [7], 1, CONSTRUCT
),
387 new BigInteger( [8], 1, CONSTRUCT
),
388 new BigInteger( [9], 1, CONSTRUCT
),
389 new BigInteger([10], 1, CONSTRUCT
),
390 new BigInteger([11], 1, CONSTRUCT
),
391 new BigInteger([12], 1, CONSTRUCT
),
392 new BigInteger([13], 1, CONSTRUCT
),
393 new BigInteger([14], 1, CONSTRUCT
),
394 new BigInteger([15], 1, CONSTRUCT
),
395 new BigInteger([16], 1, CONSTRUCT
),
396 new BigInteger([17], 1, CONSTRUCT
),
397 new BigInteger([18], 1, CONSTRUCT
),
398 new BigInteger([19], 1, CONSTRUCT
),
399 new BigInteger([20], 1, CONSTRUCT
),
400 new BigInteger([21], 1, CONSTRUCT
),
401 new BigInteger([22], 1, CONSTRUCT
),
402 new BigInteger([23], 1, CONSTRUCT
),
403 new BigInteger([24], 1, CONSTRUCT
),
404 new BigInteger([25], 1, CONSTRUCT
),
405 new BigInteger([26], 1, CONSTRUCT
),
406 new BigInteger([27], 1, CONSTRUCT
),
407 new BigInteger([28], 1, CONSTRUCT
),
408 new BigInteger([29], 1, CONSTRUCT
),
409 new BigInteger([30], 1, CONSTRUCT
),
410 new BigInteger([31], 1, CONSTRUCT
),
411 new BigInteger([32], 1, CONSTRUCT
),
412 new BigInteger([33], 1, CONSTRUCT
),
413 new BigInteger([34], 1, CONSTRUCT
),
414 new BigInteger([35], 1, CONSTRUCT
),
415 new BigInteger([36], 1, CONSTRUCT
)
418 // Used for parsing/radix conversion
419 BigInteger
.digits
= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");
423 Convert a <BigInteger> to a string.
425 When *base* is greater than 10, letters are upper case.
429 base - Optional base to represent the number in (default is base 10).
430 Must be between 2 and 36 inclusive, or an Error will be thrown.
434 The string representation of the <BigInteger>.
436 BigInteger
.prototype.toString = function(base
) {
438 if (base
< 2 || base
> 36) {
439 throw new Error("illegal radix " + base
+ ".");
445 var str
= this._s
< 0 ? "-" : "";
446 str
+= this._d
[this._d
.length
- 1].toString();
447 for (var i
= this._d
.length
- 2; i
>= 0; i
--) {
448 var group
= this._d
[i
].toString();
449 while (group
.length
< BigInteger_base_log10
) group
= '0' + group
;
455 var numerals
= BigInteger
.digits
;
456 base
= BigInteger
.small
[base
];
464 var divmod
= n
.divRem(base
);
467 // TODO: This could be changed to unshift instead of reversing at the end.
468 // Benchmark both to compare speeds.
469 digits
.push(numerals
[digit
.valueOf()]);
471 return (sign
< 0 ? "-" : "") + digits
.reverse().join("");
475 // Verify strings for parsing
476 BigInteger
.radixRegex
= [
518 Parse a string into a <BigInteger>.
520 *base* is optional but, if provided, must be from 2 to 36 inclusive. If
521 *base* is not provided, it will be guessed based on the leading characters
524 - "0x" or "0X": *base* = 16
525 - "0c" or "0C": *base* = 8
526 - "0b" or "0B": *base* = 2
529 If no base is provided, or *base* is 10, the number can be in exponential
530 form. For example, these are all valid:
532 > BigInteger.parse("1e9"); // Same as "1000000000"
533 > BigInteger.parse("1.234*10^3"); // Same as 1234
534 > BigInteger.parse("56789 * 10 ** -2"); // Same as 567
536 If any characters fall outside the range defined by the radix, an exception
541 s - The string to parse.
542 base - Optional radix (default is to guess based on *s*).
546 a <BigInteger> instance.
548 BigInteger
.parse = function(s
, base
) {
549 // Expands a number in exponential form to decimal form.
550 // expandExponential("-13.441*10^5") === "1344100";
551 // expandExponential("1.12300e-1") === "0.112300";
552 // expandExponential(1000000000000000000000000000000) === "1000000000000000000000000000000";
553 function expandExponential(str
) {
554 str
= str
.replace(/\s*[*xX]\s*10\s*(\^|\*\*)\s*/, "e");
556 return str
.replace(/^([+\-])?(\d+)\.?(\d*)[eE]([+\-]?\d+)$/, function(x
, s
, n
, f
, c
) {
559 var i
= n
.length
+ c
;
560 x
= (l
? n : f
).length
;
561 c
= ((c
= Math
.abs(c
)) >= x
? c
- x
+ l : 0);
562 var z
= (new Array(c
+ 1)).join("0");
564 return (s
|| "") + (l
? r
= z
+ r : r
+= z
).substr(0, i
+= l
? z
.length : 0) + (i
< r
.length
? "." + r
.substr(i
) : "");
569 if (typeof base
=== "undefined" || +base
=== 10) {
570 s
= expandExponential(s
);
574 if (typeof base
=== "undefined") {
577 else if (base
== 16) {
580 else if (base
== 8) {
583 else if (base
== 2) {
589 var parts
= new RegExp('^([+\\-]?)(' + prefixRE
+ ')?([0-9a-z]*)(?:\\.\\d*)?$', 'i').exec(s
);
591 var sign
= parts
[1] || "+";
592 var baseSection
= parts
[2] || "";
593 var digits
= parts
[3] || "";
595 if (typeof base
=== "undefined") {
597 if (baseSection
=== "0x" || baseSection
=== "0X") { // Hex
600 else if (baseSection
=== "0c" || baseSection
=== "0C") { // Octal
603 else if (baseSection
=== "0b" || baseSection
=== "0B") { // Binary
610 else if (base
< 2 || base
> 36) {
611 throw new Error("Illegal radix " + base
+ ".");
616 // Check for digits outside the range
617 if (!(BigInteger
.radixRegex
[base
].test(digits
))) {
618 throw new Error("Bad digit for radix " + base
);
621 // Strip leading zeros, and convert to array
622 digits
= digits
.replace(/^0+/, "").split("");
623 if (digits
.length
=== 0) {
627 // Get the sign (we know it's not zero)
628 sign
= (sign
=== "-") ? -1 : 1;
633 while (digits
.length
>= BigInteger_base_log10
) {
634 d
.push(parseInt(digits
.splice(digits
.length
-BigInteger
.base_log10
, BigInteger
.base_log10
).join(''), 10));
636 d
.push(parseInt(digits
.join(''), 10));
637 return new BigInteger(d
, sign
, CONSTRUCT
);
642 base
= BigInteger
.small
[base
];
643 var small
= BigInteger
.small
;
644 for (var i
= 0; i
< digits
.length
; i
++) {
645 d
= d
.multiply(base
).add(small
[parseInt(digits
[i
], 36)]);
647 return new BigInteger(d
._d
, sign
, CONSTRUCT
);
650 throw new Error("Invalid BigInteger format: " + s
);
656 Add two <BigIntegers>.
660 n - The number to add to *this*. Will be converted to a <BigInteger>.
664 The numbers added together.
668 <subtract>, <multiply>, <quotient>, <next>
670 BigInteger
.prototype.add = function(n
) {
672 return BigInteger(n
);
679 if (this._s
!== n
._s
) {
681 return this.subtract(n
);
688 var sum
= new Array(Math
.max(al
, bl
) + 1);
689 var size
= Math
.min(al
, bl
);
693 for (var i
= 0; i
< size
; i
++) {
694 digit
= a
[i
] + b
[i
] + carry
;
695 sum
[i
] = digit
% BigInteger_base
;
696 carry
= (digit
/ BigInteger_base
) | 0;
702 for (i
= size
; carry
&& i
< al
; i
++) {
703 digit
= a
[i
] + carry
;
704 sum
[i
] = digit
% BigInteger_base
;
705 carry
= (digit
/ BigInteger_base
) | 0;
711 for ( ; i
< al
; i
++) {
715 return new BigInteger(sum
, this._s
, CONSTRUCT
);
720 Get the additive inverse of a <BigInteger>.
724 A <BigInteger> with the same magnatude, but with the opposite sign.
730 BigInteger
.prototype.negate = function() {
731 return new BigInteger(this._d
, (-this._s
) | 0, CONSTRUCT
);
736 Get the absolute value of a <BigInteger>.
740 A <BigInteger> with the same magnatude, but always positive (or zero).
746 BigInteger
.prototype.abs = function() {
747 return (this._s
< 0) ? this.negate() : this;
752 Subtract two <BigIntegers>.
756 n - The number to subtract from *this*. Will be converted to a <BigInteger>.
760 The *n* subtracted from *this*.
764 <add>, <multiply>, <quotient>, <prev>
766 BigInteger
.prototype.subtract = function(n
) {
768 return BigInteger(n
).negate();
775 if (this._s
!== n
._s
) {
781 // negative - negative => -|a| - -|b| => -|a| + |b| => |b| - |a|
783 m
= new BigInteger(n
._d
, 1, CONSTRUCT
);
784 n
= new BigInteger(this._d
, 1, CONSTRUCT
);
787 // Both are positive => a - b
788 var sign
= m
.compareAbs(n
);
804 var diff
= new Array(al
); // al >= bl since a > b
809 for (i
= 0; i
< bl
; i
++) {
810 digit
= a
[i
] - borrow
- b
[i
];
812 digit
+= BigInteger_base
;
820 for (i
= bl
; i
< al
; i
++) {
821 digit
= a
[i
] - borrow
;
823 digit
+= BigInteger_base
;
831 for ( ; i
< al
; i
++) {
835 return new BigInteger(diff
, sign
, CONSTRUCT
);
839 function addOne(n
, sign
) {
846 var digit
= (a
[i
] || 0) + 1;
847 sum
[i
] = digit
% BigInteger_base
;
848 if (digit
<= BigInteger_base
- 1) {
854 return new BigInteger(sum
, sign
, CONSTRUCT
);
857 function subtractOne(n
, sign
) {
864 var digit
= (a
[i
] || 0) - 1;
866 sum
[i
] = digit
+ BigInteger_base
;
875 return new BigInteger(sum
, sign
, CONSTRUCT
);
880 Get the next <BigInteger> (add one).
890 BigInteger
.prototype.next = function() {
895 return subtractOne(this, -1);
898 return addOne(this, 1);
904 Get the previous <BigInteger> (subtract one).
914 BigInteger
.prototype.prev = function() {
919 return addOne(this, -1);
922 return subtractOne(this, 1);
929 Compare the absolute value of two <BigIntegers>.
931 Calling <compareAbs> is faster than calling <abs> twice, then <compare>.
935 n - The number to compare to *this*. Will be converted to a <BigInteger>.
939 -1, 0, or +1 if *|this|* is less than, equal to, or greater than *|n|*.
945 BigInteger
.prototype.compareAbs = function(n
) {
950 if (!(n
instanceof BigInteger
)) {
952 return(isNaN(n
) ? n : -1);
958 return (n
._s
!== 0) ? -1 : 0;
964 var l
= this._d
.length
;
965 var nl
= n
._d
.length
;
975 for (var i
= l
-1; i
>= 0; i
--) {
977 return a
[i
] < b
[i
] ? -1 : 1;
986 Compare two <BigIntegers>.
990 n - The number to compare to *this*. Will be converted to a <BigInteger>.
994 -1, 0, or +1 if *this* is less than, equal to, or greater than *n*.
998 <compareAbs>, <isPositive>, <isNegative>, <isUnit>
1000 BigInteger
.prototype.compare = function(n
) {
1007 if (this._s
=== 0) {
1011 if (this._s
=== n
._s
) { // both positive or both negative
1012 var cmp
= this.compareAbs(n
);
1013 return cmp
* this._s
;
1022 Return true iff *this* is either 1 or -1.
1026 true if *this* compares equal to <BigInteger.ONE> or <BigInteger.M_ONE>.
1030 <isZero>, <isNegative>, <isPositive>, <compareAbs>, <compare>,
1031 <BigInteger.ONE>, <BigInteger.M_ONE>
1033 BigInteger
.prototype.isUnit = function() {
1034 return this === ONE
||
1036 (this._d
.length
=== 1 && this._d
[0] === 1);
1041 Multiply two <BigIntegers>.
1045 n - The number to multiply *this* by. Will be converted to a
1050 The numbers multiplied together.
1054 <add>, <subtract>, <quotient>, <square>
1056 BigInteger
.prototype.multiply = function(n
) {
1057 // TODO: Consider adding Karatsuba multiplication for large numbers
1058 if (this._s
=== 0) {
1066 if (this.isUnit()) {
1074 return this.negate();
1079 return this.square();
1082 var r
= (this._d
.length
>= n
._d
.length
);
1083 var a
= (r
? this : n
)._d
; // a will be longer than b
1084 var b
= (r
? n : this)._d
;
1089 var partial
= new Array(pl
);
1091 for (i
= 0; i
< pl
; i
++) {
1095 for (i
= 0; i
< bl
; i
++) {
1098 var jlimit
= al
+ i
;
1100 for (var j
= i
; j
< jlimit
; j
++) {
1101 digit
= partial
[j
] + bi
* a
[j
- i
] + carry
;
1102 carry
= (digit
/ BigInteger_base
) | 0;
1103 partial
[j
] = (digit
% BigInteger_base
) | 0;
1106 digit
= partial
[j
] + carry
;
1107 carry
= (digit
/ BigInteger_base
) | 0;
1108 partial
[j
] = digit
% BigInteger_base
;
1111 return new BigInteger(partial
, this._s
* n
._s
, CONSTRUCT
);
1114 // Multiply a BigInteger by a single-digit native number
1115 // Assumes that this and n are >= 0
1116 // This is not really intended to be used outside the library itself
1117 BigInteger
.prototype.multiplySingleDigit = function(n
) {
1118 if (n
=== 0 || this._s
=== 0) {
1126 if (this._d
.length
=== 1) {
1127 digit
= this._d
[0] * n
;
1128 if (digit
>= BigInteger_base
) {
1129 return new BigInteger([(digit
% BigInteger_base
)|0,
1130 (digit
/ BigInteger_base
)|0], 1, CONSTRUCT
);
1132 return new BigInteger([digit
], 1, CONSTRUCT
);
1136 return this.add(this);
1138 if (this.isUnit()) {
1139 return new BigInteger([n
], 1, CONSTRUCT
);
1146 var partial
= new Array(pl
);
1147 for (var i
= 0; i
< pl
; i
++) {
1152 for (var j
= 0; j
< al
; j
++) {
1153 digit
= n
* a
[j
] + carry
;
1154 carry
= (digit
/ BigInteger_base
) | 0;
1155 partial
[j
] = (digit
% BigInteger_base
) | 0;
1161 return new BigInteger(partial
, 1, CONSTRUCT
);
1166 Multiply a <BigInteger> by itself.
1168 This is slightly faster than regular multiplication, since it removes the
1169 duplicated multiplcations.
1173 > this.multiply(this)
1178 BigInteger
.prototype.square = function() {
1179 // Normally, squaring a 10-digit number would take 100 multiplications.
1180 // Of these 10 are unique diagonals, of the remaining 90 (100-10), 45 are repeated.
1181 // This procedure saves (N*(N-1))/2 multiplications, (e.g., 45 of 100 multiplies).
1182 // Based on code by Gary Darby, Intellitech Systems Inc., www.DelphiForFun.org
1184 if (this._s
=== 0) {
1187 if (this.isUnit()) {
1191 var digits
= this._d
;
1192 var length
= digits
.length
;
1193 var imult1
= new Array(length
+ length
+ 1);
1194 var product
, carry
, k
;
1197 // Calculate diagonal
1198 for (i
= 0; i
< length
; i
++) {
1200 product
= digits
[i
] * digits
[i
];
1201 carry
= (product
/ BigInteger_base
) | 0;
1202 imult1
[k
] = product
% BigInteger_base
;
1203 imult1
[k
+ 1] = carry
;
1206 // Calculate repeating part
1207 for (i
= 0; i
< length
; i
++) {
1210 for (var j
= i
+ 1; j
< length
; j
++, k
++) {
1211 product
= digits
[j
] * digits
[i
] * 2 + imult1
[k
] + carry
;
1212 carry
= (product
/ BigInteger_base
) | 0;
1213 imult1
[k
] = product
% BigInteger_base
;
1216 var digit
= carry
+ imult1
[k
];
1217 carry
= (digit
/ BigInteger_base
) | 0;
1218 imult1
[k
] = digit
% BigInteger_base
;
1219 imult1
[k
+ 1] += carry
;
1222 return new BigInteger(imult1
, 1, CONSTRUCT
);
1227 Divide two <BigIntegers> and truncate towards zero.
1229 <quotient> throws an exception if *n* is zero.
1233 n - The number to divide *this* by. Will be converted to a <BigInteger>.
1237 The *this* / *n*, truncated to an integer.
1241 <add>, <subtract>, <multiply>, <divRem>, <remainder>
1243 BigInteger
.prototype.quotient = function(n
) {
1244 return this.divRem(n
)[0];
1249 Deprecated synonym for <quotient>.
1251 BigInteger
.prototype.divide
= BigInteger
.prototype.quotient
;
1255 Calculate the remainder of two <BigIntegers>.
1257 <remainder> throws an exception if *n* is zero.
1261 n - The remainder after *this* is divided *this* by *n*. Will be
1262 converted to a <BigInteger>.
1270 <divRem>, <quotient>
1272 BigInteger
.prototype.remainder = function(n
) {
1273 return this.divRem(n
)[1];
1278 Calculate the integer quotient and remainder of two <BigIntegers>.
1280 <divRem> throws an exception if *n* is zero.
1284 n - The number to divide *this* by. Will be converted to a <BigInteger>.
1288 A two-element array containing the quotient and the remainder.
1292 is exactly equivalent to
1294 > [a.quotient(b), a.remainder(b)]
1296 except it is faster, because they are calculated at the same time.
1300 <quotient>, <remainder>
1302 BigInteger
.prototype.divRem = function(n
) {
1305 throw new Error("Divide by zero");
1307 if (this._s
=== 0) {
1308 return [ZERO
, ZERO
];
1310 if (n
._d
.length
=== 1) {
1311 return this.divRemSmall(n
._s
* n
._d
[0]);
1314 // Test for easy cases -- |n1| <= |n2|
1315 switch (this.compareAbs(n
)) {
1317 return [this._s
=== n
._s
? ONE : M_ONE
, ZERO
];
1318 case -1: // |n1| < |n2|
1319 return [ZERO
, this];
1322 var sign
= this._s
* n
._s
;
1324 var b_digits
= this._d
;
1325 var b_index
= b_digits
.length
;
1326 var digits
= n
._d
.length
;
1330 var part
= new BigInteger([], 0, CONSTRUCT
);
1333 part
._d
.unshift(b_digits
[--b_index
]);
1334 part
= new BigInteger(part
._d
, 1, CONSTRUCT
);
1336 if (part
.compareAbs(n
) < 0) {
1340 if (part
._s
=== 0) {
1344 var xlen
= part
._d
.length
, ylen
= a
._d
.length
;
1345 var highx
= part
._d
[xlen
-1]*BigInteger_base
+ part
._d
[xlen
-2];
1346 var highy
= a
._d
[ylen
-1]*BigInteger_base
+ a
._d
[ylen
-2];
1347 if (part
._d
.length
> a
._d
.length
) {
1348 // The length of part._d can either match a._d length,
1349 // or exceed it by one.
1350 highx
= (highx
+1)*BigInteger_base
;
1352 guess
= Math
.ceil(highx
/highy
);
1355 var check
= a
.multiplySingleDigit(guess
);
1356 if (check
.compareAbs(part
) <= 0) {
1366 var diff
= part
.subtract(check
);
1367 part
._d
= diff
._d
.slice();
1370 return [new BigInteger(quot
.reverse(), sign
, CONSTRUCT
),
1371 new BigInteger(part
._d
, this._s
, CONSTRUCT
)];
1374 // Throws an exception if n is outside of (-BigInteger.base, -1] or
1375 // [1, BigInteger.base). It's not necessary to call this, since the
1376 // other division functions will call it if they are able to.
1377 BigInteger
.prototype.divRemSmall = function(n
) {
1381 throw new Error("Divide by zero");
1384 var n_s
= n
< 0 ? -1 : 1;
1385 var sign
= this._s
* n_s
;
1388 if (n
< 1 || n
>= BigInteger_base
) {
1389 throw new Error("Argument out of range");
1392 if (this._s
=== 0) {
1393 return [ZERO
, ZERO
];
1396 if (n
=== 1 || n
=== -1) {
1397 return [(sign
=== 1) ? this.abs() : new BigInteger(this._d
, sign
, CONSTRUCT
), ZERO
];
1400 // 2 <= n < BigInteger_base
1402 // divide a single digit by a single digit
1403 if (this._d
.length
=== 1) {
1404 var q
= new BigInteger([(this._d
[0] / n
) | 0], 1, CONSTRUCT
);
1405 r
= new BigInteger([(this._d
[0] % n
) | 0], 1, CONSTRUCT
);
1415 var digits
= this._d
.slice();
1416 var quot
= new Array(digits
.length
);
1422 while (digits
.length
) {
1423 part
= part
* BigInteger_base
+ digits
[digits
.length
- 1];
1427 diff
= BigInteger_base
* diff
+ part
;
1434 guess
= (part
/ n
) | 0;
1437 var check
= n
* guess
;
1438 diff
= part
- check
;
1449 r
= new BigInteger([diff
], 1, CONSTRUCT
);
1453 return [new BigInteger(quot
.reverse(), sign
, CONSTRUCT
), r
];
1458 Return true iff *this* is divisible by two.
1460 Note that <BigInteger.ZERO> is even.
1464 true if *this* is even, false otherwise.
1470 BigInteger
.prototype.isEven = function() {
1471 var digits
= this._d
;
1472 return this._s
=== 0 || digits
.length
=== 0 || (digits
[0] % 2) === 0;
1477 Return true iff *this* is not divisible by two.
1481 true if *this* is odd, false otherwise.
1487 BigInteger
.prototype.isOdd = function() {
1488 return !this.isEven();
1493 Get the sign of a <BigInteger>.
1503 <isZero>, <isPositive>, <isNegative>, <compare>, <BigInteger.ZERO>
1505 BigInteger
.prototype.sign = function() {
1510 Function: isPositive
1511 Return true iff *this* > 0.
1515 true if *this*.compare(<BigInteger.ZERO>) == 1.
1519 <sign>, <isZero>, <isNegative>, <isUnit>, <compare>, <BigInteger.ZERO>
1521 BigInteger
.prototype.isPositive = function() {
1526 Function: isNegative
1527 Return true iff *this* < 0.
1531 true if *this*.compare(<BigInteger.ZERO>) == -1.
1535 <sign>, <isPositive>, <isZero>, <isUnit>, <compare>, <BigInteger.ZERO>
1537 BigInteger
.prototype.isNegative = function() {
1543 Return true iff *this* == 0.
1547 true if *this*.compare(<BigInteger.ZERO>) == 0.
1551 <sign>, <isPositive>, <isNegative>, <isUnit>, <BigInteger.ZERO>
1553 BigInteger
.prototype.isZero = function() {
1554 return this._s
=== 0;
1559 Multiply a <BigInteger> by a power of 10.
1561 This is equivalent to, but faster than
1564 > return this.multiply(BigInteger("1e" + n));
1567 > return this.quotient(BigInteger("1e" + -n));
1572 n - The power of 10 to multiply *this* by. *n* is converted to a
1573 javascipt number and must be no greater than <BigInteger.MAX_EXP>
1574 (0x7FFFFFFF), or an exception will be thrown.
1578 *this* * (10 ** *n*), truncated to an integer if necessary.
1584 BigInteger
.prototype.exp10 = function(n
) {
1589 if (Math
.abs(n
) > Number(MAX_EXP
)) {
1590 throw new Error("exponent too large in BigInteger.exp10");
1592 // Optimization for this == 0. This also keeps us from having to trim zeros in the positive n case
1593 if (this._s
=== 0) {
1597 var k
= new BigInteger(this._d
.slice(), this._s
, CONSTRUCT
);
1599 for (; n
>= BigInteger_base_log10
; n
-= BigInteger_base_log10
) {
1605 k
= k
.multiplySingleDigit(Math
.pow(10, n
));
1606 return (this._s
< 0 ? k
.negate() : k
);
1607 } else if (-n
>= this._d
.length
*BigInteger_base_log10
) {
1610 var k
= new BigInteger(this._d
.slice(), this._s
, CONSTRUCT
);
1612 for (n
= -n
; n
>= BigInteger_base_log10
; n
-= BigInteger_base_log10
) {
1615 return (n
== 0) ? k : k
.divRemSmall(Math
.pow(10, n
))[0];
1621 Raise a <BigInteger> to a power.
1623 In this implementation, 0**0 is 1.
1627 n - The exponent to raise *this* by. *n* must be no greater than
1628 <BigInteger.MAX_EXP> (0x7FFFFFFF), or an exception will be thrown.
1632 *this* raised to the *nth* power.
1638 BigInteger
.prototype.pow = function(n
) {
1639 if (this.isUnit()) {
1644 return BigInteger(n
).isOdd() ? this : this.negate();
1652 else if (n
._s
< 0) {
1653 if (this._s
=== 0) {
1654 throw new Error("Divide by zero");
1660 if (this._s
=== 0) {
1667 if (n
.compareAbs(MAX_EXP
) > 0) {
1668 throw new Error("exponent too large in BigInteger.pow");
1672 var two
= BigInteger
.small
[2];
1674 while (n
.isPositive()) {
1676 aux
= aux
.multiply(x
);
1682 n
= n
.quotient(two
);
1690 Raise a <BigInteger> to a power (mod m).
1692 Because it is reduced by a modulus, <modPow> is not limited by
1693 <BigInteger.MAX_EXP> like <pow>.
1697 exponent - The exponent to raise *this* by. Must be positive.
1698 modulus - The modulus.
1702 *this* ^ *exponent* (mod *modulus*).
1708 BigInteger
.prototype.modPow = function(exponent
, modulus
) {
1712 while (exponent
.isPositive()) {
1713 if (exponent
.isOdd()) {
1714 result
= result
.multiply(base
).remainder(modulus
);
1717 exponent
= exponent
.quotient(BigInteger
.small
[2]);
1718 if (exponent
.isPositive()) {
1719 base
= base
.square().remainder(modulus
);
1728 Get the natural logarithm of a <BigInteger> as a native JavaScript number.
1730 This is equivalent to
1732 > Math.log(this.toJSValue())
1734 but handles values outside of the native number range.
1744 BigInteger
.prototype.log = function() {
1746 case 0: return -Infinity
;
1747 case -1: return NaN
;
1748 default: // Fall through.
1751 var l
= this._d
.length
;
1753 if (l
*BigInteger_base_log10
< 30) {
1754 return Math
.log(this.valueOf());
1757 var N
= Math
.ceil(30/BigInteger_base_log10
);
1758 var firstNdigits
= this._d
.slice(l
- N
);
1759 return Math
.log((new BigInteger(firstNdigits
, 1, CONSTRUCT
)).valueOf()) + (l
- N
) * Math
.log(BigInteger_base
);
1764 Convert a <BigInteger> to a native JavaScript integer.
1766 This is called automatically by JavaScipt to convert a <BigInteger> to a
1771 > parseInt(this.toString(), 10)
1775 <toString>, <toJSValue>
1777 BigInteger
.prototype.valueOf = function() {
1778 return parseInt(this.toString(), 10);
1783 Convert a <BigInteger> to a native JavaScript integer.
1785 This is the same as valueOf, but more explicitly named.
1789 > parseInt(this.toString(), 10)
1793 <toString>, <valueOf>
1795 BigInteger
.prototype.toJSValue = function() {
1796 return parseInt(this.toString(), 10);
1799 var MAX_EXP
= BigInteger(0x7FFFFFFF);
1800 // Constant: MAX_EXP
1801 // The largest exponent allowed in <pow> and <exp10> (0x7FFFFFFF or 2147483647).
1802 BigInteger
.MAX_EXP
= MAX_EXP
;
1805 function makeUnary(fn
) {
1806 return function(a
) {
1807 return fn
.call(BigInteger(a
));
1811 function makeBinary(fn
) {
1812 return function(a
, b
) {
1813 return fn
.call(BigInteger(a
), BigInteger(b
));
1817 function makeTrinary(fn
) {
1818 return function(a
, b
, c
) {
1819 return fn
.call(BigInteger(a
), BigInteger(b
), BigInteger(c
));
1825 var unary
= "toJSValue,isEven,isOdd,sign,isZero,isNegative,abs,isUnit,square,negate,isPositive,toString,next,prev,log".split(",");
1826 var binary
= "compare,remainder,divRem,subtract,add,quotient,divide,multiply,pow,compareAbs".split(",");
1827 var trinary
= ["modPow"];
1829 for (i
= 0; i
< unary
.length
; i
++) {
1831 BigInteger
[fn
] = makeUnary(BigInteger
.prototype[fn
]);
1834 for (i
= 0; i
< binary
.length
; i
++) {
1836 BigInteger
[fn
] = makeBinary(BigInteger
.prototype[fn
]);
1839 for (i
= 0; i
< trinary
.length
; i
++) {
1841 BigInteger
[fn
] = makeTrinary(BigInteger
.prototype[fn
]);
1844 BigInteger
.exp10 = function(x
, n
) {
1845 return BigInteger(x
).exp10(n
);
1850 exports
.BigInteger
= BigInteger
;
1851 })(typeof exports
!== 'undefined' ? exports : this);