Yet another class for arbitrary-precision integers in pure JavaScript. Small. Well tested.
npm install js-big-integerBigInteger
==========
Yet another BigInteger class in JavaScript
This library performs arithmetic operations on integers of arbitrary size.
To use it from a web browser:
``
`
`
To use it from the node.js:
`
npm install Yaffle/BigInteger
`
Then:
`
var BigInteger = require("js-big-integer").BigInteger;
BigInteger
The API is terrible, but small integers are stored as primitive numbers, so operations on small integers are faster.
The API was updated to match the API provided by https://github.com/GoogleChromeLabs/jsbi
Operation | | Number | BigInt (https://github.com/tc39/proposal-bigint)
BigInteger.BigInt(string)
-----------------------|--------------------------------------|----------------------------------|---------------------------------------------------
Conversion from String | | Number(string) | BigInt(string)
BigInteger.BigInt(number)
Conversion from Number | | N/A | BigInt(number)
a.toString(radix)
Conversion to String | | a.toString(radix) | a.toString(radix)
a.toNumber()
Conversion to Number | | N/A | Number(bigint)
BigInteger.add(a, b)
Addition | | a + b | a + b
BigInteger.subtract(a, b)
Subtraction | | a - b | a - b
BigInteger.multiply(a, b)
Multiplication | | 0 + a b | a b
BigInteger.divide(a, b)
Division | | 0 + Math.trunc(a / b) | a / b
BigInteger.remainder(a, b)
Remainder | | 0 + a % b | a % b
BigInteger.exponentiate(a, b)
Exponentiation | | 0 + ab | ab
BigInteger.unaryMinus(a)
Negation | | 0 - a | -a
BigInteger.equal(a, b)
Comparison | | a === b | a === b
BigInteger.lessThan(a, b)
... | | a < b | a < b
BigInteger.greaterThan(a, b)
... | | a > b | a > b
BigInteger.notEqual(a, b)
... | | a !== b | a !== b
BigInteger.lessThanOrEqual(a, b)
... | | a <= b | a <= b
BigInteger.greaterThanOrEqual(a, b)
... | | a >= b | a >= b
BigInteger.signedRightShift(a, b)
Signed Right Shift | | a >> b | a >> b
BigInteger.leftShift(a, b)
Left Shift | | a << b | a << b
`
Example
=======
javascript
``
var factorial = function (n) {
var result = BigInteger.BigInt(1);
var i = 0;
while (++i <= n) {
result = BigInteger.multiply(result, BigInteger.BigInt(i));
}
return result;
};
console.log(factorial(30).toString(10));
Other pure JavaScript implementations:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
Benchmark: