File tree Expand file tree Collapse file tree 1 file changed +81
-0
lines changed Expand file tree Collapse file tree 1 file changed +81
-0
lines changed Original file line number Diff line number Diff line change
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 } ;
You can’t perform that action at this time.
0 commit comments