Skip to content

Commit b11f02a

Browse files
author
Gonzalo Diaz
committed
Helper math library added for bigint operations
https://golb.hplar.ch/2018/09/javascript-bigint.html#math
1 parent 9af81b3 commit b11f02a

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed

src/hackerrank/lib/BigIntMath.ts

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
/* istanbul ignore file */
2+
3+
export class BigIntMath {
4+
static max(...values: bigint[]): bigint | null {
5+
if (values.length === 0) {
6+
return null;
7+
}
8+
9+
if (values.length === 1) {
10+
return values[0];
11+
}
12+
13+
let max = values[0];
14+
for (let i = 1; i < values.length; i++) {
15+
if (values[i] > max) {
16+
max = values[i];
17+
}
18+
}
19+
return max;
20+
}
21+
22+
static min(...values: bigint[]): bigint | null {
23+
if (values.length === 0) {
24+
return null;
25+
}
26+
27+
if (values.length === 1) {
28+
return values[0];
29+
}
30+
31+
let min = values[0];
32+
for (let i = 1; i < values.length; i++) {
33+
if (values[i] < min) {
34+
min = values[i];
35+
}
36+
}
37+
return min;
38+
}
39+
40+
static sign(value: bigint): bigint {
41+
if (value > 0n) {
42+
return 1n;
43+
}
44+
if (value < 0n) {
45+
return -1n;
46+
}
47+
return 0n;
48+
}
49+
50+
static abs(value: bigint): bigint {
51+
if (this.sign(value) === -1n) {
52+
return -value;
53+
}
54+
return value;
55+
}
56+
57+
// https://stackoverflow.com/questions/53683995/javascript-big-integer-square-root/58863398#58863398
58+
static rootNth(value: bigint, k = 2n): bigint {
59+
if (value < 0n) {
60+
throw Error('negative number is not supported');
61+
}
62+
63+
let o = 0n;
64+
let x = value;
65+
let limit = 100;
66+
67+
while (x ** k !== k && x !== o && limit > 0) {
68+
limit -= 1;
69+
o = x;
70+
x = ((k - 1n) * x + value / x ** (k - 1n)) / k;
71+
}
72+
73+
return x;
74+
}
75+
76+
static sqrt(value: bigint): bigint {
77+
return BigIntMath.rootNth(value);
78+
}
79+
}
80+
81+
export default { BigIntMath };

0 commit comments

Comments
 (0)