Skip to content

polarstoat/bigint-factorial

Repository files navigation

bigint-factorial

npm npm bundle size David GitHub

Tiny factorial function using JavaScript's built-in BigInt

Factorials get very big, very quickly. Older packages for calculating them that use the number primitive internally suffer the following issues:

  • Subject to imprecision at factorials larger than 18 (at which point they surpass Number.MAX_SAFE_INTEGER)
  • Return Infinity at factorials larger than 170 (at which point they surpass Number.MAX_VALUE)

This package avoids these by dealing exclusively with the bigint primitive.

Install

Install with npm (or Yarn)

npm i bigint-factorial

Usage

  1. Import the package

    import factorial from 'bigint-factorial';
    // or
    const factorial = require('bigint-factorial');
  2. Calculate factorials

    factorial(5n);
    // ↪︎ 120n
    
    factorial(6n);
    // ↪︎ 720n
    
    factorial(7n);
    // ↪︎ 5040n
    
    factorial(183n);
    // ↪︎ 1211079010624906224171770242040000913194755344907123328387229208384122199143398983962077168073033852647945203036376445283346314711222230177466494273255728793463071956674839497876987299889729720327479783667584731115257659422804284707863129430806869565563037239578516564219715854442393339376435200000000000000000000000000000000000000000000n

API

factorial ⇒ bigint

Calculate the factorial of n

Returns: bigint - The factorial of n
Throws:

  • TypeError If n is not of type 'bigint'
  • RangeError If n is negative
Param Type Description
n bigint The number to calculate the factorial of

System requirements

This package has been tested and confirmed to work on the above versions.

BigInt was added to Node.js in v10.4.0 with V8 release v6.7, therefore this package won't work in Node.js versions earlier than v10.4.0.

About

Tiny JS factorial function using BigInt

Resources

License

Stars

Watchers

Forks

Packages

No packages published