Skip to content

Commit

Permalink
Helper math library added for bigint operations
Browse files Browse the repository at this point in the history
  • Loading branch information
Gonzalo Diaz committed Sep 27, 2024
1 parent 9af81b3 commit b11f02a
Showing 1 changed file with 81 additions and 0 deletions.
81 changes: 81 additions & 0 deletions src/hackerrank/lib/BigIntMath.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
/* istanbul ignore file */

export class BigIntMath {
static max(...values: bigint[]): bigint | null {
if (values.length === 0) {
return null;
}

if (values.length === 1) {
return values[0];
}

let max = values[0];
for (let i = 1; i < values.length; i++) {
if (values[i] > max) {
max = values[i];
}
}
return max;
}

static min(...values: bigint[]): bigint | null {
if (values.length === 0) {
return null;
}

if (values.length === 1) {
return values[0];
}

let min = values[0];
for (let i = 1; i < values.length; i++) {
if (values[i] < min) {
min = values[i];
}
}
return min;
}

static sign(value: bigint): bigint {
if (value > 0n) {
return 1n;
}
if (value < 0n) {
return -1n;
}
return 0n;
}

static abs(value: bigint): bigint {
if (this.sign(value) === -1n) {
return -value;
}
return value;
}

// https://stackoverflow.com/questions/53683995/javascript-big-integer-square-root/58863398#58863398
static rootNth(value: bigint, k = 2n): bigint {
if (value < 0n) {
throw Error('negative number is not supported');
}

let o = 0n;
let x = value;
let limit = 100;

while (x ** k !== k && x !== o && limit > 0) {
limit -= 1;
o = x;
x = ((k - 1n) * x + value / x ** (k - 1n)) / k;
}

return x;
}

static sqrt(value: bigint): bigint {
return BigIntMath.rootNth(value);
}
}

export default { BigIntMath };

0 comments on commit b11f02a

Please sign in to comment.