-
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Helper math library added for bigint operations
- Loading branch information
Gonzalo Diaz
committed
Sep 27, 2024
1 parent
9af81b3
commit b11f02a
Showing
1 changed file
with
81 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 }; |