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