-
-/*
- Function: compareAbs
- Compare the absolute value of two <BigIntegers>.
-
- Calling <compareAbs> is faster than calling <abs> twice, then <compare>.
-
- Parameters:
-
- n - The number to compare to *this*. Will be converted to a <BigInteger>.
-
- Returns:
-
- -1, 0, or +1 if *|this|* is less than, equal to, or greater than *|n|*.
-
- See Also:
-
- <compare>, <abs>
-*/
-BigInteger.prototype.compareAbs = function(n) {
- if (this === n) {
- return 0;
- }
-
- if (!(n instanceof BigInteger)) {
- if (!isFinite(n)) {
- return(isNaN(n) ? n : -1);
- }
- n = BigInteger(n);
- }
-
- if (this._s === 0) {
- return (n._s !== 0) ? -1 : 0;
- }
- if (n._s === 0) {
- return 1;
- }
-
- var l = this._d.length;
- var nl = n._d.length;
- if (l < nl) {
- return -1;
- }
- else if (l > nl) {
- return 1;
- }
-
- var a = this._d;
- var b = n._d;
- for (var i = l-1; i >= 0; i--) {
- if (a[i] !== b[i]) {
- return a[i] < b[i] ? -1 : 1;
- }
- }
-
- return 0;
-};
-
-/*
- Function: compare
- Compare two <BigIntegers>.
-
- Parameters:
-
- n - The number to compare to *this*. Will be converted to a <BigInteger>.
-
- Returns:
-
- -1, 0, or +1 if *this* is less than, equal to, or greater than *n*.
-
- See Also:
-
- <compareAbs>, <isPositive>, <isNegative>, <isUnit>
-*/
-BigInteger.prototype.compare = function(n) {
- if (this === n) {
- return 0;
- }
-
- n = BigInteger(n);
-
- if (this._s === 0) {
- return -n._s;
- }
-
- if (this._s === n._s) { // both positive or both negative
- var cmp = this.compareAbs(n);
- return cmp * this._s;
- }
- else {
- return this._s;
- }
-};
-
-/*
- Function: isUnit
- Return true iff *this* is either 1 or -1.
-
- Returns:
-
- true if *this* compares equal to <BigInteger.ONE> or <BigInteger.M_ONE>.
-
- See Also:
-
- <isZero>, <isNegative>, <isPositive>, <compareAbs>, <compare>,
- <BigInteger.ONE>, <BigInteger.M_ONE>
-*/
-BigInteger.prototype.isUnit = function() {
- return this === ONE ||
- this === M_ONE ||
- (this._d.length === 1 && this._d[0] === 1);
-};
-
-/*
- Function: multiply
- Multiply two <BigIntegers>.
-
- Parameters:
-
- n - The number to multiply *this* by. Will be converted to a
- <BigInteger>.
-
- Returns:
-
- The numbers multiplied together.
-
- See Also:
-
- <add>, <subtract>, <quotient>, <square>
-*/
-BigInteger.prototype.multiply = function(n) {
- // TODO: Consider adding Karatsuba multiplication for large numbers
- if (this._s === 0) {
- return ZERO;
- }
-
- n = BigInteger(n);
- if (n._s === 0) {
- return ZERO;
- }
- if (this.isUnit()) {
- if (this._s < 0) {
- return n.negate();
- }
- return n;
- }
- if (n.isUnit()) {
- if (n._s < 0) {
- return this.negate();
- }
- return this;
- }
- if (this === n) {
- return this.square();
- }
-
- var r = (this._d.length >= n._d.length);
- var a = (r ? this : n)._d; // a will be longer than b
- var b = (r ? n : this)._d;
- var al = a.length;
- var bl = b.length;
-
- var pl = al + bl;
- var partial = new Array(pl);
- var i;
- for (i = 0; i < pl; i++) {
- partial[i] = 0;
- }
-
- for (i = 0; i < bl; i++) {
- var carry = 0;
- var bi = b[i];
- var jlimit = al + i;
- var digit;
- for (var j = i; j < jlimit; j++) {
- digit = partial[j] + bi * a[j - i] + carry;
- carry = (digit / BigInteger_base) | 0;
- partial[j] = (digit % BigInteger_base) | 0;
- }
- if (carry) {
- digit = partial[j] + carry;
- carry = (digit / BigInteger_base) | 0;
- partial[j] = digit % BigInteger_base;
- }
- }
- return new BigInteger(partial, this._s * n._s, CONSTRUCT);
-};
-
-// Multiply a BigInteger by a single-digit native number
-// Assumes that this and n are >= 0
-// This is not really intended to be used outside the library itself
-BigInteger.prototype.multiplySingleDigit = function(n) {
- if (n === 0 || this._s === 0) {
- return ZERO;
- }
- if (n === 1) {
- return this;
- }
-
- var digit;
- if (this._d.length === 1) {
- digit = this._d[0] * n;
- if (digit >= BigInteger_base) {
- return new BigInteger([(digit % BigInteger_base)|0,
- (digit / BigInteger_base)|0], 1, CONSTRUCT);
- }
- return new BigInteger([digit], 1, CONSTRUCT);
- }
-
- if (n === 2) {
- return this.add(this);
- }
- if (this.isUnit()) {
- return new BigInteger([n], 1, CONSTRUCT);
- }
-
- var a = this._d;
- var al = a.length;
-
- var pl = al + 1;
- var partial = new Array(pl);
- for (var i = 0; i < pl; i++) {
- partial[i] = 0;
- }
-
- var carry = 0;
- for (var j = 0; j < al; j++) {
- digit = n * a[j] + carry;
- carry = (digit / BigInteger_base) | 0;
- partial[j] = (digit % BigInteger_base) | 0;
- }
- if (carry) {
- partial[j] = carry;
- }
-
- return new BigInteger(partial, 1, CONSTRUCT);
-};
-
-/*
- Function: square
- Multiply a <BigInteger> by itself.
-
- This is slightly faster than regular multiplication, since it removes the
- duplicated multiplcations.
-
- Returns:
-
- > this.multiply(this)
-
- See Also:
- <multiply>
-*/
-BigInteger.prototype.square = function() {
- // Normally, squaring a 10-digit number would take 100 multiplications.
- // Of these 10 are unique diagonals, of the remaining 90 (100-10), 45 are repeated.
- // This procedure saves (N*(N-1))/2 multiplications, (e.g., 45 of 100 multiplies).
- // Based on code by Gary Darby, Intellitech Systems Inc., www.DelphiForFun.org
-
- if (this._s === 0) {
- return ZERO;
- }
- if (this.isUnit()) {
- return ONE;
- }
-
- var digits = this._d;
- var length = digits.length;
- var imult1 = new Array(length + length + 1);
- var product, carry, k;
- var i;
-
- // Calculate diagonal
- for (i = 0; i < length; i++) {
- k = i * 2;
- product = digits[i] * digits[i];
- carry = (product / BigInteger_base) | 0;
- imult1[k] = product % BigInteger_base;
- imult1[k + 1] = carry;
- }
-
- // Calculate repeating part
- for (i = 0; i < length; i++) {
- carry = 0;
- k = i * 2 + 1;
- for (var j = i + 1; j < length; j++, k++) {
- product = digits[j] * digits[i] * 2 + imult1[k] + carry;
- carry = (product / BigInteger_base) | 0;
- imult1[k] = product % BigInteger_base;
- }
- k = length + i;
- var digit = carry + imult1[k];
- carry = (digit / BigInteger_base) | 0;
- imult1[k] = digit % BigInteger_base;
- imult1[k + 1] += carry;
- }
-
- return new BigInteger(imult1, 1, CONSTRUCT);
-};
-
-/*
- Function: quotient
- Divide two <BigIntegers> and truncate towards zero.
-
- <quotient> throws an exception if *n* is zero.
-
- Parameters:
-
- n - The number to divide *this* by. Will be converted to a <BigInteger>.
-
- Returns:
-
- The *this* / *n*, truncated to an integer.
-
- See Also:
-
- <add>, <subtract>, <multiply>, <divRem>, <remainder>
-*/
-BigInteger.prototype.quotient = function(n) {
- return this.divRem(n)[0];
-};
-
-/*
- Function: divide
- Deprecated synonym for <quotient>.
-*/
-BigInteger.prototype.divide = BigInteger.prototype.quotient;
-
-/*
- Function: remainder
- Calculate the remainder of two <BigIntegers>.
-
- <remainder> throws an exception if *n* is zero.
-
- Parameters:
-
- n - The remainder after *this* is divided *this* by *n*. Will be
- converted to a <BigInteger>.
-
- Returns:
-
- *this* % *n*.
-
- See Also:
-
- <divRem>, <quotient>
-*/
-BigInteger.prototype.remainder = function(n) {
- return this.divRem(n)[1];
-};
-
-/*
- Function: divRem
- Calculate the integer quotient and remainder of two <BigIntegers>.
-
- <divRem> throws an exception if *n* is zero.
-
- Parameters:
-
- n - The number to divide *this* by. Will be converted to a <BigInteger>.
-
- Returns:
-
- A two-element array containing the quotient and the remainder.
-
- > a.divRem(b)
-
- is exactly equivalent to
-
- > [a.quotient(b), a.remainder(b)]
-
- except it is faster, because they are calculated at the same time.
-
- See Also:
-
- <quotient>, <remainder>
-*/
-BigInteger.prototype.divRem = function(n) {
- n = BigInteger(n);
- if (n._s === 0) {
- throw new Error("Divide by zero");
- }
- if (this._s === 0) {
- return [ZERO, ZERO];
- }
- if (n._d.length === 1) {
- return this.divRemSmall(n._s * n._d[0]);
- }
-
- // Test for easy cases -- |n1| <= |n2|
- switch (this.compareAbs(n)) {
- case 0: // n1 == n2
- return [this._s === n._s ? ONE : M_ONE, ZERO];
- case -1: // |n1| < |n2|
- return [ZERO, this];
- }
-
- var sign = this._s * n._s;
- var a = n.abs();
- var b_digits = this._d;
- var b_index = b_digits.length;
- var digits = n._d.length;
- var quot = [];
- var guess;
-
- var part = new BigInteger([], 0, CONSTRUCT);
-
- while (b_index) {
- part._d.unshift(b_digits[--b_index]);
- part = new BigInteger(part._d, 1, CONSTRUCT);
-
- if (part.compareAbs(n) < 0) {
- quot.push(0);
- continue;
- }
- if (part._s === 0) {
- guess = 0;
- }
- else {
- var xlen = part._d.length, ylen = a._d.length;
- var highx = part._d[xlen-1]*BigInteger_base + part._d[xlen-2];
- var highy = a._d[ylen-1]*BigInteger_base + a._d[ylen-2];
- if (part._d.length > a._d.length) {
- // The length of part._d can either match a._d length,
- // or exceed it by one.
- highx = (highx+1)*BigInteger_base;
- }
- guess = Math.ceil(highx/highy);
- }
- do {
- var check = a.multiplySingleDigit(guess);
- if (check.compareAbs(part) <= 0) {
- break;
- }
- guess--;
- } while (guess);
-
- quot.push(guess);
- if (!guess) {
- continue;
- }
- var diff = part.subtract(check);
- part._d = diff._d.slice();
- }
-
- return [new BigInteger(quot.reverse(), sign, CONSTRUCT),
- new BigInteger(part._d, this._s, CONSTRUCT)];
-};
-
-// Throws an exception if n is outside of (-BigInteger.base, -1] or
-// [1, BigInteger.base). It's not necessary to call this, since the
-// other division functions will call it if they are able to.
-BigInteger.prototype.divRemSmall = function(n) {
- var r;
- n = +n;
- if (n === 0) {
- throw new Error("Divide by zero");
- }
-
- var n_s = n < 0 ? -1 : 1;
- var sign = this._s * n_s;
- n = Math.abs(n);
-
- if (n < 1 || n >= BigInteger_base) {
- throw new Error("Argument out of range");
- }
-
- if (this._s === 0) {
- return [ZERO, ZERO];
- }
-
- if (n === 1 || n === -1) {
- return [(sign === 1) ? this.abs() : new BigInteger(this._d, sign, CONSTRUCT), ZERO];
- }
-
- // 2 <= n < BigInteger_base
-
- // divide a single digit by a single digit
- if (this._d.length === 1) {
- var q = new BigInteger([(this._d[0] / n) | 0], 1, CONSTRUCT);
- r = new BigInteger([(this._d[0] % n) | 0], 1, CONSTRUCT);
- if (sign < 0) {
- q = q.negate();
- }
- if (this._s < 0) {
- r = r.negate();
- }
- return [q, r];
- }
-
- var digits = this._d.slice();
- var quot = new Array(digits.length);
- var part = 0;
- var diff = 0;
- var i = 0;
- var guess;
-
- while (digits.length) {
- part = part * BigInteger_base + digits[digits.length - 1];
- if (part < n) {
- quot[i++] = 0;
- digits.pop();
- diff = BigInteger_base * diff + part;
- continue;
- }
- if (part === 0) {
- guess = 0;
- }
- else {
- guess = (part / n) | 0;
- }
-
- var check = n * guess;
- diff = part - check;
- quot[i++] = guess;
- if (!guess) {
- digits.pop();
- continue;
- }
-
- digits.pop();
- part = diff;
- }
-
- r = new BigInteger([diff], 1, CONSTRUCT);
- if (this._s < 0) {
- r = r.negate();
- }
- return [new BigInteger(quot.reverse(), sign, CONSTRUCT), r];
-};
-
-/*
- Function: isEven
- Return true iff *this* is divisible by two.
-
- Note that <BigInteger.ZERO> is even.
-
- Returns:
-
- true if *this* is even, false otherwise.
-
- See Also:
-
- <isOdd>
-*/
-BigInteger.prototype.isEven = function() {
- var digits = this._d;
- return this._s === 0 || digits.length === 0 || (digits[0] % 2) === 0;
-};
-
-/*
- Function: isOdd
- Return true iff *this* is not divisible by two.
-
- Returns:
-
- true if *this* is odd, false otherwise.
-
- See Also:
-
- <isEven>
-*/
-BigInteger.prototype.isOdd = function() {
- return !this.isEven();
-};
-
-/*
- Function: sign
- Get the sign of a <BigInteger>.
-
- Returns:
-
- * -1 if *this* < 0
- * 0 if *this* == 0
- * +1 if *this* > 0
-
- See Also:
-
- <isZero>, <isPositive>, <isNegative>, <compare>, <BigInteger.ZERO>
-*/
-BigInteger.prototype.sign = function() {
- return this._s;
-};
-
-/*
- Function: isPositive
- Return true iff *this* > 0.
-
- Returns:
-
- true if *this*.compare(<BigInteger.ZERO>) == 1.
-
- See Also:
-
- <sign>, <isZero>, <isNegative>, <isUnit>, <compare>, <BigInteger.ZERO>
-*/
-BigInteger.prototype.isPositive = function() {
- return this._s > 0;
-};
-
-/*
- Function: isNegative
- Return true iff *this* < 0.
-
- Returns:
-
- true if *this*.compare(<BigInteger.ZERO>) == -1.
-
- See Also:
-
- <sign>, <isPositive>, <isZero>, <isUnit>, <compare>, <BigInteger.ZERO>
-*/
-BigInteger.prototype.isNegative = function() {
- return this._s < 0;
-};
-
-/*
- Function: isZero
- Return true iff *this* == 0.
-
- Returns:
-
- true if *this*.compare(<BigInteger.ZERO>) == 0.
-
- See Also:
-
- <sign>, <isPositive>, <isNegative>, <isUnit>, <BigInteger.ZERO>
-*/
-BigInteger.prototype.isZero = function() {
- return this._s === 0;
-};
-
-/*
- Function: exp10
- Multiply a <BigInteger> by a power of 10.
-
- This is equivalent to, but faster than
-
- > if (n >= 0) {
- > return this.multiply(BigInteger("1e" + n));
- > }
- > else { // n <= 0
- > return this.quotient(BigInteger("1e" + -n));
- > }
-
- Parameters:
-
- n - The power of 10 to multiply *this* by. *n* is converted to a
- javascipt number and must be no greater than <BigInteger.MAX_EXP>
- (0x7FFFFFFF), or an exception will be thrown.
-
- Returns:
-
- *this* * (10 ** *n*), truncated to an integer if necessary.
-
- See Also:
-
- <pow>, <multiply>
-*/
-BigInteger.prototype.exp10 = function(n) {
- n = +n;
- if (n === 0) {
- return this;
- }
- if (Math.abs(n) > Number(MAX_EXP)) {
- throw new Error("exponent too large in BigInteger.exp10");
- }
- // Optimization for this == 0. This also keeps us from having to trim zeros in the positive n case
- if (this._s === 0) {
- return ZERO;
- }
- if (n > 0) {
- var k = new BigInteger(this._d.slice(), this._s, CONSTRUCT);
-
- for (; n >= BigInteger_base_log10; n -= BigInteger_base_log10) {
- k._d.unshift(0);
- }
- if (n == 0)
- return k;
- k._s = 1;
- k = k.multiplySingleDigit(Math.pow(10, n));
- return (this._s < 0 ? k.negate() : k);
- } else if (-n >= this._d.length*BigInteger_base_log10) {
- return ZERO;
- } else {
- var k = new BigInteger(this._d.slice(), this._s, CONSTRUCT);
-
- for (n = -n; n >= BigInteger_base_log10; n -= BigInteger_base_log10) {
- k._d.shift();
- }
- return (n == 0) ? k : k.divRemSmall(Math.pow(10, n))[0];
- }
-};
-
-/*
- Function: pow
- Raise a <BigInteger> to a power.
-
- In this implementation, 0**0 is 1.
-
- Parameters:
-
- n - The exponent to raise *this* by. *n* must be no greater than
- <BigInteger.MAX_EXP> (0x7FFFFFFF), or an exception will be thrown.
-
- Returns:
-
- *this* raised to the *nth* power.
-
- See Also:
-
- <modPow>
-*/
-BigInteger.prototype.pow = function(n) {
- if (this.isUnit()) {
- if (this._s > 0) {
- return this;
- }
- else {
- return BigInteger(n).isOdd() ? this : this.negate();
- }
- }
-
- n = BigInteger(n);
- if (n._s === 0) {
- return ONE;
- }
- else if (n._s < 0) {
- if (this._s === 0) {
- throw new Error("Divide by zero");
- }
- else {
- return ZERO;
- }
- }
- if (this._s === 0) {
- return ZERO;
- }
- if (n.isUnit()) {
- return this;
- }
-
- if (n.compareAbs(MAX_EXP) > 0) {
- throw new Error("exponent too large in BigInteger.pow");
- }
- var x = this;
- var aux = ONE;
- var two = BigInteger.small[2];
-
- while (n.isPositive()) {
- if (n.isOdd()) {
- aux = aux.multiply(x);
- if (n.isUnit()) {
- return aux;
- }
- }
- x = x.square();
- n = n.quotient(two);
- }
-
- return aux;
-};
-
-/*
- Function: modPow
- Raise a <BigInteger> to a power (mod m).
-
- Because it is reduced by a modulus, <modPow> is not limited by
- <BigInteger.MAX_EXP> like <pow>.
-
- Parameters:
-
- exponent - The exponent to raise *this* by. Must be positive.
- modulus - The modulus.
-
- Returns:
-
- *this* ^ *exponent* (mod *modulus*).
-
- See Also:
-
- <pow>, <mod>
-*/
-BigInteger.prototype.modPow = function(exponent, modulus) {
- var result = ONE;
- var base = this;
-
- while (exponent.isPositive()) {
- if (exponent.isOdd()) {
- result = result.multiply(base).remainder(modulus);
- }
-
- exponent = exponent.quotient(BigInteger.small[2]);
- if (exponent.isPositive()) {
- base = base.square().remainder(modulus);
- }
- }
-
- return result;
-};
-
-/*
- Function: log
- Get the natural logarithm of a <BigInteger> as a native JavaScript number.
-
- This is equivalent to
-
- > Math.log(this.toJSValue())
-
- but handles values outside of the native number range.
-
- Returns:
-
- log( *this* )
-
- See Also:
-
- <toJSValue>
-*/
-BigInteger.prototype.log = function() {
- switch (this._s) {
- case 0: return -Infinity;
- case -1: return NaN;
- default: // Fall through.
- }
-
- var l = this._d.length;
-
- if (l*BigInteger_base_log10 < 30) {
- return Math.log(this.valueOf());
- }
-
- var N = Math.ceil(30/BigInteger_base_log10);
- var firstNdigits = this._d.slice(l - N);
- return Math.log((new BigInteger(firstNdigits, 1, CONSTRUCT)).valueOf()) + (l - N) * Math.log(BigInteger_base);
-};
-
-/*
- Function: valueOf
- Convert a <BigInteger> to a native JavaScript integer.
-
- This is called automatically by JavaScipt to convert a <BigInteger> to a
- native value.
-
- Returns:
-
- > parseInt(this.toString(), 10)
-
- See Also:
-
- <toString>, <toJSValue>
-*/
-BigInteger.prototype.valueOf = function() {
- return parseInt(this.toString(), 10);
-};
-
-/*
- Function: toJSValue
- Convert a <BigInteger> to a native JavaScript integer.
-
- This is the same as valueOf, but more explicitly named.
-
- Returns:
-
- > parseInt(this.toString(), 10)
-
- See Also:
-
- <toString>, <valueOf>
-*/
-BigInteger.prototype.toJSValue = function() {
- return parseInt(this.toString(), 10);
-};
-
-var MAX_EXP = BigInteger(0x7FFFFFFF);
-// Constant: MAX_EXP
-// The largest exponent allowed in <pow> and <exp10> (0x7FFFFFFF or 2147483647).
-BigInteger.MAX_EXP = MAX_EXP;
-
-(function() {
- function makeUnary(fn) {
- return function(a) {
- return fn.call(BigInteger(a));
- };
- }
-
- function makeBinary(fn) {
- return function(a, b) {
- return fn.call(BigInteger(a), BigInteger(b));
- };
- }
-
- function makeTrinary(fn) {
- return function(a, b, c) {
- return fn.call(BigInteger(a), BigInteger(b), BigInteger(c));
- };
- }
-
- (function() {
- var i, fn;
- var unary = "toJSValue,isEven,isOdd,sign,isZero,isNegative,abs,isUnit,square,negate,isPositive,toString,next,prev,log".split(",");
- var binary = "compare,remainder,divRem,subtract,add,quotient,divide,multiply,pow,compareAbs".split(",");
- var trinary = ["modPow"];
-
- for (i = 0; i < unary.length; i++) {
- fn = unary[i];
- BigInteger[fn] = makeUnary(BigInteger.prototype[fn]);
- }
-
- for (i = 0; i < binary.length; i++) {
- fn = binary[i];
- BigInteger[fn] = makeBinary(BigInteger.prototype[fn]);
- }
-
- for (i = 0; i < trinary.length; i++) {
- fn = trinary[i];
- BigInteger[fn] = makeTrinary(BigInteger.prototype[fn]);
- }
-
- BigInteger.exp10 = function(x, n) {
- return BigInteger(x).exp10(n);
- };
- })();
-})();
-
-exports.BigInteger = BigInteger;
-})(typeof exports !== 'undefined' ? exports : this);