or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

arithmetic.mdbitwise.mdcomparison.mdconversion.mdindex.mdproperties.md
tile.json

tessl/npm-big-integer

An arbitrary length integer library for Javascript

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/big-integer@1.6.x

To install, run

npx @tessl/cli install tessl/npm-big-integer@1.6.0

index.mddocs/

BigInteger.js

BigInteger.js is an arbitrary-length integer arithmetic library for JavaScript that enables mathematical operations on integers of unlimited size beyond JavaScript's native number limitations. The library automatically uses native BigInt when available and acts as a polyfill for environments without native support.

Package Information

  • Package Name: big-integer
  • Package Type: npm
  • Language: JavaScript (with TypeScript definitions)
  • Installation: npm install big-integer

Core Imports

const bigInt = require('big-integer');

For ES modules:

import bigInt from 'big-integer';

Basic Usage

const bigInt = require('big-integer');

// Create big integers from various sources
const zero = bigInt();
const fromNumber = bigInt(93);
const fromString = bigInt("75643564363473453456342378564387956906736546456235345");
const fromHex = bigInt("FF", 16);
const googol = bigInt("1e100");

// Perform arithmetic operations
const a = bigInt("12345678901234567890");
const b = bigInt("98765432109876543210");
const sum = a.add(b);
const product = a.multiply(b);

// Check properties
const isPrime = bigInt(17).isPrime(); // true

// Convert back to string
console.log(sum.toString()); // "111111111011111111100"

Architecture

BigInteger.js is built around several key components:

  • Factory Function: The bigInt function creates BigInteger instances from various input types
  • Native BigInt Wrapper: When available, wraps native BigInt for optimal performance
  • Immutable Operations: All operations return new BigInteger instances
  • Method Chaining: Operations can be chained for fluent syntax
  • Pre-cached Constants: Numbers from -999 to 999 are pre-stored for performance

Capabilities

Construction and Constants

Create BigInteger instances from numbers, strings, bigints, or other BigIntegers, with support for custom bases and alphabets.

/**
 * Creates a BigInteger from various input types
 * @param value - Number, string, bigint, or BigInteger (optional, defaults to zero)
 * @param base - Base for string parsing (optional, default 10)
 * @param alphabet - Custom alphabet for base conversion (optional)
 * @param caseSensitive - Whether to treat letters as case-sensitive (optional, default false)
 * @returns BigInteger instance
 */
function bigInt(
  value?: number | bigint | string | BigInteger,
  base?: BigNumber,
  alphabet?: string,
  caseSensitive?: boolean
): BigInteger;

// Pre-defined constants
bigInt.zero: BigInteger;     // Equivalent to bigInt(0)
bigInt.one: BigInteger;      // Equivalent to bigInt(1)
bigInt.minusOne: BigInteger; // Equivalent to bigInt(-1)

// Pre-cached integer constants from -999 to 999
bigInt['-999']: BigInteger;  // through bigInt['999']

/**
 * Constructs a BigInteger from an array of digits
 * @param digits - Array of digit values
 * @param base - Number base (default 10)
 * @param isNegative - Whether the number is negative
 * @returns BigInteger
 */
bigInt.fromArray(
  digits: BigNumber[],
  base?: BigNumber,
  isNegative?: boolean
): BigInteger;

/**
 * Type guard to check if value is a BigInteger
 * @param x - Value to check
 * @returns True if x is a BigInteger
 */
bigInt.isInstance(x: any): boolean;

// Type alias for valid inputs to BigInteger operations
type BigNumber = number | bigint | string | BigInteger;

Arithmetic Operations

Perform standard arithmetic operations including addition, subtraction, multiplication, division, modulo, and exponentiation.

/**
 * Addition
 * @param number - Value to add
 * @returns New BigInteger with sum
 */
add(number: BigNumber): BigInteger;
plus(number: BigNumber): BigInteger;  // Alias for add

/**
 * Subtraction
 * @param number - Value to subtract
 * @returns New BigInteger with difference
 */
subtract(number: BigNumber): BigInteger;
minus(number: BigNumber): BigInteger;  // Alias for subtract

/**
 * Multiplication
 * @param number - Value to multiply by
 * @returns New BigInteger with product
 */
multiply(number: BigNumber): BigInteger;
times(number: BigNumber): BigInteger;  // Alias for multiply

/**
 * Integer division (discards remainder)
 * @param number - Divisor
 * @returns New BigInteger with quotient
 */
divide(number: BigNumber): BigInteger;
over(number: BigNumber): BigInteger;  // Alias for divide

/**
 * Modulo operation (remainder)
 * @param number - Divisor
 * @returns New BigInteger with remainder
 */
mod(number: BigNumber): BigInteger;
remainder(number: BigNumber): BigInteger;  // Alias for mod

/**
 * Combined division and modulo
 * @param number - Divisor
 * @returns Object with quotient and remainder
 */
divmod(number: BigNumber): { quotient: BigInteger, remainder: BigInteger };

/**
 * Exponentiation (returns 0 for negative exponents)
 * @param number - Exponent
 * @returns New BigInteger raised to power
 */
pow(number: BigNumber): BigInteger;

/**
 * Modular exponentiation
 * @param exp - Exponent
 * @param mod - Modulus
 * @returns (this ^ exp) mod mod
 */
modPow(exp: BigNumber, mod: BigNumber): BigInteger;

/**
 * Modular multiplicative inverse
 * @param mod - Modulus
 * @returns Multiplicative inverse modulo mod
 */
modInv(mod: BigNumber): BigInteger;

Arithmetic Operations

Bitwise Operations

Perform bitwise operations using two's complement representation including AND, OR, XOR, NOT, and bit shifts.

/**
 * Bitwise AND
 * @param number - Value to AND with
 * @returns New BigInteger with result
 */
and(number: BigNumber): BigInteger;

/**
 * Bitwise OR
 * @param number - Value to OR with
 * @returns New BigInteger with result
 */
or(number: BigNumber): BigInteger;

/**
 * Bitwise XOR
 * @param number - Value to XOR with
 * @returns New BigInteger with result
 */
xor(number: BigNumber): BigInteger;

/**
 * Bitwise NOT
 * @returns New BigInteger with bitwise complement
 */
not(): BigInteger;

/**
 * Left bit shift (negative values shift right)
 * @param n - Number of positions to shift
 * @returns New BigInteger shifted left
 * @throws Error if n outside range [-9007199254740992, 9007199254740992]
 */
shiftLeft(n: BigNumber): BigInteger;

/**
 * Right bit shift (negative values shift left)
 * @param n - Number of positions to shift
 * @returns New BigInteger shifted right
 * @throws Error if n outside range [-9007199254740992, 9007199254740992]
 */
shiftRight(n: BigNumber): BigInteger;

/**
 * Returns number of bits required to represent in binary
 * @returns BigInteger representing bit length
 */
bitLength(): BigInteger;

Bitwise Operations

Comparison Operations

Compare BigInteger values with comprehensive comparison methods including equality, ordering, and absolute value comparisons.

/**
 * Three-way comparison
 * @param number - Value to compare against
 * @returns -1 if less, 0 if equal, 1 if greater
 */
compare(number: BigNumber): number;
compareTo(number: BigNumber): number;  // Alias for compare

/**
 * Compare absolute values
 * @param number - Value to compare against
 * @returns -1 if |this| < |number|, 0 if equal, 1 if |this| > |number|
 */
compareAbs(number: BigNumber): number;

/**
 * Equality check
 * @param number - Value to compare
 * @returns True if equal
 */
equals(number: BigNumber): boolean;
eq(number: BigNumber): boolean;  // Alias for equals

/**
 * Inequality check
 * @param number - Value to compare
 * @returns True if not equal
 */
notEquals(number: BigNumber): boolean;
neq(number: BigNumber): boolean;  // Alias for notEquals

/**
 * Greater than check
 * @param number - Value to compare
 * @returns True if this > number
 */
greater(number: BigNumber): boolean;
gt(number: BigNumber): boolean;  // Alias for greater

/**
 * Greater than or equal check
 * @param number - Value to compare
 * @returns True if this >= number
 */
greaterOrEquals(number: BigNumber): boolean;
geq(number: BigNumber): boolean;  // Alias for greaterOrEquals

/**
 * Less than check
 * @param number - Value to compare
 * @returns True if this < number
 */
lesser(number: BigNumber): boolean;
lt(number: BigNumber): boolean;  // Alias for lesser

/**
 * Less than or equal check
 * @param number - Value to compare
 * @returns True if this <= number
 */
lesserOrEquals(number: BigNumber): boolean;
leq(number: BigNumber): boolean;  // Alias for lesserOrEquals

/**
 * Static method to return larger value
 * @param a - First value
 * @param b - Second value
 * @returns Larger of the two values
 */
bigInt.max(a: BigNumber, b: BigNumber): BigInteger;

/**
 * Static method to return smaller value
 * @param a - First value
 * @param b - Second value
 * @returns Smaller of the two values
 */
bigInt.min(a: BigNumber, b: BigNumber): BigInteger;

Comparison Operations

Property Checks and Number Theory

Check mathematical properties including parity, sign, divisibility, primality testing, and related number theory operations.

/**
 * Check if number is even
 * @returns True if even
 */
isEven(): boolean;

/**
 * Check if number is odd
 * @returns True if odd
 */
isOdd(): boolean;

/**
 * Check if number is positive (false for ±0)
 * @returns True if positive
 */
isPositive(): boolean;

/**
 * Check if number is negative (false for ±0)
 * @returns True if negative
 */
isNegative(): boolean;

/**
 * Check if number is zero (true for ±0)
 * @returns True if zero
 */
isZero(): boolean;

/**
 * Check if number is 1 or -1
 * @returns True if ±1
 */
isUnit(): boolean;

/**
 * Check if number is divisible by another
 * @param number - Potential divisor
 * @returns True if divisible
 */
isDivisibleBy(number: BigNumber): boolean;

/**
 * Deterministic primality test
 * @param strict - Force GRH-supported lower bound of 2*log(N)^2 (optional)
 * @returns True if prime
 */
isPrime(strict?: boolean): boolean;

/**
 * Probabilistic primality test (Miller-Rabin)
 * @param iterations - Number of test iterations (default 5)
 * @param rng - Custom random number generator (optional)
 * @returns True if probably prime
 */
isProbablePrime(iterations?: number, rng?: () => number): boolean;

/**
 * Greatest common divisor
 * @param a - First value
 * @param b - Second value
 * @returns GCD of a and b
 */
bigInt.gcd(a: BigNumber, b: BigNumber): BigInteger;

/**
 * Least common multiple
 * @param a - First value
 * @param b - Second value
 * @returns LCM of a and b
 */
bigInt.lcm(a: BigNumber, b: BigNumber): BigInteger;

Property Checks and Number Theory

Conversion Operations

Convert BigInteger values to various formats including strings with custom bases, arrays, native JavaScript numbers, and JSON.

/**
 * Convert to string in specified base
 * @param radix - Number base (default 10, supports 0, 1, -1, negative bases, any positive base)
 * @param alphabet - Custom alphabet (default "0123456789abcdefghijklmnopqrstuvwxyz")
 * @returns String representation
 * @throws Error for base 0 with non-zero numbers
 */
toString(radix?: number, alphabet?: string): string;

/**
 * Convert to array representation in specified radix
 * @param radix - Number base
 * @returns Object with value array and sign flag
 */
toArray(radix: number): { value: number[], isNegative: boolean };

/**
 * Convert to native JavaScript number (loses precision outside safe range)
 * @returns JavaScript number
 */
toJSNumber(): number;

/**
 * Convert to string for JSON serialization
 * @returns String representation
 */
toJSON(): string;

/**
 * Convert to number for native operators (loses precision outside safe range)
 * @returns JavaScript number
 */
valueOf(): number;

/**
 * Absolute value
 * @returns New BigInteger with absolute value
 */
abs(): BigInteger;

/**
 * Negate (flip sign)
 * @returns New BigInteger with opposite sign
 */
negate(): BigInteger;

/**
 * Add one
 * @returns New BigInteger incremented by 1
 */
next(): BigInteger;

/**
 * Subtract one
 * @returns New BigInteger decremented by 1
 */
prev(): BigInteger;

/**
 * Square the number
 * @returns New BigInteger squared
 */
square(): BigInteger;

Conversion Operations

Random Number Generation

Generate random BigInteger values within specified ranges with optional custom random number generators.

/**
 * Generate random BigInteger in range [min, max]
 * @param min - Minimum value (inclusive)
 * @param max - Maximum value (inclusive)
 * @param rng - Custom random number generator (default Math.random)
 * @returns Random BigInteger in range
 */
bigInt.randBetween(
  min: BigNumber,
  max: BigNumber,
  rng?: () => number
): BigInteger;

Types

Type definitions for working with BigInteger.

/**
 * Type alias for values that can be used as BigInteger inputs
 * Accepted by all BigInteger methods that take number parameters
 */
type BigNumber = number | bigint | string | BigInteger;

/**
 * Interface for array representation of BigInteger values
 * Returned by toArray() method
 */
interface BaseArray {
  /** Array of digit values in the specified base */
  value: number[];
  /** Flag indicating if the original number was negative */
  isNegative: boolean;
}

Usage Examples:

// BigNumber type - accepts multiple input types
function processNumber(input) {
  const bi = bigInt(input);
  return bi.multiply(2);
}

processNumber(42);           // Works with number
processNumber("12345");      // Works with string
processNumber(bigInt(100));  // Works with BigInteger

// BaseArray interface - working with array representations
const num = bigInt(12345);
const base10 = num.toArray(10);
// base10 = { value: [1, 2, 3, 4, 5], isNegative: false }

const negative = bigInt(-789);
const result = negative.toArray(10);
// result = { value: [7, 8, 9], isNegative: true }

// Reconstruct from array
const reconstructed = bigInt.fromArray(
  base10.value,
  10,
  base10.isNegative
);

Important Notes

Precision Warnings

JavaScript numbers larger than 9007199254740992 or smaller than -9007199254740992 are not precisely represented and will not produce exact results. Use string inputs for numbers outside the safe integer range:

// BAD: Number loses precision
const bad = bigInt(9007199254740993); // May be imprecise

// GOOD: String preserves exact value
const good = bigInt("9007199254740993"); // Exact

Method Chaining

BigInteger operations return new BigInteger instances, enabling method chaining:

const result = bigInt(100)
  .multiply(5)
  .add(20)
  .divide(2);
// result = 260

Native BigInt Polyfill

When native BigInt is available (ES2020+), this library acts as a thin wrapper over the native implementation for optimal performance while maintaining a consistent API.