JavaScript BigInteger Library

Awhile ago, I was playing around with Continued Fractions in JavaScript. For some of the things I wanted to do, I needed a way to represent large numbers accurately in JavaScript. I couldn’t find any convenient arbitrary-sized integer libraries for JavaScript that did everything I needed, so I decided to write my own.

If you need more than just integer arithmetic, John Tobey has written a full Scheme number tower using BigInteger, with exact rational numbers (fractions), real, and complex numbers. You can get it at https://github.com/jtobey/javascript-bignum.

Documentation

Read the Natural Docs API documentation.

Download

I’m currently hosting the source code on github. You can download it here. I’m releasing it under the Open Source/Free Software MIT license.

Design Considerations

BigIntegers are immutable

Instances can be shared by reference to save time and memory. Technically, you can access the “private” data to modify them yourself, but none of the library methods modify their arguments.

Numbers are stored as little-endian arrays in base 10

The library could easily be changed to use a larger base, saving memory for large numbers, but I decided to use base 10 to speed up parsing and formatting. Most of the numbers I needed aren’t extremely large anyways, and in my testing, converting BigIntegers to strings was one of the slowest operations, so I decided decimal was the way to go. If you really need performance, don’t use JavaScript.

I’ve tried to balance simplicity and performance

Performance is not the primary concern, but I have tried to make things efficent. The multiply function currently uses the somewhat naive O(n2) algorithm you learn in school instead of faster algorithms like Karatsuba multiplication. In the (somewhat limited) testing I’ve done so far the added complexity and recursion makes Karatsuba multiplication slower for most integer sizes.