UNPKG

@lucadani7/algonodejs-for-beginners

Version:

Just a simple Node.js package with some basic algorithms perfect for people just starting out. It's got easy-to-understand TypeScript versions of stuff like sorting, searching, math with numbers, and messing with strings.

78 lines (77 loc) 2.24 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.PrimalityChecker = void 0; class PrimalityChecker { static randomBase(start, end) { const mini = BigInt(Math.min(Number(start), Number(end))); const maxi = BigInt(Math.max(Number(start), Number(end))); const range = maxi - mini + 1n; let bits = range.toString(2).length; let result; do { result = 0n; for (let i = 0; i < bits; ++i) { if (Math.random() < 0.5) { result |= (1n << BigInt(i)); } } } while (result >= range); return result + mini; } static fastExp(a, b, m) { let result = 1n; for (; b !== 0n; b >>= 1n) { result = (b & 1n) > 0 ? ((result * a) % m) : result; a = (a * a) % m; } return result; } static millerRabinTest(d, value) { let a = this.randomBase(2n, value - 2n); let x = this.fastExp(a, d, value); if (x === 1n || x === value - 1n) { return true; } while (d !== value - 1n) { x = (x * x) % value; d *= 2n; if (x === 1n) { return false; } if (x === value - 1n) { return true; } } return false; } static valueIsPrime(value, trialsCount) { if (value < 4n) { return value > 1n; } let d = value - 1n; for (; d % 2 === 0n; d >>= 1n) ; for (let i = 0; i < trialsCount; ++i) { if (!this.millerRabinTest(d, value)) { return false; } } return true; } static nextPrime(value, trialsCount) { do { value += 1n; } while (!this.valueIsPrime(value, trialsCount)); return value; } static previousPrime(value, trialsCount) { do { if (value <= 2n) { return null; } value -= 1n; } while (!this.valueIsPrime(value, trialsCount)); return value; } } exports.PrimalityChecker = PrimalityChecker;