BigInteger.js Build Status Coverage Status Monthly Downloads

BigInteger.js is an arbitrary-length integer library for Javascript, allowing arithmetic operations on integers of unlimited size, notwithstanding memory and time limitations.

Update (December 2, 2018): BigInt is being added as a native feature of JavaScript. This library now works as a polyfill: if the environment supports the native BigInt, this library acts as a thin wrapper over the native implementation.

Installation

If you are using a browser, you can download BigInteger.js from GitHub or just hotlink to it:

<script src="https://peterolson.github.io/BigInteger.js/BigInteger.min.js"></script>

If you are using node, you can install BigInteger with npm.

npm install big-integer

Then you can include it in your code:

var bigInt = require("big-integer");

Usage

bigInt(number, [base], [alphabet], [caseSensitive])

You can create a bigInt by calling the bigInt function. You can pass in

If you provide a second parameter, then it will parse number as a number in base base. Note that base can be any bigInt (even negative or zero). The letters "a-z" and "A-Z" will be interpreted as the numbers 10 to 35. Higher digits can be specified in angle brackets (< and >). The default base is 10.

You can specify a custom alphabet for base conversion with the third parameter. The default alphabet is "0123456789abcdefghijklmnopqrstuvwxyz".

The fourth parameter specifies whether or not the number string should be case-sensitive, i.e. whether a and A should be treated as different digits. By default caseSensitive is false.

Examples:

var zero = bigInt();
var ninetyThree = bigInt(93);
var largeNumber = bigInt("75643564363473453456342378564387956906736546456235345");
var googol = bigInt("1e100");
var bigNumber = bigInt(largeNumber);

var maximumByte = bigInt("FF", 16);
var fiftyFiveGoogol = bigInt("<55>0", googol);

Note that Javascript numbers larger than 9007199254740992 and smaller than -9007199254740992 are not precisely represented numbers and will not produce exact results. If you are dealing with numbers outside that range, it is better to pass in strings.

Method Chaining

Note that bigInt operations return bigInts, which allows you to chain methods, for example:

var salary = bigInt(dollarsPerHour).times(hoursWorked).plus(randomBonuses)

Constants

There are three named constants already stored that you do not have to construct with the bigInt function yourself:

The numbers from -999 to 999 are also already prestored and can be accessed using bigInt[index], for example:

Methods

abs()

Returns the absolute value of a bigInt.

add(number)

Performs addition.

View benchmarks for this method

and(number)

Performs the bitwise AND operation. The operands are treated as if they were represented using two's complement representation.

bitLength()

Returns the number of digits required to represent a bigInt in binary.

compare(number)

Performs a comparison between two numbers. If the numbers are equal, it returns 0. If the first number is greater, it returns 1. If the first number is lesser, it returns -1.

compareAbs(number)

Performs a comparison between the absolute value of two numbers.

compareTo(number)

Alias for the compare method.

divide(number)

Performs integer division, disregarding the remainder.

View benchmarks for this method

divmod(number)

Performs division and returns an object with two properties: quotient and remainder. The sign of the remainder will match the sign of the dividend.

View benchmarks for this method

eq(number)

Alias for the equals method.

equals(number)

Checks if two numbers are equal.

geq(number)

Alias for the greaterOrEquals method.

greater(number)

Checks if the first number is greater than the second.

greaterOrEquals(number)

Checks if the first number is greater than or equal to the second.

gt(number)

Alias for the greater method.

isDivisibleBy(number)

Returns true if the first number is divisible by the second number, false otherwise.

isEven()

Returns true if the number is even, false otherwise.

isNegative()

Returns true if the number is negative, false otherwise. Returns false for 0 and -0.

isOdd()

Returns true if the number is odd, false otherwise.

isPositive()

Return true if the number is positive, false otherwise. Returns false for 0 and -0.

isPrime()

Returns true if the number is prime, false otherwise.

isProbablePrime([iterations], [rng])

Returns true if the number is very likely to be prime, false otherwise. Supplying iterations is optional - it determines the number of iterations of the test (default: 5). The more iterations, the lower chance of getting a false positive. This uses the Miller Rabin test.

Note that this function is not deterministic, since it relies on random sampling of factors, so the result for some numbers is not always the same - unless you pass a predictable random number generator as rng. The behavior and requirements are the same as with randBetween.

If the number is composite then the Miller–Rabin primality test declares the number probably prime with a probability at most 4 to the power −iterations. If the number is prime, this function always returns true.

isUnit()

Returns true if the number is 1 or -1, false otherwise.

isZero()

Return true if the number is 0 or -0, false otherwise.

leq(number)

Alias for the lesserOrEquals method.

lesser(number)

Checks if the first number is lesser than the second.

lesserOrEquals(number)

Checks if the first number is less than or equal to the second.

lt(number)

Alias for the lesser method.

minus(number)

Alias for the subtract method.

View benchmarks for this method

mod(number)

Performs division and returns the remainder, disregarding the quotient. The sign of the remainder will match the sign of the dividend.

View benchmarks for this method

modInv(mod)

Finds the multiplicative inverse of the number modulo mod.

modPow(exp, mod)

Takes the number to the power exp modulo mod.

multiply(number)

Performs multiplication.

View benchmarks for this method

neq(number)

Alias for the notEquals method.

next()

Adds one to the number.

not()

Performs the bitwise NOT operation. The operands are treated as if they were represented using two's complement representation.

notEquals(number)

Checks if two numbers are not equal.

or(number)

Performs the bitwise OR operation. The operands are treated as if they were represented using two's complement representation.

over(number)

Alias for the divide method.

View benchmarks for this method

plus(number)

Alias for the add method.

View benchmarks for this method

pow(number)

Performs exponentiation. If the exponent is less than 0, pow returns 0. bigInt.zero.pow(0) returns 1.

View benchmarks for this method

prev(number)

Subtracts one from the number.

remainder(number)

Alias for the mod method.

View benchmarks for this method

shiftLeft(n)

Shifts the number left by n places in its binary representation. If a negative number is provided, it will shift right. Throws an error if n is outside of the range [-9007199254740992, 9007199254740992].

shiftRight(n)

Shifts the number right by n places in its binary representation. If a negative number is provided, it will shift left. Throws an error if n is outside of the range [-9007199254740992, 9007199254740992].

square()

Squares the number

View benchmarks for this method

subtract(number)

Performs subtraction.

View benchmarks for this method

times(number)

Alias for the multiply method.

View benchmarks for this method

toArray(radix)

Converts a bigInt into an object with the properties "value" and "isNegative." "Value" is an array of integers modulo the given radix. "isNegative" is a boolean that represents the sign of the result.

Negative bases are supported.

Base 1 and base -1 are also supported.

Base 0 is only allowed for the number zero.

toJSNumber()

Converts a bigInt into a native Javascript number. Loses precision for numbers outside the range [-9007199254740992, 9007199254740992].

xor(number)

Performs the bitwise XOR operation. The operands are treated as if they were represented using two's complement representation.

Static Methods

fromArray(digits, base = 10, isNegative?)

Constructs a bigInt from an array of digits in base base. The optional isNegative flag will make the number negative.

gcd(a, b)

Finds the greatest common denominator of a and b.

isInstance(x)

Returns true if x is a BigInteger, false otherwise.

lcm(a,b)

Finds the least common multiple of a and b.

max(a,b)

Returns the largest of a and b.

min(a,b)

Returns the smallest of a and b.

randBetween(min, max, [rng])

Returns a random number between min and max, optionally using rng to generate randomness.

rng should take no arguments and return a number between 0 and 1. It defaults to Math.random.

Override Methods

toString(radix = 10, [alphabet])

Converts a bigInt to a string. There is an optional radix parameter (which defaults to 10) that converts the number to the given radix. Digits in the range 10-35 will use the letters a-z.

You can use a custom base alphabet with the second parameter. The default alphabet is "0123456789abcdefghijklmnopqrstuvwxyz".

Note that arithmetical operators will trigger the valueOf function rather than the toString function. When converting a bigInteger to a string, you should use the toString method or the String function instead of adding the empty string.

Bases larger than 36 are supported. If a digit is greater than or equal to 36, it will be enclosed in angle brackets.

Negative bases are also supported.

Base 1 and base -1 are also supported.

Base 0 is only allowed for the number zero.

View benchmarks for this method

valueOf()

Converts a bigInt to a native Javascript number. This override allows you to use native arithmetic operators without explicit conversion:

Contributors

To contribute, just fork the project, make some changes, and submit a pull request. Please verify that the unit tests pass before submitting.

The unit tests are contained in the spec/spec.js file. You can run them locally by opening the spec/SpecRunner.html or file or running npm test. You can also run the tests online from GitHub.

There are performance benchmarks that can be viewed from the benchmarks/index.html page. You can run them online from GitHub.

License

This project is public domain. For more details, read about the Unlicense.