@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.
48 lines (47 loc) • 1.41 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.FibonacciAlgorithms = void 0;
class FibonacciAlgorithms {
static fibo(value) {
const memo = new Array(Number(value + 1n)).fill(undefined);
return this.fiboMemo(value, memo);
}
static fiboMemo(value, memo) {
if (value === 0n || value === 1n) {
return value;
}
if (memo[value] !== undefined) {
return memo[value];
}
return this.fiboMemo(value - 2n, memo) + this.fiboMemo(value - 1n, memo);
}
static isFiboElem(value) {
if (value < 0n) {
return false;
}
if (value === 0n || value === 1n) {
return true;
}
const value1 = 5 * value * value + 4;
const sqrt1 = this.sqrtBigInt(value1);
const value2 = 5 * value * value - 4;
const sqrt2 = this.sqrtBigInt(value2);
return sqrt1 * sqrt1 === value1 || sqrt2 * sqrt2 === value2;
}
static sqrtBigInt(val) {
if (val < 0n) {
throw new Error("Value must be 0n or greater!");
}
if (val < 2n) {
return val;
}
let x = val;
let y = (x + 1n) >> 1n;
while (y < x) {
x = y;
y = (x + val / x) >> 1n;
}
return x;
}
}
exports.FibonacciAlgorithms = FibonacciAlgorithms;