Nibbling Pastry Monster


    1.2.4 • Public • Published

    Numbers Logic

    Numbers logic - a set of number tools. Expanding on the work of several packages, for a list please see Dependencies

    Use Cases:

    Data analysis, calculations and other math functions.

    Exploring the number space in an easy to use way.

    Server side or client side number operations

    Includes tools for:

    • Basic calculations
    • Calculus
    • Matrix Operations
    • Prime Numbers
    • Statistics
    • More...

    A few things to note before using: JavaScript, like many languages, does not necessarily manage floating points as well as we'd all like it to.

    For example, if adding decimals, the addition tool won't return the exact value.

    In some functions precautions have been made to account for this, you can set an error bound, Anything in this will be considered an "acceptable outcome." - I plan to expand out the code so this solution covers all cases if I can not find a solution to handle decimals, floats and large numbers in Javascript.

    How to use:

    With node, simply require it:

    const nl = require('numbers-logic');


    Lets start wth some 'prime' examples

    We can check if a number is prime:;

    millerRabin primality check;


    Determines if the given number is prime. Uses a very efficient sieve function, and should be fast. Note: this full prime factorization to determine if the number is prime. You might get a faster result using the miller function below.

    nl.isPrime(7); // Returns true
    nl.isPrime(48); // Returns false

    miller(number), isProbablyPrime(number)

    Uses the determinisic Miller-Rabin Primality Test to determine if the given number is prime. Works for all positive integers less than 341,550,071,728,321.

    nl.miller(17); // Returns true
    nl.miller(284); // Returns false


    Determines the prime factorization for a given integer. For more information see Wikipedia's Integer Factorization entry.

      Returns: [
        {  prime: 2, power: 2 },
        { prime: 3, power: 1 },
        { prime: 11, power: 1 }


    Computes a list of all prime factors for the given integer. Note: while this method fully computes the prime factorization of the integer, it only returns the primes and not the powers of the factorization. For full prime factorization please use factor.

    nl.primeFactors(18); // Returns [2, 3]

    Mersenne Primes




    Safe Prime


    Self Prime


    Prime Power


    Is product of X Primes

    This returns a true/false if the total number of factors that make up said number, equals test. Useful if you want to do a calculation like a Sphenic number with higher dimensions.

    nl.isProductOfXPrimes(number, test);

    eulerPhi(number), totient(number)

    Counts the positive integers less than a given number that are co-prime with the given number. For more information see the Wikipedia entry for Euler's Totient Function.

    nl.eulerPhi(26); // Returns 12

    squareRootModPrime(n, p)

    Uses the Tonelli–Shanks algorithm to determine a single square root in Z mod p.

    nl.squareRootModPrime(100, 19) // Returns 9

    if we wanted to estimate the integral of sin(x) from -2 to 4, we could: Use Riemann integrals (with 200 subdivisions)

    nl.calculus.Riemann(Math.sin, -2, 4, 200);

    Or use adaptive simpson quadrature (with epsilon .0001)

    nl.calculus.adaptiveSimpson(Math.sin, -2, 4, .0001);

    User-defined functions can be used too:

    var myFunc = function(x) {
      return 2*Math.pow(x,2) + 1;
    nl.calculus.Riemann(myFunc, -2, 4, 200);
    nl.calculus.adaptiveSimpson(myFunc, -2, 4, .0001);

    Now say we wanted to run some matrix calculations: We can add two matrices

    var array1 = [0, 1, 2];
    var array2 = [3, 4, 5];
    nl.matrix.addition(array1, array2);

    We can transpose a matrix


    When working with vectors, treat them like single row matrices:

    var vector1 = [[1, 0, 0]];

    The statistics tools include mean, median, mode, standard deviation, random sample generator, correlation, confidence intervals, t-test, chi-square, and more.

    nl.statistic.randomSample(lower, upper, n);
    nl.statistic.correlation(array1, array2);

    For further documentation, check out


    Determines all of the divisors for a given number.

    nl.divisors(6); // Returns [1, 2, 3, 6]


    Uses the Pollard-Rho integer factorization algorithm to quickly find a small divisor of the given number. Note: the divisor found need not be prime (as Pollar-Rho is a general integer factorization algorithm).

    nl.findDivisor(152); // Returns 8

    gcd(a, b)

    Finds the greatest common divisor of two integers a and b.

    nl.gcd(84, 172); // Returns 4

    incMixed(tuple, bases)

    Given a mixed-radix number and the bases for each digit, this determines the increment of the number. For more information, see Wikipedia's entry on Mixed Radix number systems.

    // A number representing a mixed-radix "clock" at 11:59 PM
    var number = [59, 59, 23];
    // The bases for each of the mixed radix digits (60 seconds to a minute,
    // 60 minutes to an hour, 24 hours to a day).
    var base = [60, 60, 24];
    nl.incMixed(number, base); // Returns [0, 0, 0] (or midnight the next day)

    inverseMod(a, m)

    Given an integer this function computes the modular multiplicative inverse to the given modulo.

    nl.inverseMod(14, 17); // Returns 11


    Given an integer, returns a Boolean indicating whether it's an abundant number.

    nl.isAbundant(36); // Returns true
    nl.isAbundant(35); // Returns false


    Given an integer, returns a Boolean indicating whether it's a deficient number.

    nl.isDeficient(15); // Returns true
    nl.isDeficient(12); // Returns false


    Given an integer, returns a Boolean indicating whether it's a heptagonal number.

    nl.isHeptagonal(112); // Returns true
    nl.isHeptagonal(175); // Returns false


    Given an integer, returns a Boolean indicating whether it's a hexagonal number.

    nl.isHexagonal(190); // Returns true
    nl.isHexagonal(50); // Returns false


    Given an integer, returns a Boolean indicating whether it's an octagonal number.

    nl.isOctagonal(65); // Returns true
    nl.isOctagonal(50); // Returns false


    Given an integer, returns a Boolean indicating whether it's a pentagonal number.

    nl.isPentagonal(92); // Returns true
    nl.isPentagona(50); // Returns false


    Given an integer, returns a Boolean indicating whether it's a perfect number.

    nl.isPerfect(496); // Returns true
    nl.isPerfect(200); // Returns false


    Given an integer, returns a Boolean indicating whether it's a square number.

    nl.isSquare(16); // Returns true
    nl.isSquare(55); // Returns false


    Given an integer, returns a Boolean indicating whether it's a triangular number.

    nl.isTriangular(21); // Returns true
    nl.isTriangular(25); // Returns false

    jacobiSymbol(a, b)

    Computes the Jacobi Symbol for the given numbers.

    nl.jacobiSymbol(928, 33); // returns 1

    lcm(a, b)

    Finds the least common multiple of two integers a and b.

    nl.lcm(4, 3); // Returns 12

    logMod(a, b, m)

    Solves a discrete logarithm. For more information see the following:


    Compute the value of the Möbius function for n using naive factorization. The Möbius function is defined as 1 if n is a square-free integer with an even number of prime factors, -1 if square-free with an odd number of prime factors, and 0 if n has a squared prime factor.

    nl.mobius(30); // Returns -1

    mobiusRange(n1, n2[, primalityTest = miller])

    Compute the value of the Möbius function for integers from n1 to n2 - 1 (inclusive) using a sieve method. Compared to mobius, this method still effectively factors each integer but is somewhat more efficient than factoring and computing each value individually. Numbers less than min(n1, sqrt(n2)) cannot be sieved implicitly during computation, so an explicit primality test must be performed. By default, the deterministic Miller-Rabin primality test is used, but any boolean primality test may optionally be provided.

    nl.mobiusRange(1000000, 1000005); // Returns [0, 1, -1, -1, 0]

    multiplyMod(a, b, m)

    Multiplies the two given numbers mod the given modulus. See Wikipedia's entry on Modular Arithmetic.

    nl.multiplyMod(928, 284, 18); // Returns 14

    powerMod(base, exponent, mod)

    Computes the power of a base mod the given modulus. For more information see Wikipedia's entry on Modular Exponentiation.

    nl.powerMod(567283, 2843, 776); // Returns 299


    Computes the smallest primitive root for Z mod n, meaning a multiplicative generator for the group of units of Z mod n. For more information see Wikipedia's entry on Primitive roots modulo n.

    nl.primitiveRoot(1043); // Returns 7


    Computes a quadratic nonresidue for the given number. For more information see Wikipedia's entry for Quadratic Residues.

    nl.quadraticNonresidue(777); // Returns 5


    Find a random primitive root for Z mod n, meaning a multiplicative generator for the group of units of Z mod n. Unlike primitiveRoot, this function returns a random primitive root. For more information see Wikipedia's entry on Primitive roots modulo n.


    Determines a list of prime numbers up to the given number by performing the Sieve of Eratosthenes. Supports: Very large numbers upto Number.MAX_SAFE_INTEGER (Function is able to go much further, but that's a limitation of JS native Number)

    nl.sieve(10); // Returns [ 2, 3, 5, 7 ]

    squareRootMod(n, m)

    Determines all square roots of a given number modulo the given modulus. For more information see Wikipedia's entry on Quadratic Residues.

    nl.squareRootMod(1023, 77); // Returns [76, 1]

    Centered Hexagonal

    In mathematics and combinatorics, a centered hexagonal number, or hex number,[1][2] is a centered figurate number that represents a hexagon with a dot in the center and all other dots surrounding the center dot in a hexagonal lattice.

    // Is number in sequence of Centered Hexagonal numbers? True/False
    // Gets the n-th element from the sequence of Centered Hexagonal numbers
    nl.getCenteredHexagonal(1); // returns 1
    nl.getCenteredHexagonal(2); // returns 7
    nl.getCenteredHexagonal(3); // returns 19

    Star Number

    A star number is a centered figurate number a centered hexagram (six-pointed star), such as the Star of David, or the board Chinese checkers is played on.

    // Is number in sequence of star numbers? True/False
    // Gets the n-th element from the sequence of star numbers
    nl.getStar(1); // returns 1
    nl.getStar(2); // returns 13
    nl.getStar(3); // returns 37

    Tetrahedral Numbers

    A tetrahedral number, or triangular pyramidal number, is a figurate number that represents a pyramid with a triangular base and three sides, called a tetrahedron.

    // Is number in squence of tetrahedral numbers? True/False
    // Gets the n-th element from the sequence of tetrahedral numbers
    nl.getTetrahedral(1); // returns 1
    nl.getTetrahedral(2); // returns 4
    nl.getTetrahedral(3); // returns 10

    Polite, Impolite and Politeness

    In number theory, a polite number is a positive integer that can be written as the sum of two or more consecutive positive integers. A positive integer which is not polite is called impolite. The impolite numbers are exactly the powers of two, and the polite numbers are the natural numbers that are not powers of two.

    Polite numbers have also been called staircase numbers because the Young diagrams which represent graphically the partitions of a polite number into consecutive integers (in the French notation of drawing these diagrams) resemble staircases.


    (EVIL numbers)[]

    In number theory, an evil number is a non-negative integer that has an even number of 1s in its binary expansion. These numbers give the positions of the zero values in the Thue–Morse sequence, and for this reason they have also been called the Thue–Morse set. Non-negative integers that are not evil are called odious numbers.


    (Happy numbers)[}

    A happy number is a number which eventually reaches 1 when replaced by the sum of the square of each digit. Sad numbers never reach 1, instead eventually entering a loop.


    Powers of 2

    Power of two is a number of the form 2n where n is an integer, that is, the result of exponentiation with number two as the base and integer n as the exponent.


    Arithmetic numbers

    In number theory, an arithmetic number is an integer for which the average of its positive divisors is also an integer ...


    Natural Numbers

    These are the numbers we use for counting, like 0, 1, 2, 3, 4... Some definitions, including the standard ISO 80000-2, begin the natural numbers with 0, corresponding to the non-negative integers 0, 1, 2, 3, ..., whereas others start with 1, corresponding to the positive integers 1, 2, 3...

    We have elected to follow ISO standards, and begin this range from 0. You can alternately use isWhole which begins from 1.


    Pronic numbers

    A pronic number is a number which is the product of two consecutive integers, that is, a number of the form n(n + 1). The study of these numbers dates back to Aristotle. They are also called oblong numbers, heteromecic numbers, or rectangular numbers; however, the term "rectangular number" has also been applied to the composite numbers.


    Smooth or Friable numbers

    In number theory, an n-smooth (or n-friable) number is an integer whose prime factors are all less than or equal to n. For example, a 7-smooth number is a number whose every prime factor is at most 7, so 49 = 72 and 15750 = 2 × 32 × 53 × 7 are both 7-smooth, while 11 and 702 = 2 × 33 × 13 are not 7-smooth. The term seems to have been coined by Leonard Adleman. Smooth numbers are especially important in cryptography, which relies on factorization of integers. The 2-smooth numbers are just the powers of 2, while 5-smooth numbers are known as regular numbers.


    Rough numbers

    A k-rough number, as defined by Finch in 2001 and 2003, is a positive integer whose prime factors are all greater than or equal to k. k-roughness has alternately been defined as requiring all prime factors to strictly exceed k


    Round numbers

    A round number is an integer that ends with one or more "0"s (zero-digit) in a given base.[1] So, 590 is rounder than 592, but 590 is less round than 600.

    nl.isRound(n, base);
    // Want to know if one number is more smooth than another?
    // Want to compare if numbers are smoother in one base than another?
    nl.isMoreRound(n1, n2, base1, base2);

    Sphenic numbers

    In number theory, a sphenic number is a positive integer that is the product of three distinct prime numbers.


    Practical or Panarithmic numbers

    In number theory, a practical number or panarithmic number is a positive integer n such that all smaller positive integers can be represented as sums of distinct divisors of n.


    Semiperfect numbers

    In number theory, a semiperfect number or pseudoperfect number is a natural number n that is equal to the sum of all or some of its proper divisors. A semiperfect number that is equal to the sum of all its proper divisors is a perfect number.


    Self numbers

    A self number, Colombian number or Devlali number in a given number base b is a natural number that cannot be written as the sum of any other natural number n and the individual digits of n.

    nl.isSelf(n, base); // IMPORTANT: Currently only works in base 10

    Untouchable Number

    An untouchable number is a positive integer that cannot be expressed as the sum of all the proper divisors of any positive integer (including the untouchable number itself). That is, these numbers are not in the image of the aliquot sum function.


    Weird numbers

    The sum of the proper divisors (divisors including 1 but not itself) of the number is greater than the number, but no subset of those divisors sums to the number itself.


    Unusual numbers

    Read the wiki article, it's foramtted to display this information better than I can do here. All prime numbers are unusual.


    Integer Root

    Tests if the number has a degree of root that returns a whole number result. For instance, { 9^(1/3) = 3 } || cuberoot(9)

    nl.hasIntRoot(n);  // returns if a number has a whole root true/false
    nl.getIntRoot(n); // returns the root `degree` that wholy roots the number
    nl.getIntRoot(n); // returns 3


    For the full license please read the full

    License cliff notes:

    Permission is hereby granted, free of charge, to any natural person obtaining a copy of this software and associated documentation files (the "Software"), to use or distribute copies of the Software, subject to the following conditions

    You are required to release the source code of any program that you distribute that uses "Numbers Logic".


    The dependencies of this project carry their own licenses

    We have done our best to make sure that we build ontop of open source un-restricted licenses, but it is your responsability to make sure you comply with the licenses of dependencies, and you agree to indemnify us against any usage by you.


    Contributions of Code are welcome, however:

    This project uses a custom license, it is not "OSS". If you would like to contribute Open Source code, you may want to consider contributing it to one of the dependencies of this project (Depending if your new code is applicable to their project or not). Alternatively you may wish to publish your own package and notify us, we will assess it for suitability, and include it if we deem it fit for purpose and in the interest of the project to do so. The License you publish your works under will also impact if we can or can not include it in our own.

    Alternately you can contact the Copyright holder (Details are available in the License)[]

    More documentation and help can be found at:

    If you can't find something documented here, you're probably going to want to check out the packages I have derived functions from. Check the Dependencies of this project

    For numbers documentation, check out

    For number-theory check out their NPM page

    This project stands on the shoulders of giants:

    In no particular order:



    npm i numbers-logic

    DownloadsWeekly Downloads






    Unpacked Size

    121 kB

    Total Files


    Last publish


    • tolmera