Math utilities for numberscope
The primary resource for doing math inside the frontscope code is the
mathjs package, which this repository depends on.
The shared/math
module of Numberscope provides some additional utilities
aimed at making common mathematical operations more convenient, especially
when working with bigints.
Note that currently every one of these functions accepts either
number
or bigint
inputs for all arguments and simply converts them
to bigints.
Example usage
import {
safeNumber,
floorSqrt,
modulo,
powmod,
natlog
} from '../shared/math'
try {
const myNumber = safeNumber(9007199254740992n)
} catch (err: unknown) {
console.log('This will always be logged')
}
try {
const myNumber = safeNumber(9007n)
} catch (err: unknown) {
console.log('This will never be logged and myNumber will be 9007')
}
const five: bigint = floorSqrt(30n)
const negativeTwo: bigint = floorSqrt(-2n)
const three: bigint = modulo(-7n, 5)
const two: bigint = modulo(7, 5n)
const six: bigint = powmod(6, 2401n, 7n)
// n to the p is congruent to n mod a prime p,
// so a to any power of p is as well.
const fortysixish: number = natlog(100000000000000000000n)
const seven: bigint = bigabs(-7n)
Detailed function reference
safeNumber(n: number | bigint): number
Returns the number
mathematically equal to n if there is one, or
throws an error otherwise.
floorSqrt(n: number | bigint): bigint
Returns the largest bigint r such that the square of r is less than or equal to n, if there is one; otherwise returns the bigint mathematically equal to n. (Thus, it leaves negative bigints unchanged.)
modulo(n: number | bigint, modulus: number | bigint): bigint
Returns the smallest nonnegative bigint congruent to n modulo
modulus; this is also the remainder upon dividing n by modulus. Note
that this is the "mathematician's modulus" that never returns a negative
value, unlike the built-in JavaScript %
operator.
Throws a RangeError if modulus is nonpositive.
powmod(n, exponent, modulus): bigint
All parameters have type number | bigint
. If modulus is nonpositive,
throws a RangeError.
Otherwise, if exponent is positive, returns the smallest nonnegative bigint
congruent to n raised to the exponent power modulo modulus (but far more
efficiently than computing modulo(n**exponent, modulus)
).
If exponent is negative, first computes i = powmod(n, -exponent, modulus)
.
If i has a multiplicative inverse modulo modulus, returns that inverse,
otherwise throws a RangeError.
natlog(n: number | bigint): number
Returns the natural log of the input.
bigabs(n: bigint): bigint
returns the absolute value of a bigint