]>
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) || [];
41 this.fromString = function(rawEntropyStr
) {
42 // Find type of entropy being used (binary, hex, dice etc)
43 var base
= getBase(rawEntropyStr
);
44 // Convert dice to base6 entropy (ie 1-6 to 0-5)
45 if (base
.str
== "dice") {
46 var newRawEntropyStr
= "";
47 for (var i
=0; i
<rawEntropyStr
.length
; i
++) {
48 var c
= rawEntropyStr
[i
];
49 if ("123456".indexOf(c
) > -1) {
50 newRawEntropyStr
+= (parseInt(c
) - 1).toString();
56 rawEntropyStr
= newRawEntropyStr
;
57 base
.str
= "base 6 (dice)";
58 base
.parts
= matchers
.base6(rawEntropyStr
);
59 base
.matcher
= matchers
.base6
;
61 // Detect empty entropy
62 if (base
.parts
.length
== 0) {
70 // Pull leading zeros off
71 var leadingZeros
= [];
72 while (base
.parts
[0] == "0") {
73 leadingZeros
.push("0");
76 // Convert leading zeros to binary equivalent
77 var numBinLeadingZeros
= Math
.ceil(Math
.log2(base
.asInt
) * leadingZeros
.length
);
78 var binLeadingZeros
= "";
79 for (var i
=0; i
<numBinLeadingZeros
; i
++) {
80 binLeadingZeros
+= "0";
82 // Convert leading zeros to hex equivalent
83 var numHexLeadingZeros
= Math
.floor(numBinLeadingZeros
/ 4);
84 var hexLeadingZeros
= "";
85 for (var i
=0; i
<numHexLeadingZeros
; i
++) {
86 hexLeadingZeros
+= "0";
88 // Handle entropy of zero
89 if (base
.parts
.length
== 0) {
91 binaryStr: binLeadingZeros
,
92 hexStr: hexLeadingZeros
|| "0",
93 cleanStr: leadingZeros
,
97 // If using hex, should always be multiples of 4 bits, which can get
98 // out of sync if first number has leading 0 bits, eg 2 in hex is 0010
99 // which would show up as 10, thus missing 2 bits it should have.
100 if (base
.asInt
== 16) {
101 var firstDigit
= parseInt(base
.parts
[0], 16);
102 if (firstDigit
>= 4 && firstDigit
< 8) {
103 binLeadingZeros
+= "0";
105 else if (firstDigit
>= 2 && firstDigit
< 4) {
106 binLeadingZeros
+= "00";
108 else if (firstDigit
>= 1 && firstDigit
< 2) {
109 binLeadingZeros
+= "000";
112 // Convert entropy to different foramts
113 var entropyInt
= BigInteger
.parse(base
.parts
.join(""), base
.asInt
);
114 var entropyBin
= binLeadingZeros
+ entropyInt
.toString(2);
115 var entropyHex
= hexLeadingZeros
+ entropyInt
.toString(16);
116 var entropyClean
= leadingZeros
.join("") + base
.parts
.join("");
118 binaryStr: entropyBin
,
120 cleanStr: entropyClean
,
126 function getBase(str
) {
127 // Need to get the lowest base for the supplied entropy.
128 // This prevents interpreting, say, dice rolls as hexadecimal.
129 var binaryMatches
= matchers
.binary(str
);
130 var hexMatches
= matchers
.hex(str
);
131 // Find the lowest base that can be used, whilst ignoring any irrelevant chars
132 if (binaryMatches
.length
== hexMatches
.length
) {
134 parts: binaryMatches
,
135 matcher: matchers
.binary
,
140 var diceMatches
= matchers
.dice(str
);
141 if (diceMatches
.length
== hexMatches
.length
) {
144 matcher: matchers
.dice
,
149 var base6Matches
= matchers
.base6(str
);
150 if (base6Matches
.length
== hexMatches
.length
) {
153 matcher: matchers
.base6
,
158 var base10Matches
= matchers
.base10(str
);
159 if (base10Matches
.length
== hexMatches
.length
) {
161 parts: base10Matches
,
162 matcher: matchers
.base10
,
169 matcher: matchers
.hex
,
175 // Polyfill for Math.log2
176 // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/log2#Polyfill
177 Math
.log2
= Math
.log2
|| function(x
) {
178 return Math
.log(x
) * Math
.LOG2E
;
184 // BigInteger library included here because
185 // only the entropy library depends on it
186 // so if entropy detection is removed so is the dependency
190 JavaScript BigInteger library version 0.9.1
191 http://silentmatt.com/biginteger/
193 Copyright (c) 2009 Matthew Crumley <email@matthewcrumley.com>
194 Copyright (c) 2010,2011 by John Tobey <John.Tobey@gmail.com>
195 Licensed under the MIT license.
197 Support for arbitrary internal representation base was added by
212 An arbitrarily-large integer.
214 <BigInteger> objects should be considered immutable. None of the "built-in"
215 methods modify *this* or their arguments. All properties should be
218 All the methods of <BigInteger> instances can be called "statically". The
219 static versions are convenient if you don't already have a <BigInteger>
222 As an example, these calls are equivalent.
224 > BigInteger(4).multiply(5); // returns BigInteger(20);
225 > BigInteger.multiply(4, 5); // returns BigInteger(20);
228 > var a = BigInteger.toJSValue("0b101010"); // Not completely useless...
231 var CONSTRUCT
= {}; // Unique token to call "private" version of constructor
234 Constructor: BigInteger()
235 Convert a value to a <BigInteger>.
237 Although <BigInteger()> is the constructor for <BigInteger> objects, it is
238 best not to call it as a constructor. If *n* is a <BigInteger> object, it is
239 simply returned as-is. Otherwise, <BigInteger()> is equivalent to <parse>
240 without a radix argument.
242 > var n0 = BigInteger(); // Same as <BigInteger.ZERO>
243 > var n1 = BigInteger("123"); // Create a new <BigInteger> with value 123
244 > var n2 = BigInteger(123); // Create a new <BigInteger> with value 123
245 > var n3 = BigInteger(n2); // Return n2, unchanged
247 The constructor form only takes an array and a sign. *n* must be an
248 array of numbers in little-endian order, where each digit is between 0
249 and BigInteger.base. The second parameter sets the sign: -1 for
250 negative, +1 for positive, or 0 for zero. The array is *not copied and
251 may be modified*. If the array contains only zeros, the sign parameter
252 is ignored and is forced to zero.
254 > new BigInteger([5], -1): create a new BigInteger with value -5
258 n - Value to convert to a <BigInteger>.
262 A <BigInteger> value.
266 <parse>, <BigInteger>
268 function BigInteger(n
, s
, token
) {
269 if (token
!== CONSTRUCT
) {
270 if (n
instanceof BigInteger
) {
273 else if (typeof n
=== "undefined") {
276 return BigInteger
.parse(n
);
279 n
= n
|| []; // Provide the nullary constructor for subclasses.
280 while (n
.length
&& !n
[n
.length
- 1]) {
284 this._s
= n
.length
? (s
|| 1) : 0;
287 BigInteger
._construct = function(n
, s
) {
288 return new BigInteger(n
, s
, CONSTRUCT
);
291 // Base-10 speedup hacks in parse, toString, exp10 and log functions
292 // require base to be a power of 10. 10^7 is the largest such power
293 // that won't cause a precision loss when digits are multiplied.
294 var BigInteger_base
= 10000000;
295 var BigInteger_base_log10
= 7;
297 BigInteger
.base
= BigInteger_base
;
298 BigInteger
.base_log10
= BigInteger_base_log10
;
300 var ZERO
= new BigInteger([], 0, CONSTRUCT
);
303 BigInteger
.ZERO
= ZERO
;
305 var ONE
= new BigInteger([1], 1, CONSTRUCT
);
308 BigInteger
.ONE
= ONE
;
310 var M_ONE
= new BigInteger(ONE
._d
, -1, CONSTRUCT
);
313 BigInteger
.M_ONE
= M_ONE
;
316 // Shortcut for <ZERO>.
317 BigInteger
._0
= ZERO
;
320 // Shortcut for <ONE>.
325 Array of <BigIntegers> from 0 to 36.
327 These are used internally for parsing, but useful when you need a "small"
332 <ZERO>, <ONE>, <_0>, <_1>
337 /* Assuming BigInteger_base > 36 */
338 new BigInteger( [2], 1, CONSTRUCT
),
339 new BigInteger( [3], 1, CONSTRUCT
),
340 new BigInteger( [4], 1, CONSTRUCT
),
341 new BigInteger( [5], 1, CONSTRUCT
),
342 new BigInteger( [6], 1, CONSTRUCT
),
343 new BigInteger( [7], 1, CONSTRUCT
),
344 new BigInteger( [8], 1, CONSTRUCT
),
345 new BigInteger( [9], 1, CONSTRUCT
),
346 new BigInteger([10], 1, CONSTRUCT
),
347 new BigInteger([11], 1, CONSTRUCT
),
348 new BigInteger([12], 1, CONSTRUCT
),
349 new BigInteger([13], 1, CONSTRUCT
),
350 new BigInteger([14], 1, CONSTRUCT
),
351 new BigInteger([15], 1, CONSTRUCT
),
352 new BigInteger([16], 1, CONSTRUCT
),
353 new BigInteger([17], 1, CONSTRUCT
),
354 new BigInteger([18], 1, CONSTRUCT
),
355 new BigInteger([19], 1, CONSTRUCT
),
356 new BigInteger([20], 1, CONSTRUCT
),
357 new BigInteger([21], 1, CONSTRUCT
),
358 new BigInteger([22], 1, CONSTRUCT
),
359 new BigInteger([23], 1, CONSTRUCT
),
360 new BigInteger([24], 1, CONSTRUCT
),
361 new BigInteger([25], 1, CONSTRUCT
),
362 new BigInteger([26], 1, CONSTRUCT
),
363 new BigInteger([27], 1, CONSTRUCT
),
364 new BigInteger([28], 1, CONSTRUCT
),
365 new BigInteger([29], 1, CONSTRUCT
),
366 new BigInteger([30], 1, CONSTRUCT
),
367 new BigInteger([31], 1, CONSTRUCT
),
368 new BigInteger([32], 1, CONSTRUCT
),
369 new BigInteger([33], 1, CONSTRUCT
),
370 new BigInteger([34], 1, CONSTRUCT
),
371 new BigInteger([35], 1, CONSTRUCT
),
372 new BigInteger([36], 1, CONSTRUCT
)
375 // Used for parsing/radix conversion
376 BigInteger
.digits
= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");
380 Convert a <BigInteger> to a string.
382 When *base* is greater than 10, letters are upper case.
386 base - Optional base to represent the number in (default is base 10).
387 Must be between 2 and 36 inclusive, or an Error will be thrown.
391 The string representation of the <BigInteger>.
393 BigInteger
.prototype.toString = function(base
) {
395 if (base
< 2 || base
> 36) {
396 throw new Error("illegal radix " + base
+ ".");
402 var str
= this._s
< 0 ? "-" : "";
403 str
+= this._d
[this._d
.length
- 1].toString();
404 for (var i
= this._d
.length
- 2; i
>= 0; i
--) {
405 var group
= this._d
[i
].toString();
406 while (group
.length
< BigInteger_base_log10
) group
= '0' + group
;
412 var numerals
= BigInteger
.digits
;
413 base
= BigInteger
.small
[base
];
421 var divmod
= n
.divRem(base
);
424 // TODO: This could be changed to unshift instead of reversing at the end.
425 // Benchmark both to compare speeds.
426 digits
.push(numerals
[digit
.valueOf()]);
428 return (sign
< 0 ? "-" : "") + digits
.reverse().join("");
432 // Verify strings for parsing
433 BigInteger
.radixRegex
= [
475 Parse a string into a <BigInteger>.
477 *base* is optional but, if provided, must be from 2 to 36 inclusive. If
478 *base* is not provided, it will be guessed based on the leading characters
481 - "0x" or "0X": *base* = 16
482 - "0c" or "0C": *base* = 8
483 - "0b" or "0B": *base* = 2
486 If no base is provided, or *base* is 10, the number can be in exponential
487 form. For example, these are all valid:
489 > BigInteger.parse("1e9"); // Same as "1000000000"
490 > BigInteger.parse("1.234*10^3"); // Same as 1234
491 > BigInteger.parse("56789 * 10 ** -2"); // Same as 567
493 If any characters fall outside the range defined by the radix, an exception
498 s - The string to parse.
499 base - Optional radix (default is to guess based on *s*).
503 a <BigInteger> instance.
505 BigInteger
.parse = function(s
, base
) {
506 // Expands a number in exponential form to decimal form.
507 // expandExponential("-13.441*10^5") === "1344100";
508 // expandExponential("1.12300e-1") === "0.112300";
509 // expandExponential(1000000000000000000000000000000) === "1000000000000000000000000000000";
510 function expandExponential(str
) {
511 str
= str
.replace(/\s*[*xX]\s*10\s*(\^|\*\*)\s*/, "e");
513 return str
.replace(/^([+\-])?(\d+)\.?(\d*)[eE]([+\-]?\d+)$/, function(x
, s
, n
, f
, c
) {
516 var i
= n
.length
+ c
;
517 x
= (l
? n : f
).length
;
518 c
= ((c
= Math
.abs(c
)) >= x
? c
- x
+ l : 0);
519 var z
= (new Array(c
+ 1)).join("0");
521 return (s
|| "") + (l
? r
= z
+ r : r
+= z
).substr(0, i
+= l
? z
.length : 0) + (i
< r
.length
? "." + r
.substr(i
) : "");
526 if (typeof base
=== "undefined" || +base
=== 10) {
527 s
= expandExponential(s
);
531 if (typeof base
=== "undefined") {
534 else if (base
== 16) {
537 else if (base
== 8) {
540 else if (base
== 2) {
546 var parts
= new RegExp('^([+\\-]?)(' + prefixRE
+ ')?([0-9a-z]*)(?:\\.\\d*)?$', 'i').exec(s
);
548 var sign
= parts
[1] || "+";
549 var baseSection
= parts
[2] || "";
550 var digits
= parts
[3] || "";
552 if (typeof base
=== "undefined") {
554 if (baseSection
=== "0x" || baseSection
=== "0X") { // Hex
557 else if (baseSection
=== "0c" || baseSection
=== "0C") { // Octal
560 else if (baseSection
=== "0b" || baseSection
=== "0B") { // Binary
567 else if (base
< 2 || base
> 36) {
568 throw new Error("Illegal radix " + base
+ ".");
573 // Check for digits outside the range
574 if (!(BigInteger
.radixRegex
[base
].test(digits
))) {
575 throw new Error("Bad digit for radix " + base
);
578 // Strip leading zeros, and convert to array
579 digits
= digits
.replace(/^0+/, "").split("");
580 if (digits
.length
=== 0) {
584 // Get the sign (we know it's not zero)
585 sign
= (sign
=== "-") ? -1 : 1;
590 while (digits
.length
>= BigInteger_base_log10
) {
591 d
.push(parseInt(digits
.splice(digits
.length
-BigInteger
.base_log10
, BigInteger
.base_log10
).join(''), 10));
593 d
.push(parseInt(digits
.join(''), 10));
594 return new BigInteger(d
, sign
, CONSTRUCT
);
599 base
= BigInteger
.small
[base
];
600 var small
= BigInteger
.small
;
601 for (var i
= 0; i
< digits
.length
; i
++) {
602 d
= d
.multiply(base
).add(small
[parseInt(digits
[i
], 36)]);
604 return new BigInteger(d
._d
, sign
, CONSTRUCT
);
607 throw new Error("Invalid BigInteger format: " + s
);
613 Add two <BigIntegers>.
617 n - The number to add to *this*. Will be converted to a <BigInteger>.
621 The numbers added together.
625 <subtract>, <multiply>, <quotient>, <next>
627 BigInteger
.prototype.add = function(n
) {
629 return BigInteger(n
);
636 if (this._s
!== n
._s
) {
638 return this.subtract(n
);
645 var sum
= new Array(Math
.max(al
, bl
) + 1);
646 var size
= Math
.min(al
, bl
);
650 for (var i
= 0; i
< size
; i
++) {
651 digit
= a
[i
] + b
[i
] + carry
;
652 sum
[i
] = digit
% BigInteger_base
;
653 carry
= (digit
/ BigInteger_base
) | 0;
659 for (i
= size
; carry
&& i
< al
; i
++) {
660 digit
= a
[i
] + carry
;
661 sum
[i
] = digit
% BigInteger_base
;
662 carry
= (digit
/ BigInteger_base
) | 0;
668 for ( ; i
< al
; i
++) {
672 return new BigInteger(sum
, this._s
, CONSTRUCT
);
677 Get the additive inverse of a <BigInteger>.
681 A <BigInteger> with the same magnatude, but with the opposite sign.
687 BigInteger
.prototype.negate = function() {
688 return new BigInteger(this._d
, (-this._s
) | 0, CONSTRUCT
);
693 Get the absolute value of a <BigInteger>.
697 A <BigInteger> with the same magnatude, but always positive (or zero).
703 BigInteger
.prototype.abs = function() {
704 return (this._s
< 0) ? this.negate() : this;
709 Subtract two <BigIntegers>.
713 n - The number to subtract from *this*. Will be converted to a <BigInteger>.
717 The *n* subtracted from *this*.
721 <add>, <multiply>, <quotient>, <prev>
723 BigInteger
.prototype.subtract = function(n
) {
725 return BigInteger(n
).negate();
732 if (this._s
!== n
._s
) {
738 // negative - negative => -|a| - -|b| => -|a| + |b| => |b| - |a|
740 m
= new BigInteger(n
._d
, 1, CONSTRUCT
);
741 n
= new BigInteger(this._d
, 1, CONSTRUCT
);
744 // Both are positive => a - b
745 var sign
= m
.compareAbs(n
);
761 var diff
= new Array(al
); // al >= bl since a > b
766 for (i
= 0; i
< bl
; i
++) {
767 digit
= a
[i
] - borrow
- b
[i
];
769 digit
+= BigInteger_base
;
777 for (i
= bl
; i
< al
; i
++) {
778 digit
= a
[i
] - borrow
;
780 digit
+= BigInteger_base
;
788 for ( ; i
< al
; i
++) {
792 return new BigInteger(diff
, sign
, CONSTRUCT
);
796 function addOne(n
, sign
) {
803 var digit
= (a
[i
] || 0) + 1;
804 sum
[i
] = digit
% BigInteger_base
;
805 if (digit
<= BigInteger_base
- 1) {
811 return new BigInteger(sum
, sign
, CONSTRUCT
);
814 function subtractOne(n
, sign
) {
821 var digit
= (a
[i
] || 0) - 1;
823 sum
[i
] = digit
+ BigInteger_base
;
832 return new BigInteger(sum
, sign
, CONSTRUCT
);
837 Get the next <BigInteger> (add one).
847 BigInteger
.prototype.next = function() {
852 return subtractOne(this, -1);
855 return addOne(this, 1);
861 Get the previous <BigInteger> (subtract one).
871 BigInteger
.prototype.prev = function() {
876 return addOne(this, -1);
879 return subtractOne(this, 1);
886 Compare the absolute value of two <BigIntegers>.
888 Calling <compareAbs> is faster than calling <abs> twice, then <compare>.
892 n - The number to compare to *this*. Will be converted to a <BigInteger>.
896 -1, 0, or +1 if *|this|* is less than, equal to, or greater than *|n|*.
902 BigInteger
.prototype.compareAbs = function(n
) {
907 if (!(n
instanceof BigInteger
)) {
909 return(isNaN(n
) ? n : -1);
915 return (n
._s
!== 0) ? -1 : 0;
921 var l
= this._d
.length
;
922 var nl
= n
._d
.length
;
932 for (var i
= l
-1; i
>= 0; i
--) {
934 return a
[i
] < b
[i
] ? -1 : 1;
943 Compare two <BigIntegers>.
947 n - The number to compare to *this*. Will be converted to a <BigInteger>.
951 -1, 0, or +1 if *this* is less than, equal to, or greater than *n*.
955 <compareAbs>, <isPositive>, <isNegative>, <isUnit>
957 BigInteger
.prototype.compare = function(n
) {
968 if (this._s
=== n
._s
) { // both positive or both negative
969 var cmp
= this.compareAbs(n
);
970 return cmp
* this._s
;
979 Return true iff *this* is either 1 or -1.
983 true if *this* compares equal to <BigInteger.ONE> or <BigInteger.M_ONE>.
987 <isZero>, <isNegative>, <isPositive>, <compareAbs>, <compare>,
988 <BigInteger.ONE>, <BigInteger.M_ONE>
990 BigInteger
.prototype.isUnit = function() {
991 return this === ONE
||
993 (this._d
.length
=== 1 && this._d
[0] === 1);
998 Multiply two <BigIntegers>.
1002 n - The number to multiply *this* by. Will be converted to a
1007 The numbers multiplied together.
1011 <add>, <subtract>, <quotient>, <square>
1013 BigInteger
.prototype.multiply = function(n
) {
1014 // TODO: Consider adding Karatsuba multiplication for large numbers
1015 if (this._s
=== 0) {
1023 if (this.isUnit()) {
1031 return this.negate();
1036 return this.square();
1039 var r
= (this._d
.length
>= n
._d
.length
);
1040 var a
= (r
? this : n
)._d
; // a will be longer than b
1041 var b
= (r
? n : this)._d
;
1046 var partial
= new Array(pl
);
1048 for (i
= 0; i
< pl
; i
++) {
1052 for (i
= 0; i
< bl
; i
++) {
1055 var jlimit
= al
+ i
;
1057 for (var j
= i
; j
< jlimit
; j
++) {
1058 digit
= partial
[j
] + bi
* a
[j
- i
] + carry
;
1059 carry
= (digit
/ BigInteger_base
) | 0;
1060 partial
[j
] = (digit
% BigInteger_base
) | 0;
1063 digit
= partial
[j
] + carry
;
1064 carry
= (digit
/ BigInteger_base
) | 0;
1065 partial
[j
] = digit
% BigInteger_base
;
1068 return new BigInteger(partial
, this._s
* n
._s
, CONSTRUCT
);
1071 // Multiply a BigInteger by a single-digit native number
1072 // Assumes that this and n are >= 0
1073 // This is not really intended to be used outside the library itself
1074 BigInteger
.prototype.multiplySingleDigit = function(n
) {
1075 if (n
=== 0 || this._s
=== 0) {
1083 if (this._d
.length
=== 1) {
1084 digit
= this._d
[0] * n
;
1085 if (digit
>= BigInteger_base
) {
1086 return new BigInteger([(digit
% BigInteger_base
)|0,
1087 (digit
/ BigInteger_base
)|0], 1, CONSTRUCT
);
1089 return new BigInteger([digit
], 1, CONSTRUCT
);
1093 return this.add(this);
1095 if (this.isUnit()) {
1096 return new BigInteger([n
], 1, CONSTRUCT
);
1103 var partial
= new Array(pl
);
1104 for (var i
= 0; i
< pl
; i
++) {
1109 for (var j
= 0; j
< al
; j
++) {
1110 digit
= n
* a
[j
] + carry
;
1111 carry
= (digit
/ BigInteger_base
) | 0;
1112 partial
[j
] = (digit
% BigInteger_base
) | 0;
1118 return new BigInteger(partial
, 1, CONSTRUCT
);
1123 Multiply a <BigInteger> by itself.
1125 This is slightly faster than regular multiplication, since it removes the
1126 duplicated multiplcations.
1130 > this.multiply(this)
1135 BigInteger
.prototype.square = function() {
1136 // Normally, squaring a 10-digit number would take 100 multiplications.
1137 // Of these 10 are unique diagonals, of the remaining 90 (100-10), 45 are repeated.
1138 // This procedure saves (N*(N-1))/2 multiplications, (e.g., 45 of 100 multiplies).
1139 // Based on code by Gary Darby, Intellitech Systems Inc., www.DelphiForFun.org
1141 if (this._s
=== 0) {
1144 if (this.isUnit()) {
1148 var digits
= this._d
;
1149 var length
= digits
.length
;
1150 var imult1
= new Array(length
+ length
+ 1);
1151 var product
, carry
, k
;
1154 // Calculate diagonal
1155 for (i
= 0; i
< length
; i
++) {
1157 product
= digits
[i
] * digits
[i
];
1158 carry
= (product
/ BigInteger_base
) | 0;
1159 imult1
[k
] = product
% BigInteger_base
;
1160 imult1
[k
+ 1] = carry
;
1163 // Calculate repeating part
1164 for (i
= 0; i
< length
; i
++) {
1167 for (var j
= i
+ 1; j
< length
; j
++, k
++) {
1168 product
= digits
[j
] * digits
[i
] * 2 + imult1
[k
] + carry
;
1169 carry
= (product
/ BigInteger_base
) | 0;
1170 imult1
[k
] = product
% BigInteger_base
;
1173 var digit
= carry
+ imult1
[k
];
1174 carry
= (digit
/ BigInteger_base
) | 0;
1175 imult1
[k
] = digit
% BigInteger_base
;
1176 imult1
[k
+ 1] += carry
;
1179 return new BigInteger(imult1
, 1, CONSTRUCT
);
1184 Divide two <BigIntegers> and truncate towards zero.
1186 <quotient> throws an exception if *n* is zero.
1190 n - The number to divide *this* by. Will be converted to a <BigInteger>.
1194 The *this* / *n*, truncated to an integer.
1198 <add>, <subtract>, <multiply>, <divRem>, <remainder>
1200 BigInteger
.prototype.quotient = function(n
) {
1201 return this.divRem(n
)[0];
1206 Deprecated synonym for <quotient>.
1208 BigInteger
.prototype.divide
= BigInteger
.prototype.quotient
;
1212 Calculate the remainder of two <BigIntegers>.
1214 <remainder> throws an exception if *n* is zero.
1218 n - The remainder after *this* is divided *this* by *n*. Will be
1219 converted to a <BigInteger>.
1227 <divRem>, <quotient>
1229 BigInteger
.prototype.remainder = function(n
) {
1230 return this.divRem(n
)[1];
1235 Calculate the integer quotient and remainder of two <BigIntegers>.
1237 <divRem> throws an exception if *n* is zero.
1241 n - The number to divide *this* by. Will be converted to a <BigInteger>.
1245 A two-element array containing the quotient and the remainder.
1249 is exactly equivalent to
1251 > [a.quotient(b), a.remainder(b)]
1253 except it is faster, because they are calculated at the same time.
1257 <quotient>, <remainder>
1259 BigInteger
.prototype.divRem = function(n
) {
1262 throw new Error("Divide by zero");
1264 if (this._s
=== 0) {
1265 return [ZERO
, ZERO
];
1267 if (n
._d
.length
=== 1) {
1268 return this.divRemSmall(n
._s
* n
._d
[0]);
1271 // Test for easy cases -- |n1| <= |n2|
1272 switch (this.compareAbs(n
)) {
1274 return [this._s
=== n
._s
? ONE : M_ONE
, ZERO
];
1275 case -1: // |n1| < |n2|
1276 return [ZERO
, this];
1279 var sign
= this._s
* n
._s
;
1281 var b_digits
= this._d
;
1282 var b_index
= b_digits
.length
;
1283 var digits
= n
._d
.length
;
1287 var part
= new BigInteger([], 0, CONSTRUCT
);
1290 part
._d
.unshift(b_digits
[--b_index
]);
1291 part
= new BigInteger(part
._d
, 1, CONSTRUCT
);
1293 if (part
.compareAbs(n
) < 0) {
1297 if (part
._s
=== 0) {
1301 var xlen
= part
._d
.length
, ylen
= a
._d
.length
;
1302 var highx
= part
._d
[xlen
-1]*BigInteger_base
+ part
._d
[xlen
-2];
1303 var highy
= a
._d
[ylen
-1]*BigInteger_base
+ a
._d
[ylen
-2];
1304 if (part
._d
.length
> a
._d
.length
) {
1305 // The length of part._d can either match a._d length,
1306 // or exceed it by one.
1307 highx
= (highx
+1)*BigInteger_base
;
1309 guess
= Math
.ceil(highx
/highy
);
1312 var check
= a
.multiplySingleDigit(guess
);
1313 if (check
.compareAbs(part
) <= 0) {
1323 var diff
= part
.subtract(check
);
1324 part
._d
= diff
._d
.slice();
1327 return [new BigInteger(quot
.reverse(), sign
, CONSTRUCT
),
1328 new BigInteger(part
._d
, this._s
, CONSTRUCT
)];
1331 // Throws an exception if n is outside of (-BigInteger.base, -1] or
1332 // [1, BigInteger.base). It's not necessary to call this, since the
1333 // other division functions will call it if they are able to.
1334 BigInteger
.prototype.divRemSmall = function(n
) {
1338 throw new Error("Divide by zero");
1341 var n_s
= n
< 0 ? -1 : 1;
1342 var sign
= this._s
* n_s
;
1345 if (n
< 1 || n
>= BigInteger_base
) {
1346 throw new Error("Argument out of range");
1349 if (this._s
=== 0) {
1350 return [ZERO
, ZERO
];
1353 if (n
=== 1 || n
=== -1) {
1354 return [(sign
=== 1) ? this.abs() : new BigInteger(this._d
, sign
, CONSTRUCT
), ZERO
];
1357 // 2 <= n < BigInteger_base
1359 // divide a single digit by a single digit
1360 if (this._d
.length
=== 1) {
1361 var q
= new BigInteger([(this._d
[0] / n
) | 0], 1, CONSTRUCT
);
1362 r
= new BigInteger([(this._d
[0] % n
) | 0], 1, CONSTRUCT
);
1372 var digits
= this._d
.slice();
1373 var quot
= new Array(digits
.length
);
1379 while (digits
.length
) {
1380 part
= part
* BigInteger_base
+ digits
[digits
.length
- 1];
1384 diff
= BigInteger_base
* diff
+ part
;
1391 guess
= (part
/ n
) | 0;
1394 var check
= n
* guess
;
1395 diff
= part
- check
;
1406 r
= new BigInteger([diff
], 1, CONSTRUCT
);
1410 return [new BigInteger(quot
.reverse(), sign
, CONSTRUCT
), r
];
1415 Return true iff *this* is divisible by two.
1417 Note that <BigInteger.ZERO> is even.
1421 true if *this* is even, false otherwise.
1427 BigInteger
.prototype.isEven = function() {
1428 var digits
= this._d
;
1429 return this._s
=== 0 || digits
.length
=== 0 || (digits
[0] % 2) === 0;
1434 Return true iff *this* is not divisible by two.
1438 true if *this* is odd, false otherwise.
1444 BigInteger
.prototype.isOdd = function() {
1445 return !this.isEven();
1450 Get the sign of a <BigInteger>.
1460 <isZero>, <isPositive>, <isNegative>, <compare>, <BigInteger.ZERO>
1462 BigInteger
.prototype.sign = function() {
1467 Function: isPositive
1468 Return true iff *this* > 0.
1472 true if *this*.compare(<BigInteger.ZERO>) == 1.
1476 <sign>, <isZero>, <isNegative>, <isUnit>, <compare>, <BigInteger.ZERO>
1478 BigInteger
.prototype.isPositive = function() {
1483 Function: isNegative
1484 Return true iff *this* < 0.
1488 true if *this*.compare(<BigInteger.ZERO>) == -1.
1492 <sign>, <isPositive>, <isZero>, <isUnit>, <compare>, <BigInteger.ZERO>
1494 BigInteger
.prototype.isNegative = function() {
1500 Return true iff *this* == 0.
1504 true if *this*.compare(<BigInteger.ZERO>) == 0.
1508 <sign>, <isPositive>, <isNegative>, <isUnit>, <BigInteger.ZERO>
1510 BigInteger
.prototype.isZero = function() {
1511 return this._s
=== 0;
1516 Multiply a <BigInteger> by a power of 10.
1518 This is equivalent to, but faster than
1521 > return this.multiply(BigInteger("1e" + n));
1524 > return this.quotient(BigInteger("1e" + -n));
1529 n - The power of 10 to multiply *this* by. *n* is converted to a
1530 javascipt number and must be no greater than <BigInteger.MAX_EXP>
1531 (0x7FFFFFFF), or an exception will be thrown.
1535 *this* * (10 ** *n*), truncated to an integer if necessary.
1541 BigInteger
.prototype.exp10 = function(n
) {
1546 if (Math
.abs(n
) > Number(MAX_EXP
)) {
1547 throw new Error("exponent too large in BigInteger.exp10");
1549 // Optimization for this == 0. This also keeps us from having to trim zeros in the positive n case
1550 if (this._s
=== 0) {
1554 var k
= new BigInteger(this._d
.slice(), this._s
, CONSTRUCT
);
1556 for (; n
>= BigInteger_base_log10
; n
-= BigInteger_base_log10
) {
1562 k
= k
.multiplySingleDigit(Math
.pow(10, n
));
1563 return (this._s
< 0 ? k
.negate() : k
);
1564 } else if (-n
>= this._d
.length
*BigInteger_base_log10
) {
1567 var k
= new BigInteger(this._d
.slice(), this._s
, CONSTRUCT
);
1569 for (n
= -n
; n
>= BigInteger_base_log10
; n
-= BigInteger_base_log10
) {
1572 return (n
== 0) ? k : k
.divRemSmall(Math
.pow(10, n
))[0];
1578 Raise a <BigInteger> to a power.
1580 In this implementation, 0**0 is 1.
1584 n - The exponent to raise *this* by. *n* must be no greater than
1585 <BigInteger.MAX_EXP> (0x7FFFFFFF), or an exception will be thrown.
1589 *this* raised to the *nth* power.
1595 BigInteger
.prototype.pow = function(n
) {
1596 if (this.isUnit()) {
1601 return BigInteger(n
).isOdd() ? this : this.negate();
1609 else if (n
._s
< 0) {
1610 if (this._s
=== 0) {
1611 throw new Error("Divide by zero");
1617 if (this._s
=== 0) {
1624 if (n
.compareAbs(MAX_EXP
) > 0) {
1625 throw new Error("exponent too large in BigInteger.pow");
1629 var two
= BigInteger
.small
[2];
1631 while (n
.isPositive()) {
1633 aux
= aux
.multiply(x
);
1639 n
= n
.quotient(two
);
1647 Raise a <BigInteger> to a power (mod m).
1649 Because it is reduced by a modulus, <modPow> is not limited by
1650 <BigInteger.MAX_EXP> like <pow>.
1654 exponent - The exponent to raise *this* by. Must be positive.
1655 modulus - The modulus.
1659 *this* ^ *exponent* (mod *modulus*).
1665 BigInteger
.prototype.modPow = function(exponent
, modulus
) {
1669 while (exponent
.isPositive()) {
1670 if (exponent
.isOdd()) {
1671 result
= result
.multiply(base
).remainder(modulus
);
1674 exponent
= exponent
.quotient(BigInteger
.small
[2]);
1675 if (exponent
.isPositive()) {
1676 base
= base
.square().remainder(modulus
);
1685 Get the natural logarithm of a <BigInteger> as a native JavaScript number.
1687 This is equivalent to
1689 > Math.log(this.toJSValue())
1691 but handles values outside of the native number range.
1701 BigInteger
.prototype.log = function() {
1703 case 0: return -Infinity
;
1704 case -1: return NaN
;
1705 default: // Fall through.
1708 var l
= this._d
.length
;
1710 if (l
*BigInteger_base_log10
< 30) {
1711 return Math
.log(this.valueOf());
1714 var N
= Math
.ceil(30/BigInteger_base_log10
);
1715 var firstNdigits
= this._d
.slice(l
- N
);
1716 return Math
.log((new BigInteger(firstNdigits
, 1, CONSTRUCT
)).valueOf()) + (l
- N
) * Math
.log(BigInteger_base
);
1721 Convert a <BigInteger> to a native JavaScript integer.
1723 This is called automatically by JavaScipt to convert a <BigInteger> to a
1728 > parseInt(this.toString(), 10)
1732 <toString>, <toJSValue>
1734 BigInteger
.prototype.valueOf = function() {
1735 return parseInt(this.toString(), 10);
1740 Convert a <BigInteger> to a native JavaScript integer.
1742 This is the same as valueOf, but more explicitly named.
1746 > parseInt(this.toString(), 10)
1750 <toString>, <valueOf>
1752 BigInteger
.prototype.toJSValue = function() {
1753 return parseInt(this.toString(), 10);
1756 var MAX_EXP
= BigInteger(0x7FFFFFFF);
1757 // Constant: MAX_EXP
1758 // The largest exponent allowed in <pow> and <exp10> (0x7FFFFFFF or 2147483647).
1759 BigInteger
.MAX_EXP
= MAX_EXP
;
1762 function makeUnary(fn
) {
1763 return function(a
) {
1764 return fn
.call(BigInteger(a
));
1768 function makeBinary(fn
) {
1769 return function(a
, b
) {
1770 return fn
.call(BigInteger(a
), BigInteger(b
));
1774 function makeTrinary(fn
) {
1775 return function(a
, b
, c
) {
1776 return fn
.call(BigInteger(a
), BigInteger(b
), BigInteger(c
));
1782 var unary
= "toJSValue,isEven,isOdd,sign,isZero,isNegative,abs,isUnit,square,negate,isPositive,toString,next,prev,log".split(",");
1783 var binary
= "compare,remainder,divRem,subtract,add,quotient,divide,multiply,pow,compareAbs".split(",");
1784 var trinary
= ["modPow"];
1786 for (i
= 0; i
< unary
.length
; i
++) {
1788 BigInteger
[fn
] = makeUnary(BigInteger
.prototype[fn
]);
1791 for (i
= 0; i
< binary
.length
; i
++) {
1793 BigInteger
[fn
] = makeBinary(BigInteger
.prototype[fn
]);
1796 for (i
= 0; i
< trinary
.length
; i
++) {
1798 BigInteger
[fn
] = makeTrinary(BigInteger
.prototype[fn
]);
1801 BigInteger
.exp10 = function(x
, n
) {
1802 return BigInteger(x
).exp10(n
);
1807 exports
.BigInteger
= BigInteger
;
1808 })(typeof exports
!== 'undefined' ? exports : this);