]>
git.immae.eu Git - perso/Immae/Projets/Cryptomonnaies/BIP39.git/blob - src/js/entropy.js
1 window
.Entropy
= new (function() {
6 dice: /[1-6]/gi, // ie dice numbers
11 this.fromString = function(rawEntropyStr
) {
12 // Find type of entropy being used (binary, hex, dice etc)
13 var base
= getBase(rawEntropyStr
);
14 // Convert dice to base6 entropy (ie 1-6 to 0-5)
15 if (base
.str
== "dice") {
16 var newRawEntropyStr
= "";
17 for (var i
=0; i
<rawEntropyStr
.length
; i
++) {
18 var c
= rawEntropyStr
[i
];
19 if ("123456".indexOf(c
) > -1) {
20 newRawEntropyStr
+= (parseInt(c
) - 1).toString();
26 rawEntropyStr
= newRawEntropyStr
;
27 base
.str
= "base 6 (dice)";
28 base
.matcher
= matchers
.base6
;
30 var entropyParts
= rawEntropyStr
.match(base
.matcher
) || [];
31 var entropyStr
= entropyParts
.join("");
32 // Detect empty entropy
33 if (entropyStr
.length
== 0) {
41 // Pull leading zeros off
42 var leadingZeros
= "";
43 while (entropyStr
[0] == "0") {
45 entropyStr
= entropyStr
.substring(1);
47 // Convert leading zeros to binary equivalent
48 var numBinLeadingZeros
= Math
.ceil(Math
.log2(base
.asInt
) * leadingZeros
.length
);
49 var binLeadingZeros
= "";
50 for (var i
=0; i
<numBinLeadingZeros
; i
++) {
51 binLeadingZeros
+= "0";
53 // Convert leading zeros to hex equivalent
54 var numHexLeadingZeros
= Math
.floor(numBinLeadingZeros
/ 4);
55 var hexLeadingZeros
= "";
56 for (var i
=0; i
<numHexLeadingZeros
; i
++) {
57 hexLeadingZeros
+= "0";
59 // Handle entropy of zero
60 if (entropyStr
== "") {
62 binaryStr: binLeadingZeros
,
63 hexStr: hexLeadingZeros
|| "0",
64 cleanStr: leadingZeros
,
68 // If using hex, should always be multiples of 4 bits, which can get
69 // out of sync if first number has leading 0 bits, eg 2 in hex is 0010
70 // which would show up as 10, thus missing 2 bits it should have.
71 if (base
.asInt
== 16) {
72 var firstDigit
= parseInt(entropyStr
[0], 16);
73 if (firstDigit
>= 4 && firstDigit
< 8) {
74 binLeadingZeros
+= "0";
76 else if (firstDigit
>= 2 && firstDigit
< 4) {
77 binLeadingZeros
+= "00";
79 else if (firstDigit
>= 1 && firstDigit
< 2) {
80 binLeadingZeros
+= "000";
83 // Convert entropy to different foramts
84 var entropyInt
= BigInteger
.parse(entropyStr
, base
.asInt
);
85 var entropyBin
= binLeadingZeros
+ entropyInt
.toString(2);
86 var entropyHex
= hexLeadingZeros
+ entropyInt
.toString(16);
87 var entropyClean
= leadingZeros
+ entropyStr
;
89 binaryStr: entropyBin
,
91 cleanStr: entropyClean
,
97 function getBase(str
) {
98 // Need to get the lowest base for the supplied entropy.
99 // This prevents interpreting, say, dice rolls as hexadecimal.
100 var binaryMatches
= str
.match(matchers
.binary
) || [];
101 var base6Matches
= str
.match(matchers
.base6
) || [];
102 var diceMatches
= str
.match(matchers
.dice
) || [];
103 var base10Matches
= str
.match(matchers
.base10
) || [];
104 var hexMatches
= str
.match(matchers
.hex
) || [];
105 // Find the lowest base that can be used, whilst ignoring any irrelevant chars
106 if (binaryMatches
.length
== hexMatches
.length
) {
108 matcher: matchers
.binary
,
113 if (diceMatches
.length
== hexMatches
.length
) {
115 matcher: matchers
.dice
,
120 if (base6Matches
.length
== hexMatches
.length
) {
122 matcher: matchers
.base6
,
127 if (base10Matches
.length
== hexMatches
.length
) {
129 matcher: matchers
.base10
,
135 matcher: matchers
.hex
,
141 // Polyfill for Math.log2
142 // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/log2#Polyfill
143 Math
.log2
= Math
.log2
|| function(x
) {
144 return Math
.log(x
) * Math
.LOG2E
;
150 // BigInteger library included here because
151 // only the entropy library depends on it
152 // so if entropy detection is removed so is the dependency
156 JavaScript BigInteger library version 0.9.1
157 http://silentmatt.com/biginteger/
159 Copyright (c) 2009 Matthew Crumley <email@matthewcrumley.com>
160 Copyright (c) 2010,2011 by John Tobey <John.Tobey@gmail.com>
161 Licensed under the MIT license.
163 Support for arbitrary internal representation base was added by
178 An arbitrarily-large integer.
180 <BigInteger> objects should be considered immutable. None of the "built-in"
181 methods modify *this* or their arguments. All properties should be
184 All the methods of <BigInteger> instances can be called "statically". The
185 static versions are convenient if you don't already have a <BigInteger>
188 As an example, these calls are equivalent.
190 > BigInteger(4).multiply(5); // returns BigInteger(20);
191 > BigInteger.multiply(4, 5); // returns BigInteger(20);
194 > var a = BigInteger.toJSValue("0b101010"); // Not completely useless...
197 var CONSTRUCT
= {}; // Unique token to call "private" version of constructor
200 Constructor: BigInteger()
201 Convert a value to a <BigInteger>.
203 Although <BigInteger()> is the constructor for <BigInteger> objects, it is
204 best not to call it as a constructor. If *n* is a <BigInteger> object, it is
205 simply returned as-is. Otherwise, <BigInteger()> is equivalent to <parse>
206 without a radix argument.
208 > var n0 = BigInteger(); // Same as <BigInteger.ZERO>
209 > var n1 = BigInteger("123"); // Create a new <BigInteger> with value 123
210 > var n2 = BigInteger(123); // Create a new <BigInteger> with value 123
211 > var n3 = BigInteger(n2); // Return n2, unchanged
213 The constructor form only takes an array and a sign. *n* must be an
214 array of numbers in little-endian order, where each digit is between 0
215 and BigInteger.base. The second parameter sets the sign: -1 for
216 negative, +1 for positive, or 0 for zero. The array is *not copied and
217 may be modified*. If the array contains only zeros, the sign parameter
218 is ignored and is forced to zero.
220 > new BigInteger([5], -1): create a new BigInteger with value -5
224 n - Value to convert to a <BigInteger>.
228 A <BigInteger> value.
232 <parse>, <BigInteger>
234 function BigInteger(n
, s
, token
) {
235 if (token
!== CONSTRUCT
) {
236 if (n
instanceof BigInteger
) {
239 else if (typeof n
=== "undefined") {
242 return BigInteger
.parse(n
);
245 n
= n
|| []; // Provide the nullary constructor for subclasses.
246 while (n
.length
&& !n
[n
.length
- 1]) {
250 this._s
= n
.length
? (s
|| 1) : 0;
253 BigInteger
._construct = function(n
, s
) {
254 return new BigInteger(n
, s
, CONSTRUCT
);
257 // Base-10 speedup hacks in parse, toString, exp10 and log functions
258 // require base to be a power of 10. 10^7 is the largest such power
259 // that won't cause a precision loss when digits are multiplied.
260 var BigInteger_base
= 10000000;
261 var BigInteger_base_log10
= 7;
263 BigInteger
.base
= BigInteger_base
;
264 BigInteger
.base_log10
= BigInteger_base_log10
;
266 var ZERO
= new BigInteger([], 0, CONSTRUCT
);
269 BigInteger
.ZERO
= ZERO
;
271 var ONE
= new BigInteger([1], 1, CONSTRUCT
);
274 BigInteger
.ONE
= ONE
;
276 var M_ONE
= new BigInteger(ONE
._d
, -1, CONSTRUCT
);
279 BigInteger
.M_ONE
= M_ONE
;
282 // Shortcut for <ZERO>.
283 BigInteger
._0
= ZERO
;
286 // Shortcut for <ONE>.
291 Array of <BigIntegers> from 0 to 36.
293 These are used internally for parsing, but useful when you need a "small"
298 <ZERO>, <ONE>, <_0>, <_1>
303 /* Assuming BigInteger_base > 36 */
304 new BigInteger( [2], 1, CONSTRUCT
),
305 new BigInteger( [3], 1, CONSTRUCT
),
306 new BigInteger( [4], 1, CONSTRUCT
),
307 new BigInteger( [5], 1, CONSTRUCT
),
308 new BigInteger( [6], 1, CONSTRUCT
),
309 new BigInteger( [7], 1, CONSTRUCT
),
310 new BigInteger( [8], 1, CONSTRUCT
),
311 new BigInteger( [9], 1, CONSTRUCT
),
312 new BigInteger([10], 1, CONSTRUCT
),
313 new BigInteger([11], 1, CONSTRUCT
),
314 new BigInteger([12], 1, CONSTRUCT
),
315 new BigInteger([13], 1, CONSTRUCT
),
316 new BigInteger([14], 1, CONSTRUCT
),
317 new BigInteger([15], 1, CONSTRUCT
),
318 new BigInteger([16], 1, CONSTRUCT
),
319 new BigInteger([17], 1, CONSTRUCT
),
320 new BigInteger([18], 1, CONSTRUCT
),
321 new BigInteger([19], 1, CONSTRUCT
),
322 new BigInteger([20], 1, CONSTRUCT
),
323 new BigInteger([21], 1, CONSTRUCT
),
324 new BigInteger([22], 1, CONSTRUCT
),
325 new BigInteger([23], 1, CONSTRUCT
),
326 new BigInteger([24], 1, CONSTRUCT
),
327 new BigInteger([25], 1, CONSTRUCT
),
328 new BigInteger([26], 1, CONSTRUCT
),
329 new BigInteger([27], 1, CONSTRUCT
),
330 new BigInteger([28], 1, CONSTRUCT
),
331 new BigInteger([29], 1, CONSTRUCT
),
332 new BigInteger([30], 1, CONSTRUCT
),
333 new BigInteger([31], 1, CONSTRUCT
),
334 new BigInteger([32], 1, CONSTRUCT
),
335 new BigInteger([33], 1, CONSTRUCT
),
336 new BigInteger([34], 1, CONSTRUCT
),
337 new BigInteger([35], 1, CONSTRUCT
),
338 new BigInteger([36], 1, CONSTRUCT
)
341 // Used for parsing/radix conversion
342 BigInteger
.digits
= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");
346 Convert a <BigInteger> to a string.
348 When *base* is greater than 10, letters are upper case.
352 base - Optional base to represent the number in (default is base 10).
353 Must be between 2 and 36 inclusive, or an Error will be thrown.
357 The string representation of the <BigInteger>.
359 BigInteger
.prototype.toString = function(base
) {
361 if (base
< 2 || base
> 36) {
362 throw new Error("illegal radix " + base
+ ".");
368 var str
= this._s
< 0 ? "-" : "";
369 str
+= this._d
[this._d
.length
- 1].toString();
370 for (var i
= this._d
.length
- 2; i
>= 0; i
--) {
371 var group
= this._d
[i
].toString();
372 while (group
.length
< BigInteger_base_log10
) group
= '0' + group
;
378 var numerals
= BigInteger
.digits
;
379 base
= BigInteger
.small
[base
];
387 var divmod
= n
.divRem(base
);
390 // TODO: This could be changed to unshift instead of reversing at the end.
391 // Benchmark both to compare speeds.
392 digits
.push(numerals
[digit
.valueOf()]);
394 return (sign
< 0 ? "-" : "") + digits
.reverse().join("");
398 // Verify strings for parsing
399 BigInteger
.radixRegex
= [
441 Parse a string into a <BigInteger>.
443 *base* is optional but, if provided, must be from 2 to 36 inclusive. If
444 *base* is not provided, it will be guessed based on the leading characters
447 - "0x" or "0X": *base* = 16
448 - "0c" or "0C": *base* = 8
449 - "0b" or "0B": *base* = 2
452 If no base is provided, or *base* is 10, the number can be in exponential
453 form. For example, these are all valid:
455 > BigInteger.parse("1e9"); // Same as "1000000000"
456 > BigInteger.parse("1.234*10^3"); // Same as 1234
457 > BigInteger.parse("56789 * 10 ** -2"); // Same as 567
459 If any characters fall outside the range defined by the radix, an exception
464 s - The string to parse.
465 base - Optional radix (default is to guess based on *s*).
469 a <BigInteger> instance.
471 BigInteger
.parse = function(s
, base
) {
472 // Expands a number in exponential form to decimal form.
473 // expandExponential("-13.441*10^5") === "1344100";
474 // expandExponential("1.12300e-1") === "0.112300";
475 // expandExponential(1000000000000000000000000000000) === "1000000000000000000000000000000";
476 function expandExponential(str
) {
477 str
= str
.replace(/\s*[*xX]\s*10\s*(\^|\*\*)\s*/, "e");
479 return str
.replace(/^([+\-])?(\d+)\.?(\d*)[eE]([+\-]?\d+)$/, function(x
, s
, n
, f
, c
) {
482 var i
= n
.length
+ c
;
483 x
= (l
? n : f
).length
;
484 c
= ((c
= Math
.abs(c
)) >= x
? c
- x
+ l : 0);
485 var z
= (new Array(c
+ 1)).join("0");
487 return (s
|| "") + (l
? r
= z
+ r : r
+= z
).substr(0, i
+= l
? z
.length : 0) + (i
< r
.length
? "." + r
.substr(i
) : "");
492 if (typeof base
=== "undefined" || +base
=== 10) {
493 s
= expandExponential(s
);
497 if (typeof base
=== "undefined") {
500 else if (base
== 16) {
503 else if (base
== 8) {
506 else if (base
== 2) {
512 var parts
= new RegExp('^([+\\-]?)(' + prefixRE
+ ')?([0-9a-z]*)(?:\\.\\d*)?$', 'i').exec(s
);
514 var sign
= parts
[1] || "+";
515 var baseSection
= parts
[2] || "";
516 var digits
= parts
[3] || "";
518 if (typeof base
=== "undefined") {
520 if (baseSection
=== "0x" || baseSection
=== "0X") { // Hex
523 else if (baseSection
=== "0c" || baseSection
=== "0C") { // Octal
526 else if (baseSection
=== "0b" || baseSection
=== "0B") { // Binary
533 else if (base
< 2 || base
> 36) {
534 throw new Error("Illegal radix " + base
+ ".");
539 // Check for digits outside the range
540 if (!(BigInteger
.radixRegex
[base
].test(digits
))) {
541 throw new Error("Bad digit for radix " + base
);
544 // Strip leading zeros, and convert to array
545 digits
= digits
.replace(/^0+/, "").split("");
546 if (digits
.length
=== 0) {
550 // Get the sign (we know it's not zero)
551 sign
= (sign
=== "-") ? -1 : 1;
556 while (digits
.length
>= BigInteger_base_log10
) {
557 d
.push(parseInt(digits
.splice(digits
.length
-BigInteger
.base_log10
, BigInteger
.base_log10
).join(''), 10));
559 d
.push(parseInt(digits
.join(''), 10));
560 return new BigInteger(d
, sign
, CONSTRUCT
);
565 base
= BigInteger
.small
[base
];
566 var small
= BigInteger
.small
;
567 for (var i
= 0; i
< digits
.length
; i
++) {
568 d
= d
.multiply(base
).add(small
[parseInt(digits
[i
], 36)]);
570 return new BigInteger(d
._d
, sign
, CONSTRUCT
);
573 throw new Error("Invalid BigInteger format: " + s
);
579 Add two <BigIntegers>.
583 n - The number to add to *this*. Will be converted to a <BigInteger>.
587 The numbers added together.
591 <subtract>, <multiply>, <quotient>, <next>
593 BigInteger
.prototype.add = function(n
) {
595 return BigInteger(n
);
602 if (this._s
!== n
._s
) {
604 return this.subtract(n
);
611 var sum
= new Array(Math
.max(al
, bl
) + 1);
612 var size
= Math
.min(al
, bl
);
616 for (var i
= 0; i
< size
; i
++) {
617 digit
= a
[i
] + b
[i
] + carry
;
618 sum
[i
] = digit
% BigInteger_base
;
619 carry
= (digit
/ BigInteger_base
) | 0;
625 for (i
= size
; carry
&& i
< al
; i
++) {
626 digit
= a
[i
] + carry
;
627 sum
[i
] = digit
% BigInteger_base
;
628 carry
= (digit
/ BigInteger_base
) | 0;
634 for ( ; i
< al
; i
++) {
638 return new BigInteger(sum
, this._s
, CONSTRUCT
);
643 Get the additive inverse of a <BigInteger>.
647 A <BigInteger> with the same magnatude, but with the opposite sign.
653 BigInteger
.prototype.negate = function() {
654 return new BigInteger(this._d
, (-this._s
) | 0, CONSTRUCT
);
659 Get the absolute value of a <BigInteger>.
663 A <BigInteger> with the same magnatude, but always positive (or zero).
669 BigInteger
.prototype.abs = function() {
670 return (this._s
< 0) ? this.negate() : this;
675 Subtract two <BigIntegers>.
679 n - The number to subtract from *this*. Will be converted to a <BigInteger>.
683 The *n* subtracted from *this*.
687 <add>, <multiply>, <quotient>, <prev>
689 BigInteger
.prototype.subtract = function(n
) {
691 return BigInteger(n
).negate();
698 if (this._s
!== n
._s
) {
704 // negative - negative => -|a| - -|b| => -|a| + |b| => |b| - |a|
706 m
= new BigInteger(n
._d
, 1, CONSTRUCT
);
707 n
= new BigInteger(this._d
, 1, CONSTRUCT
);
710 // Both are positive => a - b
711 var sign
= m
.compareAbs(n
);
727 var diff
= new Array(al
); // al >= bl since a > b
732 for (i
= 0; i
< bl
; i
++) {
733 digit
= a
[i
] - borrow
- b
[i
];
735 digit
+= BigInteger_base
;
743 for (i
= bl
; i
< al
; i
++) {
744 digit
= a
[i
] - borrow
;
746 digit
+= BigInteger_base
;
754 for ( ; i
< al
; i
++) {
758 return new BigInteger(diff
, sign
, CONSTRUCT
);
762 function addOne(n
, sign
) {
769 var digit
= (a
[i
] || 0) + 1;
770 sum
[i
] = digit
% BigInteger_base
;
771 if (digit
<= BigInteger_base
- 1) {
777 return new BigInteger(sum
, sign
, CONSTRUCT
);
780 function subtractOne(n
, sign
) {
787 var digit
= (a
[i
] || 0) - 1;
789 sum
[i
] = digit
+ BigInteger_base
;
798 return new BigInteger(sum
, sign
, CONSTRUCT
);
803 Get the next <BigInteger> (add one).
813 BigInteger
.prototype.next = function() {
818 return subtractOne(this, -1);
821 return addOne(this, 1);
827 Get the previous <BigInteger> (subtract one).
837 BigInteger
.prototype.prev = function() {
842 return addOne(this, -1);
845 return subtractOne(this, 1);
852 Compare the absolute value of two <BigIntegers>.
854 Calling <compareAbs> is faster than calling <abs> twice, then <compare>.
858 n - The number to compare to *this*. Will be converted to a <BigInteger>.
862 -1, 0, or +1 if *|this|* is less than, equal to, or greater than *|n|*.
868 BigInteger
.prototype.compareAbs = function(n
) {
873 if (!(n
instanceof BigInteger
)) {
875 return(isNaN(n
) ? n : -1);
881 return (n
._s
!== 0) ? -1 : 0;
887 var l
= this._d
.length
;
888 var nl
= n
._d
.length
;
898 for (var i
= l
-1; i
>= 0; i
--) {
900 return a
[i
] < b
[i
] ? -1 : 1;
909 Compare two <BigIntegers>.
913 n - The number to compare to *this*. Will be converted to a <BigInteger>.
917 -1, 0, or +1 if *this* is less than, equal to, or greater than *n*.
921 <compareAbs>, <isPositive>, <isNegative>, <isUnit>
923 BigInteger
.prototype.compare = function(n
) {
934 if (this._s
=== n
._s
) { // both positive or both negative
935 var cmp
= this.compareAbs(n
);
936 return cmp
* this._s
;
945 Return true iff *this* is either 1 or -1.
949 true if *this* compares equal to <BigInteger.ONE> or <BigInteger.M_ONE>.
953 <isZero>, <isNegative>, <isPositive>, <compareAbs>, <compare>,
954 <BigInteger.ONE>, <BigInteger.M_ONE>
956 BigInteger
.prototype.isUnit = function() {
957 return this === ONE
||
959 (this._d
.length
=== 1 && this._d
[0] === 1);
964 Multiply two <BigIntegers>.
968 n - The number to multiply *this* by. Will be converted to a
973 The numbers multiplied together.
977 <add>, <subtract>, <quotient>, <square>
979 BigInteger
.prototype.multiply = function(n
) {
980 // TODO: Consider adding Karatsuba multiplication for large numbers
997 return this.negate();
1002 return this.square();
1005 var r
= (this._d
.length
>= n
._d
.length
);
1006 var a
= (r
? this : n
)._d
; // a will be longer than b
1007 var b
= (r
? n : this)._d
;
1012 var partial
= new Array(pl
);
1014 for (i
= 0; i
< pl
; i
++) {
1018 for (i
= 0; i
< bl
; i
++) {
1021 var jlimit
= al
+ i
;
1023 for (var j
= i
; j
< jlimit
; j
++) {
1024 digit
= partial
[j
] + bi
* a
[j
- i
] + carry
;
1025 carry
= (digit
/ BigInteger_base
) | 0;
1026 partial
[j
] = (digit
% BigInteger_base
) | 0;
1029 digit
= partial
[j
] + carry
;
1030 carry
= (digit
/ BigInteger_base
) | 0;
1031 partial
[j
] = digit
% BigInteger_base
;
1034 return new BigInteger(partial
, this._s
* n
._s
, CONSTRUCT
);
1037 // Multiply a BigInteger by a single-digit native number
1038 // Assumes that this and n are >= 0
1039 // This is not really intended to be used outside the library itself
1040 BigInteger
.prototype.multiplySingleDigit = function(n
) {
1041 if (n
=== 0 || this._s
=== 0) {
1049 if (this._d
.length
=== 1) {
1050 digit
= this._d
[0] * n
;
1051 if (digit
>= BigInteger_base
) {
1052 return new BigInteger([(digit
% BigInteger_base
)|0,
1053 (digit
/ BigInteger_base
)|0], 1, CONSTRUCT
);
1055 return new BigInteger([digit
], 1, CONSTRUCT
);
1059 return this.add(this);
1061 if (this.isUnit()) {
1062 return new BigInteger([n
], 1, CONSTRUCT
);
1069 var partial
= new Array(pl
);
1070 for (var i
= 0; i
< pl
; i
++) {
1075 for (var j
= 0; j
< al
; j
++) {
1076 digit
= n
* a
[j
] + carry
;
1077 carry
= (digit
/ BigInteger_base
) | 0;
1078 partial
[j
] = (digit
% BigInteger_base
) | 0;
1084 return new BigInteger(partial
, 1, CONSTRUCT
);
1089 Multiply a <BigInteger> by itself.
1091 This is slightly faster than regular multiplication, since it removes the
1092 duplicated multiplcations.
1096 > this.multiply(this)
1101 BigInteger
.prototype.square = function() {
1102 // Normally, squaring a 10-digit number would take 100 multiplications.
1103 // Of these 10 are unique diagonals, of the remaining 90 (100-10), 45 are repeated.
1104 // This procedure saves (N*(N-1))/2 multiplications, (e.g., 45 of 100 multiplies).
1105 // Based on code by Gary Darby, Intellitech Systems Inc., www.DelphiForFun.org
1107 if (this._s
=== 0) {
1110 if (this.isUnit()) {
1114 var digits
= this._d
;
1115 var length
= digits
.length
;
1116 var imult1
= new Array(length
+ length
+ 1);
1117 var product
, carry
, k
;
1120 // Calculate diagonal
1121 for (i
= 0; i
< length
; i
++) {
1123 product
= digits
[i
] * digits
[i
];
1124 carry
= (product
/ BigInteger_base
) | 0;
1125 imult1
[k
] = product
% BigInteger_base
;
1126 imult1
[k
+ 1] = carry
;
1129 // Calculate repeating part
1130 for (i
= 0; i
< length
; i
++) {
1133 for (var j
= i
+ 1; j
< length
; j
++, k
++) {
1134 product
= digits
[j
] * digits
[i
] * 2 + imult1
[k
] + carry
;
1135 carry
= (product
/ BigInteger_base
) | 0;
1136 imult1
[k
] = product
% BigInteger_base
;
1139 var digit
= carry
+ imult1
[k
];
1140 carry
= (digit
/ BigInteger_base
) | 0;
1141 imult1
[k
] = digit
% BigInteger_base
;
1142 imult1
[k
+ 1] += carry
;
1145 return new BigInteger(imult1
, 1, CONSTRUCT
);
1150 Divide two <BigIntegers> and truncate towards zero.
1152 <quotient> throws an exception if *n* is zero.
1156 n - The number to divide *this* by. Will be converted to a <BigInteger>.
1160 The *this* / *n*, truncated to an integer.
1164 <add>, <subtract>, <multiply>, <divRem>, <remainder>
1166 BigInteger
.prototype.quotient = function(n
) {
1167 return this.divRem(n
)[0];
1172 Deprecated synonym for <quotient>.
1174 BigInteger
.prototype.divide
= BigInteger
.prototype.quotient
;
1178 Calculate the remainder of two <BigIntegers>.
1180 <remainder> throws an exception if *n* is zero.
1184 n - The remainder after *this* is divided *this* by *n*. Will be
1185 converted to a <BigInteger>.
1193 <divRem>, <quotient>
1195 BigInteger
.prototype.remainder = function(n
) {
1196 return this.divRem(n
)[1];
1201 Calculate the integer quotient and remainder of two <BigIntegers>.
1203 <divRem> throws an exception if *n* is zero.
1207 n - The number to divide *this* by. Will be converted to a <BigInteger>.
1211 A two-element array containing the quotient and the remainder.
1215 is exactly equivalent to
1217 > [a.quotient(b), a.remainder(b)]
1219 except it is faster, because they are calculated at the same time.
1223 <quotient>, <remainder>
1225 BigInteger
.prototype.divRem = function(n
) {
1228 throw new Error("Divide by zero");
1230 if (this._s
=== 0) {
1231 return [ZERO
, ZERO
];
1233 if (n
._d
.length
=== 1) {
1234 return this.divRemSmall(n
._s
* n
._d
[0]);
1237 // Test for easy cases -- |n1| <= |n2|
1238 switch (this.compareAbs(n
)) {
1240 return [this._s
=== n
._s
? ONE : M_ONE
, ZERO
];
1241 case -1: // |n1| < |n2|
1242 return [ZERO
, this];
1245 var sign
= this._s
* n
._s
;
1247 var b_digits
= this._d
;
1248 var b_index
= b_digits
.length
;
1249 var digits
= n
._d
.length
;
1253 var part
= new BigInteger([], 0, CONSTRUCT
);
1256 part
._d
.unshift(b_digits
[--b_index
]);
1257 part
= new BigInteger(part
._d
, 1, CONSTRUCT
);
1259 if (part
.compareAbs(n
) < 0) {
1263 if (part
._s
=== 0) {
1267 var xlen
= part
._d
.length
, ylen
= a
._d
.length
;
1268 var highx
= part
._d
[xlen
-1]*BigInteger_base
+ part
._d
[xlen
-2];
1269 var highy
= a
._d
[ylen
-1]*BigInteger_base
+ a
._d
[ylen
-2];
1270 if (part
._d
.length
> a
._d
.length
) {
1271 // The length of part._d can either match a._d length,
1272 // or exceed it by one.
1273 highx
= (highx
+1)*BigInteger_base
;
1275 guess
= Math
.ceil(highx
/highy
);
1278 var check
= a
.multiplySingleDigit(guess
);
1279 if (check
.compareAbs(part
) <= 0) {
1289 var diff
= part
.subtract(check
);
1290 part
._d
= diff
._d
.slice();
1293 return [new BigInteger(quot
.reverse(), sign
, CONSTRUCT
),
1294 new BigInteger(part
._d
, this._s
, CONSTRUCT
)];
1297 // Throws an exception if n is outside of (-BigInteger.base, -1] or
1298 // [1, BigInteger.base). It's not necessary to call this, since the
1299 // other division functions will call it if they are able to.
1300 BigInteger
.prototype.divRemSmall = function(n
) {
1304 throw new Error("Divide by zero");
1307 var n_s
= n
< 0 ? -1 : 1;
1308 var sign
= this._s
* n_s
;
1311 if (n
< 1 || n
>= BigInteger_base
) {
1312 throw new Error("Argument out of range");
1315 if (this._s
=== 0) {
1316 return [ZERO
, ZERO
];
1319 if (n
=== 1 || n
=== -1) {
1320 return [(sign
=== 1) ? this.abs() : new BigInteger(this._d
, sign
, CONSTRUCT
), ZERO
];
1323 // 2 <= n < BigInteger_base
1325 // divide a single digit by a single digit
1326 if (this._d
.length
=== 1) {
1327 var q
= new BigInteger([(this._d
[0] / n
) | 0], 1, CONSTRUCT
);
1328 r
= new BigInteger([(this._d
[0] % n
) | 0], 1, CONSTRUCT
);
1338 var digits
= this._d
.slice();
1339 var quot
= new Array(digits
.length
);
1345 while (digits
.length
) {
1346 part
= part
* BigInteger_base
+ digits
[digits
.length
- 1];
1350 diff
= BigInteger_base
* diff
+ part
;
1357 guess
= (part
/ n
) | 0;
1360 var check
= n
* guess
;
1361 diff
= part
- check
;
1372 r
= new BigInteger([diff
], 1, CONSTRUCT
);
1376 return [new BigInteger(quot
.reverse(), sign
, CONSTRUCT
), r
];
1381 Return true iff *this* is divisible by two.
1383 Note that <BigInteger.ZERO> is even.
1387 true if *this* is even, false otherwise.
1393 BigInteger
.prototype.isEven = function() {
1394 var digits
= this._d
;
1395 return this._s
=== 0 || digits
.length
=== 0 || (digits
[0] % 2) === 0;
1400 Return true iff *this* is not divisible by two.
1404 true if *this* is odd, false otherwise.
1410 BigInteger
.prototype.isOdd = function() {
1411 return !this.isEven();
1416 Get the sign of a <BigInteger>.
1426 <isZero>, <isPositive>, <isNegative>, <compare>, <BigInteger.ZERO>
1428 BigInteger
.prototype.sign = function() {
1433 Function: isPositive
1434 Return true iff *this* > 0.
1438 true if *this*.compare(<BigInteger.ZERO>) == 1.
1442 <sign>, <isZero>, <isNegative>, <isUnit>, <compare>, <BigInteger.ZERO>
1444 BigInteger
.prototype.isPositive = function() {
1449 Function: isNegative
1450 Return true iff *this* < 0.
1454 true if *this*.compare(<BigInteger.ZERO>) == -1.
1458 <sign>, <isPositive>, <isZero>, <isUnit>, <compare>, <BigInteger.ZERO>
1460 BigInteger
.prototype.isNegative = function() {
1466 Return true iff *this* == 0.
1470 true if *this*.compare(<BigInteger.ZERO>) == 0.
1474 <sign>, <isPositive>, <isNegative>, <isUnit>, <BigInteger.ZERO>
1476 BigInteger
.prototype.isZero = function() {
1477 return this._s
=== 0;
1482 Multiply a <BigInteger> by a power of 10.
1484 This is equivalent to, but faster than
1487 > return this.multiply(BigInteger("1e" + n));
1490 > return this.quotient(BigInteger("1e" + -n));
1495 n - The power of 10 to multiply *this* by. *n* is converted to a
1496 javascipt number and must be no greater than <BigInteger.MAX_EXP>
1497 (0x7FFFFFFF), or an exception will be thrown.
1501 *this* * (10 ** *n*), truncated to an integer if necessary.
1507 BigInteger
.prototype.exp10 = function(n
) {
1512 if (Math
.abs(n
) > Number(MAX_EXP
)) {
1513 throw new Error("exponent too large in BigInteger.exp10");
1515 // Optimization for this == 0. This also keeps us from having to trim zeros in the positive n case
1516 if (this._s
=== 0) {
1520 var k
= new BigInteger(this._d
.slice(), this._s
, CONSTRUCT
);
1522 for (; n
>= BigInteger_base_log10
; n
-= BigInteger_base_log10
) {
1528 k
= k
.multiplySingleDigit(Math
.pow(10, n
));
1529 return (this._s
< 0 ? k
.negate() : k
);
1530 } else if (-n
>= this._d
.length
*BigInteger_base_log10
) {
1533 var k
= new BigInteger(this._d
.slice(), this._s
, CONSTRUCT
);
1535 for (n
= -n
; n
>= BigInteger_base_log10
; n
-= BigInteger_base_log10
) {
1538 return (n
== 0) ? k : k
.divRemSmall(Math
.pow(10, n
))[0];
1544 Raise a <BigInteger> to a power.
1546 In this implementation, 0**0 is 1.
1550 n - The exponent to raise *this* by. *n* must be no greater than
1551 <BigInteger.MAX_EXP> (0x7FFFFFFF), or an exception will be thrown.
1555 *this* raised to the *nth* power.
1561 BigInteger
.prototype.pow = function(n
) {
1562 if (this.isUnit()) {
1567 return BigInteger(n
).isOdd() ? this : this.negate();
1575 else if (n
._s
< 0) {
1576 if (this._s
=== 0) {
1577 throw new Error("Divide by zero");
1583 if (this._s
=== 0) {
1590 if (n
.compareAbs(MAX_EXP
) > 0) {
1591 throw new Error("exponent too large in BigInteger.pow");
1595 var two
= BigInteger
.small
[2];
1597 while (n
.isPositive()) {
1599 aux
= aux
.multiply(x
);
1605 n
= n
.quotient(two
);
1613 Raise a <BigInteger> to a power (mod m).
1615 Because it is reduced by a modulus, <modPow> is not limited by
1616 <BigInteger.MAX_EXP> like <pow>.
1620 exponent - The exponent to raise *this* by. Must be positive.
1621 modulus - The modulus.
1625 *this* ^ *exponent* (mod *modulus*).
1631 BigInteger
.prototype.modPow = function(exponent
, modulus
) {
1635 while (exponent
.isPositive()) {
1636 if (exponent
.isOdd()) {
1637 result
= result
.multiply(base
).remainder(modulus
);
1640 exponent
= exponent
.quotient(BigInteger
.small
[2]);
1641 if (exponent
.isPositive()) {
1642 base
= base
.square().remainder(modulus
);
1651 Get the natural logarithm of a <BigInteger> as a native JavaScript number.
1653 This is equivalent to
1655 > Math.log(this.toJSValue())
1657 but handles values outside of the native number range.
1667 BigInteger
.prototype.log = function() {
1669 case 0: return -Infinity
;
1670 case -1: return NaN
;
1671 default: // Fall through.
1674 var l
= this._d
.length
;
1676 if (l
*BigInteger_base_log10
< 30) {
1677 return Math
.log(this.valueOf());
1680 var N
= Math
.ceil(30/BigInteger_base_log10
);
1681 var firstNdigits
= this._d
.slice(l
- N
);
1682 return Math
.log((new BigInteger(firstNdigits
, 1, CONSTRUCT
)).valueOf()) + (l
- N
) * Math
.log(BigInteger_base
);
1687 Convert a <BigInteger> to a native JavaScript integer.
1689 This is called automatically by JavaScipt to convert a <BigInteger> to a
1694 > parseInt(this.toString(), 10)
1698 <toString>, <toJSValue>
1700 BigInteger
.prototype.valueOf = function() {
1701 return parseInt(this.toString(), 10);
1706 Convert a <BigInteger> to a native JavaScript integer.
1708 This is the same as valueOf, but more explicitly named.
1712 > parseInt(this.toString(), 10)
1716 <toString>, <valueOf>
1718 BigInteger
.prototype.toJSValue = function() {
1719 return parseInt(this.toString(), 10);
1722 var MAX_EXP
= BigInteger(0x7FFFFFFF);
1723 // Constant: MAX_EXP
1724 // The largest exponent allowed in <pow> and <exp10> (0x7FFFFFFF or 2147483647).
1725 BigInteger
.MAX_EXP
= MAX_EXP
;
1728 function makeUnary(fn
) {
1729 return function(a
) {
1730 return fn
.call(BigInteger(a
));
1734 function makeBinary(fn
) {
1735 return function(a
, b
) {
1736 return fn
.call(BigInteger(a
), BigInteger(b
));
1740 function makeTrinary(fn
) {
1741 return function(a
, b
, c
) {
1742 return fn
.call(BigInteger(a
), BigInteger(b
), BigInteger(c
));
1748 var unary
= "toJSValue,isEven,isOdd,sign,isZero,isNegative,abs,isUnit,square,negate,isPositive,toString,next,prev,log".split(",");
1749 var binary
= "compare,remainder,divRem,subtract,add,quotient,divide,multiply,pow,compareAbs".split(",");
1750 var trinary
= ["modPow"];
1752 for (i
= 0; i
< unary
.length
; i
++) {
1754 BigInteger
[fn
] = makeUnary(BigInteger
.prototype[fn
]);
1757 for (i
= 0; i
< binary
.length
; i
++) {
1759 BigInteger
[fn
] = makeBinary(BigInteger
.prototype[fn
]);
1762 for (i
= 0; i
< trinary
.length
; i
++) {
1764 BigInteger
[fn
] = makeTrinary(BigInteger
.prototype[fn
]);
1767 BigInteger
.exp10 = function(x
, n
) {
1768 return BigInteger(x
).exp10(n
);
1773 exports
.BigInteger
= BigInteger
;
1774 })(typeof exports
!== 'undefined' ? exports : this);