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