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