@obinexusmk2/hypernum 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +256 -0
  3. package/dist/index.cjs +3425 -0
  4. package/dist/index.cjs.map +1 -0
  5. package/dist/index.d.ts +1449 -0
  6. package/dist/index.js +3284 -0
  7. package/dist/index.js.map +1 -0
  8. package/dist/index.umd.js +8 -0
  9. package/dist/index.umd.js.map +1 -0
  10. package/dist/types/config/config-loader.d.ts +56 -0
  11. package/dist/types/config/config-loader.d.ts.map +1 -0
  12. package/dist/types/config/config-parser.d.ts +28 -0
  13. package/dist/types/config/config-parser.d.ts.map +1 -0
  14. package/dist/types/config/config-resolver.d.ts +21 -0
  15. package/dist/types/config/config-resolver.d.ts.map +1 -0
  16. package/dist/types/config/config-source.d.ts +27 -0
  17. package/dist/types/config/config-source.d.ts.map +1 -0
  18. package/dist/types/config/index.d.ts +68 -0
  19. package/dist/types/config/index.d.ts.map +1 -0
  20. package/dist/types/core/common.d.ts +169 -0
  21. package/dist/types/core/common.d.ts.map +1 -0
  22. package/dist/types/core/config.d.ts +197 -0
  23. package/dist/types/core/config.d.ts.map +1 -0
  24. package/dist/types/core/constants.d.ts +88 -0
  25. package/dist/types/core/constants.d.ts.map +1 -0
  26. package/dist/types/core/errors.d.ts +97 -0
  27. package/dist/types/core/errors.d.ts.map +1 -0
  28. package/dist/types/core/hypernum.d.ts +60 -0
  29. package/dist/types/core/hypernum.d.ts.map +1 -0
  30. package/dist/types/core/index.d.ts +6 -0
  31. package/dist/types/core/index.d.ts.map +1 -0
  32. package/dist/types/index.d.ts +33 -0
  33. package/dist/types/index.d.ts.map +1 -0
  34. package/dist/types/operations/arithmetic.d.ts +72 -0
  35. package/dist/types/operations/arithmetic.d.ts.map +1 -0
  36. package/dist/types/operations/bitwise.d.ts +98 -0
  37. package/dist/types/operations/bitwise.d.ts.map +1 -0
  38. package/dist/types/operations/comparison.d.ts +94 -0
  39. package/dist/types/operations/comparison.d.ts.map +1 -0
  40. package/dist/types/operations/conversion.d.ts +79 -0
  41. package/dist/types/operations/conversion.d.ts.map +1 -0
  42. package/dist/types/operations/factorial.d.ts +58 -0
  43. package/dist/types/operations/factorial.d.ts.map +1 -0
  44. package/dist/types/operations/index.d.ts +6 -0
  45. package/dist/types/operations/index.d.ts.map +1 -0
  46. package/dist/types/operations/power.d.ts +49 -0
  47. package/dist/types/operations/power.d.ts.map +1 -0
  48. package/dist/types/storage/Heap.d.ts +95 -0
  49. package/dist/types/storage/Heap.d.ts.map +1 -0
  50. package/dist/types/storage/index.d.ts +2 -0
  51. package/dist/types/storage/index.d.ts.map +1 -0
  52. package/dist/types/structures/ackermann.d.ts +74 -0
  53. package/dist/types/structures/ackermann.d.ts.map +1 -0
  54. package/dist/types/structures/big-array.d.ts +102 -0
  55. package/dist/types/structures/big-array.d.ts.map +1 -0
  56. package/dist/types/structures/index.d.ts +5 -0
  57. package/dist/types/structures/index.d.ts.map +1 -0
  58. package/dist/types/structures/number-tree.d.ts +114 -0
  59. package/dist/types/structures/number-tree.d.ts.map +1 -0
  60. package/dist/types/structures/power-tower.d.ts +74 -0
  61. package/dist/types/structures/power-tower.d.ts.map +1 -0
  62. package/dist/types/utils/formatting.d.ts +45 -0
  63. package/dist/types/utils/formatting.d.ts.map +1 -0
  64. package/dist/types/utils/index.d.ts +5 -0
  65. package/dist/types/utils/index.d.ts.map +1 -0
  66. package/dist/types/utils/parser.d.ts +39 -0
  67. package/dist/types/utils/parser.d.ts.map +1 -0
  68. package/dist/types/utils/precision.d.ts +57 -0
  69. package/dist/types/utils/precision.d.ts.map +1 -0
  70. package/dist/types/utils/validation.d.ts +28 -0
  71. package/dist/types/utils/validation.d.ts.map +1 -0
  72. package/package.json +164 -0
  73. package/rollup.config.js +162 -0
  74. package/src/config/config-loader.ts +226 -0
  75. package/src/config/config-parser.ts +161 -0
  76. package/src/config/config-resolver.ts +52 -0
  77. package/src/config/config-source.ts +32 -0
  78. package/src/config/index.ts +159 -0
  79. package/src/core/common.ts +185 -0
  80. package/src/core/config.ts +393 -0
  81. package/src/core/constants.ts +102 -0
  82. package/src/core/errors.ts +203 -0
  83. package/src/core/hypernum.ts +241 -0
  84. package/src/core/index.ts +5 -0
  85. package/src/index.ts +183 -0
  86. package/src/operations/arithmetic.ts +333 -0
  87. package/src/operations/bitwise.ts +367 -0
  88. package/src/operations/comparison.ts +272 -0
  89. package/src/operations/conversion.ts +400 -0
  90. package/src/operations/factorial.ts +279 -0
  91. package/src/operations/index.ts +5 -0
  92. package/src/operations/power.ts +316 -0
  93. package/src/storage/Heap.ts +238 -0
  94. package/src/storage/index.ts +1 -0
  95. package/src/structures/ackermann.ts +233 -0
  96. package/src/structures/big-array.ts +306 -0
  97. package/src/structures/index.ts +4 -0
  98. package/src/structures/number-tree.ts +404 -0
  99. package/src/structures/power-tower.ts +278 -0
  100. package/src/types/common.d.ts +357 -0
  101. package/src/types/core.d.ts +161 -0
  102. package/src/types/index.d.ts +2 -0
  103. package/src/utils/formatting.ts +246 -0
  104. package/src/utils/index.ts +4 -0
  105. package/src/utils/parser.ts +245 -0
  106. package/src/utils/precision.ts +217 -0
  107. package/src/utils/validation.ts +183 -0
  108. package/tsconfig.json +84 -0
package/dist/index.cjs ADDED
@@ -0,0 +1,3425 @@
1
+ /**
2
+ * @obinexusmk2/hypernum v0.1.0
3
+ * Precison at Scale
4
+ *A high-precision mathematics library for large number operations with BigInt support, custom data structures, and comprehensive type safety
5
+ * @license ISC
6
+ */
7
+ 'use strict';
8
+
9
+ Object.defineProperty(exports, '__esModule', { value: true });
10
+
11
+ var path = require('path');
12
+ var url = require('url');
13
+ var fs = require('fs');
14
+
15
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
16
+ /**
17
+ * Validation utilities for Hypernum library
18
+ * Provides type checking and validation functions for large number operations
19
+ */
20
+ // Custom error types for validation
21
+ let ValidationError$1 = class ValidationError extends Error {
22
+ constructor(message) {
23
+ super(message);
24
+ this.name = 'ValidationError';
25
+ }
26
+ };
27
+ class OverflowError extends Error {
28
+ constructor(message) {
29
+ super(message);
30
+ this.name = 'OverflowError';
31
+ }
32
+ }
33
+ // Type guards
34
+ const isBigInt = (value) => {
35
+ return typeof value === 'bigint';
36
+ };
37
+ const isValidNumberString = (value) => {
38
+ return /^-?\d+$/.test(value);
39
+ };
40
+ const isValidNumber = (value) => {
41
+ return typeof value === 'number' && !isNaN(value) && isFinite(value);
42
+ };
43
+ // Type conversions with validation
44
+ const toBigInt = (value) => {
45
+ if (isBigInt(value)) {
46
+ return value;
47
+ }
48
+ if (typeof value === 'string') {
49
+ if (!isValidNumberString(value)) {
50
+ throw new ValidationError$1(`Invalid number string: ${value}`);
51
+ }
52
+ return BigInt(value);
53
+ }
54
+ if (isValidNumber(value)) {
55
+ if (!Number.isInteger(value)) {
56
+ throw new ValidationError$1('Cannot convert non-integer number to BigInt');
57
+ }
58
+ return BigInt(value);
59
+ }
60
+ throw new ValidationError$1(`Cannot convert ${typeof value} to BigInt`);
61
+ };
62
+ // Operation safety checks
63
+ const checkAdditionOverflow = (a, b) => {
64
+ // Check if addition would overflow
65
+ if (b > 0 && a > BigInt(Number.MAX_SAFE_INTEGER) - b) {
66
+ throw new OverflowError('Addition would overflow');
67
+ }
68
+ if (b < 0 && a < BigInt(Number.MIN_SAFE_INTEGER) - b) {
69
+ throw new OverflowError('Addition would underflow');
70
+ }
71
+ };
72
+ const checkMultiplicationOverflow = (a, b) => {
73
+ // Check if multiplication would overflow
74
+ if (a !== BigInt(0) && b !== BigInt(0)) {
75
+ const maxValue = BigInt(Number.MAX_SAFE_INTEGER);
76
+ const minValue = BigInt(Number.MIN_SAFE_INTEGER);
77
+ if (a > maxValue / b || a < minValue / b) {
78
+ throw new OverflowError('Multiplication would overflow');
79
+ }
80
+ }
81
+ };
82
+ const checkPowerOverflow = (base, exponent) => {
83
+ // Basic overflow checks for exponentiation
84
+ if (exponent < BigInt(0)) {
85
+ throw new ValidationError$1('Negative exponents not supported for integers');
86
+ }
87
+ if (base === BigInt(0) && exponent === BigInt(0)) {
88
+ throw new ValidationError$1('Zero raised to zero is undefined');
89
+ }
90
+ if (exponent > BigInt(1000)) {
91
+ throw new OverflowError('Exponent too large, computation would overflow');
92
+ }
93
+ };
94
+ const validatePositive = (value) => {
95
+ if (value <= BigInt(0)) {
96
+ throw new ValidationError$1('Value must be positive');
97
+ }
98
+ };
99
+ const validateNonNegative = (value) => {
100
+ if (value < BigInt(0)) {
101
+ throw new ValidationError$1('Value must be non-negative');
102
+ }
103
+ };
104
+
105
+ /**
106
+ * Precision utilities for Hypernum library
107
+ * Provides functions for handling decimal precision and rounding operations
108
+ */
109
+ /**
110
+ * Rounding modes for decimal operations
111
+ */
112
+ exports.RoundingMode = void 0;
113
+ (function (RoundingMode) {
114
+ RoundingMode["FLOOR"] = "FLOOR";
115
+ RoundingMode["CEIL"] = "CEIL";
116
+ RoundingMode["DOWN"] = "DOWN";
117
+ RoundingMode["UP"] = "UP";
118
+ RoundingMode["HALF_EVEN"] = "HALF_EVEN";
119
+ RoundingMode["HALF_UP"] = "HALF_UP";
120
+ RoundingMode["HALF_DOWN"] = "HALF_DOWN";
121
+ })(exports.RoundingMode || (exports.RoundingMode = {}));
122
+ /**
123
+ * Scale a bigint by a power of 10
124
+ */
125
+ const scaleByPowerOfTen = (value, power) => {
126
+ if (power === 0)
127
+ return value;
128
+ if (power > 0) {
129
+ return value * (BigInt(10) ** BigInt(power));
130
+ }
131
+ return value / (BigInt(10) ** BigInt(-power));
132
+ };
133
+ /**
134
+ * Round a number according to specified mode and precision
135
+ */
136
+ const round = (value, precision = 0, mode = exports.RoundingMode.HALF_EVEN) => {
137
+ if (precision < 0) {
138
+ throw new ValidationError$1('Precision must be non-negative');
139
+ }
140
+ if (precision === 0) {
141
+ return value;
142
+ }
143
+ const scale = BigInt(10) ** BigInt(precision);
144
+ const scaled = value / scale;
145
+ const remainder = value % scale;
146
+ switch (mode) {
147
+ case exports.RoundingMode.FLOOR:
148
+ return scaled * scale;
149
+ case exports.RoundingMode.CEIL:
150
+ return remainder > 0n ? (scaled + 1n) * scale : scaled * scale;
151
+ case exports.RoundingMode.DOWN:
152
+ return value >= 0n ? scaled * scale : (scaled - 1n) * scale;
153
+ case exports.RoundingMode.UP:
154
+ return value >= 0n ? (scaled + 1n) * scale : scaled * scale;
155
+ case exports.RoundingMode.HALF_UP:
156
+ return remainder >= scale / 2n ? (scaled + 1n) * scale : scaled * scale;
157
+ case exports.RoundingMode.HALF_DOWN:
158
+ return remainder > scale / 2n ? (scaled + 1n) * scale : scaled * scale;
159
+ case exports.RoundingMode.HALF_EVEN:
160
+ if (remainder === scale / 2n) {
161
+ return scaled % 2n === 0n ? scaled * scale : (scaled + 1n) * scale;
162
+ }
163
+ return remainder > scale / 2n ? (scaled + 1n) * scale : scaled * scale;
164
+ default:
165
+ throw new ValidationError$1('Invalid rounding mode');
166
+ }
167
+ };
168
+ /**
169
+ * Normalize two numbers to the same precision
170
+ */
171
+ const normalizePrecision = (a, b, precisionA, precisionB) => {
172
+ const targetPrecision = Math.max(precisionA, precisionB);
173
+ const scaledA = scaleByPowerOfTen(a, targetPrecision - precisionA);
174
+ const scaledB = scaleByPowerOfTen(b, targetPrecision - precisionB);
175
+ return [scaledA, scaledB];
176
+ };
177
+ /**
178
+ * Scale a division operation to achieve desired precision
179
+ */
180
+ const scaledDivision = (numerator, denominator, precision, roundingMode = exports.RoundingMode.HALF_EVEN) => {
181
+ if (denominator === 0n) {
182
+ throw new ValidationError$1('Division by zero');
183
+ }
184
+ if (precision < 0) {
185
+ throw new ValidationError$1('Precision must be non-negative');
186
+ }
187
+ // Scale up numerator to handle desired precision
188
+ const scaledNumerator = scaleByPowerOfTen(numerator, precision);
189
+ const quotient = scaledNumerator / denominator;
190
+ return round(quotient, 0, roundingMode);
191
+ };
192
+
193
+ /**
194
+ * Configuration type definitions for Hypernum library
195
+ * Defines all configuration options and their default values
196
+ */
197
+ /**
198
+ * Converts FullConfig to BasicConfig if necessary
199
+ */
200
+ function convertToBasicConfig(config) {
201
+ if (isBasicConfig(config)) {
202
+ return config;
203
+ }
204
+ return {
205
+ precision: config.arithmetic.defaultPrecision,
206
+ roundingMode: config.arithmetic.defaultRoundingMode,
207
+ checkOverflow: config.arithmetic.checkOverflow,
208
+ maxSteps: config.arithmetic.maxComputationSteps,
209
+ debug: config.debug.verbose
210
+ };
211
+ }
212
+ /**
213
+ * Default configuration values for basic config
214
+ */
215
+ const DEFAULT_BASIC_CONFIG = {
216
+ precision: 0,
217
+ roundingMode: exports.RoundingMode.HALF_EVEN,
218
+ checkOverflow: true,
219
+ maxSteps: 1000,
220
+ debug: false
221
+ };
222
+ /**
223
+ * Full default configuration values
224
+ */
225
+ const DEFAULT_FULL_CONFIG = {
226
+ arithmetic: {
227
+ defaultPrecision: 0,
228
+ defaultRoundingMode: exports.RoundingMode.HALF_EVEN,
229
+ checkOverflow: true,
230
+ maxComputationSteps: 1000,
231
+ autoPrecision: {
232
+ enabled: true,
233
+ maxPrecision: 100,
234
+ minPrecision: 0
235
+ },
236
+ constants: {
237
+ precision: 50,
238
+ cache: true,
239
+ algorithm: 'series'
240
+ }
241
+ },
242
+ dataStructures: {
243
+ array: {
244
+ initialCapacity: 16,
245
+ growthFactor: 2,
246
+ maxSize: 1000000
247
+ },
248
+ tree: {
249
+ maxDepth: 1000,
250
+ autoBalance: true,
251
+ nodeLimit: 1000000
252
+ },
253
+ heap: {
254
+ initialCapacity: 16,
255
+ growthPolicy: 'double',
256
+ validatePropertyOnOperation: true
257
+ },
258
+ cache: {
259
+ enabled: true,
260
+ maxSize: 1000,
261
+ ttl: 3600000, // 1 hour
262
+ evictionPolicy: 'LRU',
263
+ persistToDisk: false,
264
+ compressionEnabled: false
265
+ }
266
+ },
267
+ formatting: {
268
+ notation: 'standard',
269
+ precision: 0,
270
+ grouping: true,
271
+ groupSize: 3,
272
+ decimalSeparator: '.',
273
+ groupSeparator: ',',
274
+ uppercase: false,
275
+ scientific: {
276
+ minExponent: 6,
277
+ maxSignificantDigits: 6,
278
+ exponentSeparator: 'e'
279
+ },
280
+ engineering: {
281
+ useSIPrefixes: true
282
+ },
283
+ localization: {
284
+ locale: 'en-US',
285
+ useLocaleGrouping: false
286
+ }
287
+ },
288
+ performance: {
289
+ enableTracking: false,
290
+ samplingRate: 0.1,
291
+ thresholds: {
292
+ warnThresholdMs: 100,
293
+ errorThresholdMs: 1000,
294
+ maxMemoryBytes: 1024 * 1024 * 1024 // 1GB
295
+ },
296
+ metrics: {
297
+ timing: true,
298
+ memory: true,
299
+ cache: true
300
+ }
301
+ },
302
+ debug: {
303
+ verbose: false,
304
+ trackPerformance: false,
305
+ logLevel: 'error'
306
+ },
307
+ features: {
308
+ experimentalFeatures: false,
309
+ useWasm: false,
310
+ workerThreads: false,
311
+ sharedArrayBuffer: false,
312
+ bigIntTypedArrays: true
313
+ }
314
+ };
315
+ /**
316
+ * Type guard to check if config is a full configuration
317
+ */
318
+ function isFullConfig(config) {
319
+ return 'arithmetic' in config && 'dataStructures' in config;
320
+ }
321
+ /**
322
+ * Type guard to check if config is a basic configuration
323
+ */
324
+ function isBasicConfig(config) {
325
+ return !isFullConfig(config);
326
+ }
327
+ /**
328
+ * Validates configuration values
329
+ */
330
+ function validateConfig(config) {
331
+ if (isFullConfig(config)) {
332
+ validateFullConfig(config);
333
+ }
334
+ else {
335
+ validateBasicConfig(config);
336
+ }
337
+ }
338
+ /**
339
+ * Validates basic configuration values
340
+ */
341
+ function validateBasicConfig(config) {
342
+ if (config.precision !== undefined && config.precision < 0) {
343
+ throw new Error('Precision cannot be negative');
344
+ }
345
+ if (config.maxSteps !== undefined && config.maxSteps <= 0) {
346
+ throw new Error('Maximum steps must be positive');
347
+ }
348
+ if (config.debug !== undefined && typeof config.debug !== 'boolean') {
349
+ throw new Error('Debug flag must be a boolean');
350
+ }
351
+ }
352
+ /**
353
+ * Validates full configuration values
354
+ */
355
+ function validateFullConfig(config) {
356
+ if (config.arithmetic.defaultPrecision < 0) {
357
+ throw new Error('Default precision cannot be negative');
358
+ }
359
+ if (config.arithmetic.maxComputationSteps <= 0) {
360
+ throw new Error('Max computation steps must be positive');
361
+ }
362
+ if (config.dataStructures.array.initialCapacity <= 0) {
363
+ throw new Error('Initial capacity must be positive');
364
+ }
365
+ if (config.dataStructures.array.growthFactor <= 1) {
366
+ throw new Error('Growth factor must be greater than 1');
367
+ }
368
+ if (config.performance.samplingRate < 0 || config.performance.samplingRate > 1) {
369
+ throw new Error('Sampling rate must be between 0 and 1');
370
+ }
371
+ }
372
+ /**
373
+ * Merges configuration with appropriate defaults
374
+ */
375
+ function mergeConfig(custom = {}) {
376
+ if (isFullConfig(custom)) {
377
+ const fullConfig = custom;
378
+ return {
379
+ ...DEFAULT_FULL_CONFIG,
380
+ ...fullConfig,
381
+ arithmetic: { ...DEFAULT_FULL_CONFIG.arithmetic, ...fullConfig.arithmetic },
382
+ dataStructures: { ...DEFAULT_FULL_CONFIG.dataStructures, ...fullConfig.dataStructures },
383
+ formatting: { ...DEFAULT_FULL_CONFIG.formatting, ...fullConfig.formatting },
384
+ performance: { ...DEFAULT_FULL_CONFIG.performance, ...fullConfig.performance },
385
+ debug: { ...DEFAULT_FULL_CONFIG.debug, ...fullConfig.debug },
386
+ features: { ...DEFAULT_FULL_CONFIG.features, ...fullConfig.features }
387
+ };
388
+ }
389
+ const basicConfig = {
390
+ precision: custom.precision ?? DEFAULT_BASIC_CONFIG.precision,
391
+ roundingMode: custom.roundingMode ?? DEFAULT_BASIC_CONFIG.roundingMode,
392
+ checkOverflow: custom.checkOverflow ?? DEFAULT_BASIC_CONFIG.checkOverflow,
393
+ maxSteps: custom.maxSteps ?? DEFAULT_BASIC_CONFIG.maxSteps,
394
+ debug: custom.debug ?? DEFAULT_BASIC_CONFIG.debug
395
+ };
396
+ return basicConfig;
397
+ }
398
+
399
+ /**
400
+ * Core constants for Hypernum library
401
+ * Defines fundamental values and limits used across the library
402
+ */
403
+ // Numerical limits
404
+ const MAX_SAFE_INTEGER = BigInt(Number.MAX_SAFE_INTEGER);
405
+ const MIN_SAFE_INTEGER = BigInt(Number.MIN_SAFE_INTEGER);
406
+ const MAX_PRECISION = 100;
407
+ const MAX_COMPUTATION_STEPS = 1000;
408
+ const MAX_BITS = 1024;
409
+ // Commonly used values
410
+ const ZERO = BigInt(0);
411
+ const ONE = BigInt(1);
412
+ const TWO = BigInt(2);
413
+ const TEN = BigInt(10);
414
+ const NEGATIVE_ONE = BigInt(-1);
415
+ // Power operation limits
416
+ const MAX_POWER_BASE = BigInt(2) ** BigInt(53);
417
+ const MAX_POWER_EXPONENT = BigInt(1000);
418
+ const MAX_TETRATION_HEIGHT = BigInt(4);
419
+ const MAX_FACTORIAL_INPUT = BigInt(1000);
420
+ // Tree and heap configuration
421
+ const DEFAULT_TREE_MAX_DEPTH = 1000;
422
+ const DEFAULT_HEAP_INITIAL_CAPACITY = 16;
423
+ const DEFAULT_ARRAY_GROWTH_FACTOR = 2;
424
+ const MIN_ARRAY_CAPACITY = 16;
425
+ // Formatting configuration
426
+ const DEFAULT_DECIMAL_SEPARATOR = '.';
427
+ const DEFAULT_GROUP_SEPARATOR = ',';
428
+ const DEFAULT_GROUP_SIZE = 3;
429
+ const MAX_GROUP_SIZE = 10;
430
+ // Roman numeral limits
431
+ const MIN_ROMAN_VALUE = 1;
432
+ const MAX_ROMAN_VALUE = 3999;
433
+ // Ackermann function limits
434
+ const MAX_ACKERMANN_M = 4;
435
+ const MAX_ACKERMANN_N = 1000;
436
+ // Cache configuration
437
+ const DEFAULT_CACHE_SIZE = 1000;
438
+ const MAX_CACHE_SIZE = 10000;
439
+ // Error messages
440
+ const ERROR_MESSAGES = {
441
+ OVERFLOW: 'Operation would result in overflow',
442
+ UNDERFLOW: 'Operation would result in underflow',
443
+ NEGATIVE_ROOT: 'Cannot compute root of negative number',
444
+ NEGATIVE_EXPONENT: 'Negative exponents not supported for integers',
445
+ DIVISION_BY_ZERO: 'Division by zero',
446
+ INVALID_PRECISION: 'Precision must be non-negative and not exceed MAX_PRECISION',
447
+ INVALID_BASE: 'Base must be a positive integer',
448
+ INVALID_ROMAN: 'Invalid Roman numeral',
449
+ COMPUTATION_LIMIT: 'Computation exceeded maximum allowed steps',
450
+ NEGATIVE_INDEX: 'Array index cannot be negative',
451
+ TREE_DEPTH_EXCEEDED: 'Maximum tree depth exceeded',
452
+ INVALID_HEAP_PROPERTY: 'Heap property violation detected'
453
+ };
454
+ // Feature flags for optional functionality
455
+ const FEATURES = {
456
+ OVERFLOW_CHECKING: true,
457
+ AUTOMATIC_PRECISION: true,
458
+ MEMOIZATION: true,
459
+ TREE_BALANCING: true,
460
+ DEBUG_MODE: false
461
+ };
462
+ // Default options for various operations
463
+ const DEFAULT_OPTIONS$8 = {
464
+ precision: 0,
465
+ roundingMode: 'HALF_EVEN',
466
+ checkOverflow: true,
467
+ maxSteps: MAX_COMPUTATION_STEPS,
468
+ grouping: true,
469
+ uppercase: false,
470
+ cache: true
471
+ };
472
+ // Units for number formatting (powers of 1000)
473
+ const NUMBER_UNITS = [
474
+ { value: 1n, symbol: '' },
475
+ { value: 1000n, symbol: 'K' },
476
+ { value: 1000000n, symbol: 'M' },
477
+ { value: 1000000000n, symbol: 'B' },
478
+ { value: 1000000000000n, symbol: 'T' },
479
+ { value: 1000000000000000n, symbol: 'Q' }
480
+ ];
481
+ // Performance monitoring thresholds
482
+ const PERFORMANCE = {
483
+ WARN_THRESHOLD_MS: 100,
484
+ ERROR_THRESHOLD_MS: 1000,
485
+ MAX_ARRAY_SIZE: 1000000,
486
+ MAX_TREE_SIZE: 1000000
487
+ };
488
+
489
+ /**
490
+ * Custom error types for Hypernum library
491
+ * Provides specific error classes for different types of errors that can occur
492
+ * during mathematical operations and data structure manipulations
493
+ */
494
+ /**
495
+ * Base error class for Hypernum library
496
+ * All other error classes inherit from this
497
+ */
498
+ class HypernumError extends Error {
499
+ constructor(message) {
500
+ super(message);
501
+ this.name = 'HypernumError';
502
+ Object.setPrototypeOf(this, HypernumError.prototype);
503
+ }
504
+ }
505
+ /**
506
+ * Error for validation failures
507
+ */
508
+ class ValidationError extends HypernumError {
509
+ constructor(message) {
510
+ super(message);
511
+ this.name = 'ValidationError';
512
+ Object.setPrototypeOf(this, ValidationError.prototype);
513
+ }
514
+ }
515
+ /**
516
+ * Error for arithmetic underflow conditions
517
+ */
518
+ class UnderflowError extends HypernumError {
519
+ constructor(message = ERROR_MESSAGES.UNDERFLOW) {
520
+ super(message);
521
+ this.name = 'UnderflowError';
522
+ Object.setPrototypeOf(this, UnderflowError.prototype);
523
+ }
524
+ }
525
+ /**
526
+ * Error for division by zero
527
+ */
528
+ class DivisionByZeroError extends HypernumError {
529
+ constructor(message = ERROR_MESSAGES.DIVISION_BY_ZERO) {
530
+ super(message);
531
+ this.name = 'DivisionByZeroError';
532
+ Object.setPrototypeOf(this, DivisionByZeroError.prototype);
533
+ }
534
+ }
535
+ /**
536
+ * Error for precision-related issues
537
+ */
538
+ class PrecisionError extends HypernumError {
539
+ constructor(message = ERROR_MESSAGES.INVALID_PRECISION) {
540
+ super(message);
541
+ this.name = 'PrecisionError';
542
+ Object.setPrototypeOf(this, PrecisionError.prototype);
543
+ }
544
+ }
545
+ /**
546
+ * Error for computation limits exceeded
547
+ */
548
+ class ComputationLimitError extends HypernumError {
549
+ constructor(message = ERROR_MESSAGES.COMPUTATION_LIMIT) {
550
+ super(message);
551
+ this.name = 'ComputationLimitError';
552
+ Object.setPrototypeOf(this, ComputationLimitError.prototype);
553
+ }
554
+ }
555
+ /**
556
+ * Error for invalid operations on data structures
557
+ */
558
+ class DataStructureError extends HypernumError {
559
+ constructor(message) {
560
+ super(message);
561
+ this.name = 'DataStructureError';
562
+ Object.setPrototypeOf(this, DataStructureError.prototype);
563
+ }
564
+ }
565
+ /**
566
+ * Error for heap property violations
567
+ */
568
+ class HeapPropertyError extends DataStructureError {
569
+ constructor(message = ERROR_MESSAGES.INVALID_HEAP_PROPERTY) {
570
+ super(message);
571
+ this.name = 'HeapPropertyError';
572
+ Object.setPrototypeOf(this, HeapPropertyError.prototype);
573
+ }
574
+ }
575
+ /**
576
+ * Error for tree-related issues
577
+ */
578
+ class TreeError extends DataStructureError {
579
+ constructor(message = ERROR_MESSAGES.TREE_DEPTH_EXCEEDED) {
580
+ super(message);
581
+ this.name = 'TreeError';
582
+ Object.setPrototypeOf(this, TreeError.prototype);
583
+ }
584
+ }
585
+ /**
586
+ * Error for array index out of bounds
587
+ */
588
+ class IndexError extends DataStructureError {
589
+ constructor(message = ERROR_MESSAGES.NEGATIVE_INDEX) {
590
+ super(message);
591
+ this.name = 'IndexError';
592
+ Object.setPrototypeOf(this, IndexError.prototype);
593
+ }
594
+ }
595
+ /**
596
+ * Error for invalid number format or conversion
597
+ */
598
+ class FormatError extends HypernumError {
599
+ constructor(message) {
600
+ super(message);
601
+ this.name = 'FormatError';
602
+ Object.setPrototypeOf(this, FormatError.prototype);
603
+ }
604
+ }
605
+ /**
606
+ * Error for invalid Roman numeral operations
607
+ */
608
+ class RomanNumeralError extends FormatError {
609
+ constructor(message = ERROR_MESSAGES.INVALID_ROMAN) {
610
+ super(message);
611
+ this.name = 'RomanNumeralError';
612
+ Object.setPrototypeOf(this, RomanNumeralError.prototype);
613
+ }
614
+ }
615
+
616
+ /**
617
+ * Arithmetic operations module for Hypernum library
618
+ * Provides high-precision arithmetic operations with BigInt support
619
+ */
620
+ const DEFAULT_OPTIONS$7 = {
621
+ precision: 0,
622
+ roundingMode: exports.RoundingMode.HALF_EVEN,
623
+ checkOverflow: true
624
+ };
625
+ /**
626
+ * Adds two numbers with optional precision and overflow checking
627
+ */
628
+ function add(a, b, options = {}) {
629
+ const opts = { ...DEFAULT_OPTIONS$7, ...options };
630
+ const bigA = toBigInt(a);
631
+ const bigB = toBigInt(b);
632
+ if (opts.checkOverflow) {
633
+ checkAdditionOverflow(bigA, bigB);
634
+ }
635
+ if (opts.precision === 0) {
636
+ return bigA + bigB;
637
+ }
638
+ const [scaledA, scaledB] = normalizePrecision(bigA, bigB, opts.precision, opts.precision);
639
+ const result = scaledA + scaledB;
640
+ return round(result, opts.precision, opts.roundingMode);
641
+ }
642
+ /**
643
+ * Subtracts two numbers with optional precision and overflow checking
644
+ */
645
+ function subtract(a, b, options = {}) {
646
+ const opts = { ...DEFAULT_OPTIONS$7, ...options };
647
+ const bigA = toBigInt(a);
648
+ const bigB = toBigInt(b);
649
+ if (opts.checkOverflow) {
650
+ checkAdditionOverflow(bigA, -bigB);
651
+ }
652
+ if (opts.precision === 0) {
653
+ return bigA - bigB;
654
+ }
655
+ const [scaledA, scaledB] = normalizePrecision(bigA, bigB, opts.precision, opts.precision);
656
+ const result = scaledA - scaledB;
657
+ return round(result, opts.precision, opts.roundingMode);
658
+ }
659
+ /**
660
+ * Multiplies two numbers with optional precision and overflow checking
661
+ */
662
+ function multiply(a, b, options = {}) {
663
+ const opts = { ...DEFAULT_OPTIONS$7, ...options };
664
+ const bigA = toBigInt(a);
665
+ const bigB = toBigInt(b);
666
+ if (opts.checkOverflow) {
667
+ checkMultiplicationOverflow(bigA, bigB);
668
+ }
669
+ const result = bigA * bigB;
670
+ if (opts.precision === 0) {
671
+ return result;
672
+ }
673
+ return round(result, opts.precision, opts.roundingMode);
674
+ }
675
+ /**
676
+ * Divides two numbers with specified precision and rounding
677
+ */
678
+ function divide(numerator, denominator, options = {}) {
679
+ const opts = { ...DEFAULT_OPTIONS$7, ...options };
680
+ const bigNumerator = toBigInt(numerator);
681
+ const bigDenominator = toBigInt(denominator);
682
+ if (bigDenominator === BigInt(0)) {
683
+ throw new ValidationError$1('Division by zero');
684
+ }
685
+ return scaledDivision(bigNumerator, bigDenominator, opts.precision, opts.roundingMode);
686
+ }
687
+ /**
688
+ * Calculates remainder with optional precision
689
+ */
690
+ function remainder(a, b, options = {}) {
691
+ const opts = { ...DEFAULT_OPTIONS$7, ...options };
692
+ const bigA = toBigInt(a);
693
+ const bigB = toBigInt(b);
694
+ if (bigB === BigInt(0)) {
695
+ throw new ValidationError$1('Division by zero in remainder operation');
696
+ }
697
+ if (opts.precision === 0) {
698
+ return bigA % bigB;
699
+ }
700
+ const [scaledA, scaledB] = normalizePrecision(bigA, bigB, opts.precision, opts.precision);
701
+ const result = scaledA % scaledB;
702
+ return round(result, opts.precision, opts.roundingMode);
703
+ }
704
+ /**
705
+ * Calculates the absolute value
706
+ */
707
+ function abs(value) {
708
+ const bigValue = toBigInt(value);
709
+ return bigValue < BigInt(0) ? -bigValue : bigValue;
710
+ }
711
+ /**
712
+ * Returns the sign of a number (-1, 0, or 1)
713
+ */
714
+ function sign(value) {
715
+ const bigValue = toBigInt(value);
716
+ if (bigValue < BigInt(0))
717
+ return BigInt(-1);
718
+ if (bigValue > BigInt(0))
719
+ return BigInt(1);
720
+ return BigInt(0);
721
+ }
722
+ /**
723
+ * Calculates the greatest common divisor of two numbers
724
+ */
725
+ function gcd(a, b) {
726
+ let bigA = abs(toBigInt(a));
727
+ let bigB = abs(toBigInt(b));
728
+ while (bigB !== BigInt(0)) {
729
+ const temp = bigB;
730
+ bigB = bigA % bigB;
731
+ bigA = temp;
732
+ }
733
+ return bigA;
734
+ }
735
+ /**
736
+ * Calculates the least common multiple of two numbers
737
+ */
738
+ function lcm(a, b) {
739
+ const bigA = abs(toBigInt(a));
740
+ const bigB = abs(toBigInt(b));
741
+ if (bigA === BigInt(0) || bigB === BigInt(0)) {
742
+ return BigInt(0);
743
+ }
744
+ return abs(bigA * bigB) / gcd(bigA, bigB);
745
+ }
746
+
747
+ /**
748
+ * Bitwise operations module for Hypernum library
749
+ * Provides functions for bit-level manipulations of large numbers
750
+ */
751
+ const DEFAULT_OPTIONS$6 = {
752
+ maxBits: 1024,
753
+ strict: true
754
+ };
755
+ /**
756
+ * Validates shift amount is within reasonable bounds
757
+ */
758
+ function validateShift(shift, options) {
759
+ if (shift < 0n) {
760
+ throw new ValidationError$1('Shift amount cannot be negative');
761
+ }
762
+ if (options.strict && shift >= BigInt(options.maxBits)) {
763
+ throw new ValidationError$1(`Shift amount exceeds maximum of ${options.maxBits} bits`);
764
+ }
765
+ }
766
+ /**
767
+ * Performs bitwise AND operation
768
+ */
769
+ function and(a, b) {
770
+ const bigA = toBigInt(a);
771
+ const bigB = toBigInt(b);
772
+ return bigA & bigB;
773
+ }
774
+ /**
775
+ * Performs bitwise OR operation
776
+ */
777
+ function or(a, b) {
778
+ const bigA = toBigInt(a);
779
+ const bigB = toBigInt(b);
780
+ return bigA | bigB;
781
+ }
782
+ /**
783
+ * Performs bitwise XOR operation
784
+ */
785
+ function xor(a, b) {
786
+ const bigA = toBigInt(a);
787
+ const bigB = toBigInt(b);
788
+ return bigA ^ bigB;
789
+ }
790
+ /**
791
+ * Performs bitwise NOT operation
792
+ */
793
+ function not(value) {
794
+ const bigValue = toBigInt(value);
795
+ return ~bigValue;
796
+ }
797
+ /**
798
+ * Performs left shift operation
799
+ */
800
+ function leftShift(value, shift, options = {}) {
801
+ const opts = { ...DEFAULT_OPTIONS$6, ...options };
802
+ const bigValue = toBigInt(value);
803
+ const bigShift = toBigInt(shift);
804
+ validateShift(bigShift, opts);
805
+ return bigValue << bigShift;
806
+ }
807
+ /**
808
+ * Performs right shift operation
809
+ */
810
+ function rightShift(value, shift, options = {}) {
811
+ const opts = { ...DEFAULT_OPTIONS$6, ...options };
812
+ const bigValue = toBigInt(value);
813
+ const bigShift = toBigInt(shift);
814
+ validateShift(bigShift, opts);
815
+ return bigValue >> bigShift;
816
+ }
817
+ /**
818
+ * Performs unsigned right shift operation
819
+ * Note: BigInt doesn't have >>> operator, so we implement it manually
820
+ */
821
+ function unsignedRightShift(value, shift, options = {}) {
822
+ const opts = { ...DEFAULT_OPTIONS$6, ...options };
823
+ const bigValue = toBigInt(value);
824
+ const bigShift = toBigInt(shift);
825
+ validateShift(bigShift, opts);
826
+ if (bigValue >= 0n) {
827
+ return bigValue >> bigShift;
828
+ }
829
+ // Handle negative numbers by first converting to positive
830
+ const mask = (1n << BigInt(opts.maxBits)) - 1n;
831
+ return (bigValue & mask) >> bigShift;
832
+ }
833
+ /**
834
+ * Rotates bits left by specified amount
835
+ */
836
+ function rotateLeft(value, rotation, options = {}) {
837
+ const opts = { ...DEFAULT_OPTIONS$6, ...options };
838
+ const bigValue = toBigInt(value);
839
+ let bigRotation = toBigInt(rotation);
840
+ validateNonNegative(bigRotation);
841
+ // Normalize rotation to be within maxBits
842
+ if (bigRotation >= BigInt(opts.maxBits)) {
843
+ bigRotation = bigRotation % BigInt(opts.maxBits);
844
+ }
845
+ if (bigRotation === 0n) {
846
+ return bigValue;
847
+ }
848
+ const leftPart = leftShift(bigValue, bigRotation, opts);
849
+ const rightPart = unsignedRightShift(bigValue, BigInt(opts.maxBits) - bigRotation, opts);
850
+ return leftPart | rightPart;
851
+ }
852
+ /**
853
+ * Rotates bits right by specified amount
854
+ */
855
+ function rotateRight(value, rotation, options = {}) {
856
+ const opts = { ...DEFAULT_OPTIONS$6, ...options };
857
+ const bigValue = toBigInt(value);
858
+ let bigRotation = toBigInt(rotation);
859
+ validateNonNegative(bigRotation);
860
+ // Normalize rotation to be within maxBits
861
+ if (bigRotation >= BigInt(opts.maxBits)) {
862
+ bigRotation = bigRotation % BigInt(opts.maxBits);
863
+ }
864
+ if (bigRotation === 0n) {
865
+ return bigValue;
866
+ }
867
+ const rightPart = unsignedRightShift(bigValue, bigRotation, opts);
868
+ const leftPart = leftShift(bigValue, BigInt(opts.maxBits) - bigRotation, opts);
869
+ return leftPart | rightPart;
870
+ }
871
+ /**
872
+ * Counts number of set bits (1s)
873
+ */
874
+ function popCount(value, options = {}) {
875
+ const opts = { ...DEFAULT_OPTIONS$6, ...options };
876
+ let bigValue = toBigInt(value);
877
+ let count = 0n;
878
+ while (bigValue !== 0n) {
879
+ count += bigValue & 1n;
880
+ bigValue = unsignedRightShift(bigValue, 1n, opts);
881
+ }
882
+ return count;
883
+ }
884
+ /**
885
+ * Returns number of trailing zero bits
886
+ */
887
+ function trailingZeros(value, options = {}) {
888
+ const opts = { ...DEFAULT_OPTIONS$6, ...options };
889
+ let bigValue = toBigInt(value);
890
+ if (bigValue === 0n) {
891
+ return BigInt(opts.maxBits);
892
+ }
893
+ let count = 0n;
894
+ while ((bigValue & 1n) === 0n) {
895
+ count++;
896
+ bigValue = unsignedRightShift(bigValue, 1n, opts);
897
+ }
898
+ return count;
899
+ }
900
+ /**
901
+ * Returns number of leading zero bits
902
+ */
903
+ function leadingZeros(value, options = {}) {
904
+ const opts = { ...DEFAULT_OPTIONS$6, ...options };
905
+ let bigValue = toBigInt(value);
906
+ if (bigValue === 0n) {
907
+ return BigInt(opts.maxBits);
908
+ }
909
+ let count = 0n;
910
+ const msb = 1n << BigInt(opts.maxBits - 1);
911
+ while ((bigValue & msb) === 0n && count < BigInt(opts.maxBits)) {
912
+ count++;
913
+ bigValue = leftShift(bigValue, 1n, opts);
914
+ }
915
+ return count;
916
+ }
917
+ /**
918
+ * Returns bit at specified position
919
+ */
920
+ function getBit(value, position, options = {}) {
921
+ const opts = { ...DEFAULT_OPTIONS$6, ...options };
922
+ const bigValue = toBigInt(value);
923
+ const bigPosition = toBigInt(position);
924
+ validateNonNegative(bigPosition);
925
+ if (opts.strict && bigPosition >= BigInt(opts.maxBits)) {
926
+ throw new ValidationError$1(`Bit position exceeds maximum of ${opts.maxBits} bits`);
927
+ }
928
+ return (bigValue & (1n << bigPosition)) !== 0n;
929
+ }
930
+ /**
931
+ * Sets bit at specified position
932
+ */
933
+ function setBit(value, position, options = {}) {
934
+ const opts = { ...DEFAULT_OPTIONS$6, ...options };
935
+ const bigValue = toBigInt(value);
936
+ const bigPosition = toBigInt(position);
937
+ validateNonNegative(bigPosition);
938
+ if (opts.strict && bigPosition >= BigInt(opts.maxBits)) {
939
+ throw new ValidationError$1(`Bit position exceeds maximum of ${opts.maxBits} bits`);
940
+ }
941
+ return bigValue | (1n << bigPosition);
942
+ }
943
+ /**
944
+ * Clears bit at specified position
945
+ */
946
+ function clearBit(value, position, options = {}) {
947
+ const opts = { ...DEFAULT_OPTIONS$6, ...options };
948
+ const bigValue = toBigInt(value);
949
+ const bigPosition = toBigInt(position);
950
+ validateNonNegative(bigPosition);
951
+ if (opts.strict && bigPosition >= BigInt(opts.maxBits)) {
952
+ throw new ValidationError$1(`Bit position exceeds maximum of ${opts.maxBits} bits`);
953
+ }
954
+ return bigValue & ~(1n << bigPosition);
955
+ }
956
+ /**
957
+ * Toggles bit at specified position
958
+ */
959
+ function toggleBit(value, position, options = {}) {
960
+ const opts = { ...DEFAULT_OPTIONS$6, ...options };
961
+ const bigValue = toBigInt(value);
962
+ const bigPosition = toBigInt(position);
963
+ validateNonNegative(bigPosition);
964
+ if (opts.strict && bigPosition >= BigInt(opts.maxBits)) {
965
+ throw new ValidationError$1(`Bit position exceeds maximum of ${opts.maxBits} bits`);
966
+ }
967
+ return bigValue ^ (1n << bigPosition);
968
+ }
969
+
970
+ /**
971
+ * Power operations module for Hypernum library
972
+ * Provides efficient implementations for exponentiation and related operations
973
+ */
974
+ const DEFAULT_OPTIONS$5 = {
975
+ precision: 0,
976
+ roundingMode: exports.RoundingMode.HALF_EVEN,
977
+ checkOverflow: true,
978
+ maxSteps: 1000
979
+ };
980
+ /**
981
+ * Raises a number to an integer power using binary exponentiation
982
+ */
983
+ function power(baseValue, exponentValue, options = {}) {
984
+ const opts = { ...DEFAULT_OPTIONS$5, ...options };
985
+ const bigBase = toBigInt(baseValue);
986
+ const bigExponent = toBigInt(exponentValue);
987
+ // Handle special cases
988
+ if (bigExponent === 0n) {
989
+ return 1n;
990
+ }
991
+ if (bigExponent === 1n) {
992
+ return bigBase;
993
+ }
994
+ if (bigBase === 0n && bigExponent < 0n) {
995
+ throw new ValidationError$1('Zero cannot be raised to a negative power');
996
+ }
997
+ if (bigBase === 0n) {
998
+ return 0n;
999
+ }
1000
+ if (bigBase === 1n) {
1001
+ return 1n;
1002
+ }
1003
+ if (bigBase === -1n) {
1004
+ return bigExponent % 2n === 0n ? 1n : -1n;
1005
+ }
1006
+ // Validate inputs
1007
+ if (bigExponent < 0n) {
1008
+ throw new ValidationError$1('Negative exponents not supported for integer power');
1009
+ }
1010
+ if (opts.checkOverflow) {
1011
+ checkPowerOverflow(bigBase, bigExponent);
1012
+ }
1013
+ // Binary exponentiation algorithm
1014
+ let result = 1n;
1015
+ let base = bigBase;
1016
+ let exponent = bigExponent;
1017
+ let steps = 0;
1018
+ while (exponent > 0n) {
1019
+ if (steps++ > opts.maxSteps) {
1020
+ throw new OverflowError('Power operation exceeded maximum computation steps');
1021
+ }
1022
+ if (exponent & 1n) {
1023
+ result *= base;
1024
+ }
1025
+ base *= base;
1026
+ exponent >>= 1n;
1027
+ }
1028
+ if (opts.precision > 0) {
1029
+ return round(result, opts.precision, opts.roundingMode);
1030
+ }
1031
+ return result;
1032
+ }
1033
+ /**
1034
+ * Calculates square root using Newton's method
1035
+ */
1036
+ function sqrt(value, options = {}) {
1037
+ const opts = { ...DEFAULT_OPTIONS$5, ...options };
1038
+ const bigValue = toBigInt(value);
1039
+ validateNonNegative(bigValue);
1040
+ if (bigValue === 0n) {
1041
+ return 0n;
1042
+ }
1043
+ if (bigValue === 1n) {
1044
+ return 1n;
1045
+ }
1046
+ // Newton's method for square root
1047
+ let guess = bigValue >> 1n;
1048
+ let lastGuess;
1049
+ let steps = 0;
1050
+ do {
1051
+ if (steps++ > opts.maxSteps) {
1052
+ throw new OverflowError('Square root operation exceeded maximum computation steps');
1053
+ }
1054
+ lastGuess = guess;
1055
+ guess = (guess + bigValue / guess) >> 1n;
1056
+ } while (guess < lastGuess);
1057
+ if (opts.precision > 0) {
1058
+ return round(lastGuess, opts.precision, opts.roundingMode);
1059
+ }
1060
+ return lastGuess;
1061
+ }
1062
+ /**
1063
+ * Calculates nth root using Newton's method
1064
+ */
1065
+ function nthRoot(value, n, options = {}) {
1066
+ const opts = { ...DEFAULT_OPTIONS$5, ...options };
1067
+ const bigValue = toBigInt(value);
1068
+ const bigN = toBigInt(n);
1069
+ validateNonNegative(bigValue);
1070
+ if (bigN <= 0n) {
1071
+ throw new ValidationError$1('Root index must be positive');
1072
+ }
1073
+ if (bigValue === 0n) {
1074
+ return 0n;
1075
+ }
1076
+ if (bigValue === 1n) {
1077
+ return 1n;
1078
+ }
1079
+ if (bigN === 1n) {
1080
+ return bigValue;
1081
+ }
1082
+ if (bigN === 2n) {
1083
+ return sqrt(bigValue, opts);
1084
+ }
1085
+ // Newton's method for nth root
1086
+ let guess = bigValue >> 1n;
1087
+ let lastGuess;
1088
+ let steps = 0;
1089
+ const nMinus1 = bigN - 1n;
1090
+ do {
1091
+ if (steps++ > opts.maxSteps) {
1092
+ throw new OverflowError('Nth root operation exceeded maximum computation steps');
1093
+ }
1094
+ lastGuess = guess;
1095
+ const powered = power(guess, nMinus1, opts);
1096
+ guess = ((nMinus1 * guess) + (bigValue / powered)) / bigN;
1097
+ } while (guess < lastGuess);
1098
+ if (opts.precision > 0) {
1099
+ return round(lastGuess, opts.precision, opts.roundingMode);
1100
+ }
1101
+ return lastGuess;
1102
+ }
1103
+ /**
1104
+ * Calculates tetration (repeated exponentiation)
1105
+ * a↑↑n = a^(a^(a^...)) (n times)
1106
+ */
1107
+ function tetration(base, height, options = {}) {
1108
+ const opts = { ...DEFAULT_OPTIONS$5, ...options };
1109
+ const bigBase = toBigInt(base);
1110
+ const bigHeight = toBigInt(height);
1111
+ validateNonNegative(bigHeight);
1112
+ if (bigHeight === 0n) {
1113
+ return 1n;
1114
+ }
1115
+ if (bigHeight === 1n) {
1116
+ return bigBase;
1117
+ }
1118
+ if (bigBase === 0n) {
1119
+ return bigHeight % 2n === 0n ? 1n : 0n;
1120
+ }
1121
+ if (bigBase === 1n) {
1122
+ return 1n;
1123
+ }
1124
+ if (bigBase === 2n && bigHeight > 4n) {
1125
+ throw new OverflowError('Tetration would overflow for base 2 and height > 4');
1126
+ }
1127
+ let result = bigBase;
1128
+ let steps = 0;
1129
+ for (let i = 1n; i < bigHeight; i++) {
1130
+ if (steps++ > opts.maxSteps) {
1131
+ throw new OverflowError('Tetration operation exceeded maximum computation steps');
1132
+ }
1133
+ result = power(bigBase, result, opts);
1134
+ }
1135
+ if (opts.precision > 0) {
1136
+ return round(result, opts.precision, opts.roundingMode);
1137
+ }
1138
+ return result;
1139
+ }
1140
+ /**
1141
+ * Calculates super-root (inverse tetration)
1142
+ * Finds x where x↑↑n = value
1143
+ */
1144
+ function superRoot(value, height, options = {}) {
1145
+ const opts = { ...DEFAULT_OPTIONS$5, ...options };
1146
+ const bigValue = toBigInt(value);
1147
+ const bigHeight = toBigInt(height);
1148
+ validateNonNegative(bigHeight);
1149
+ if (bigHeight === 0n) {
1150
+ throw new ValidationError$1('Height cannot be zero for super-root');
1151
+ }
1152
+ if (bigValue < 1n) {
1153
+ throw new ValidationError$1('Value must be at least 1 for super-root');
1154
+ }
1155
+ if (bigValue === 1n) {
1156
+ return 1n;
1157
+ }
1158
+ if (bigHeight === 1n) {
1159
+ return bigValue;
1160
+ }
1161
+ // Binary search for super-root
1162
+ let left = 1n;
1163
+ let right = bigValue;
1164
+ let steps = 0;
1165
+ while (left <= right) {
1166
+ if (steps++ > opts.maxSteps) {
1167
+ throw new OverflowError('Super-root operation exceeded maximum computation steps');
1168
+ }
1169
+ const mid = (left + right) >> 1n;
1170
+ try {
1171
+ const test = tetration(mid, bigHeight, opts);
1172
+ if (test === bigValue) {
1173
+ return mid;
1174
+ }
1175
+ if (test < bigValue) {
1176
+ left = mid + 1n;
1177
+ }
1178
+ else {
1179
+ right = mid - 1n;
1180
+ }
1181
+ }
1182
+ catch (error) {
1183
+ right = mid - 1n;
1184
+ }
1185
+ }
1186
+ if (opts.precision > 0) {
1187
+ return round(right, opts.precision, opts.roundingMode);
1188
+ }
1189
+ return right;
1190
+ }
1191
+
1192
+ /**
1193
+ * Abstract base heap class implementing common heap operations
1194
+ */
1195
+ class Heap {
1196
+ constructor(comparator) {
1197
+ this.heap = [];
1198
+ this.compare = comparator;
1199
+ }
1200
+ /**
1201
+ * Gets the size of the heap
1202
+ */
1203
+ size() {
1204
+ return this.heap.length;
1205
+ }
1206
+ /**
1207
+ * Checks if the heap is empty
1208
+ */
1209
+ isEmpty() {
1210
+ return this.heap.length === 0;
1211
+ }
1212
+ /**
1213
+ * Peeks at the root element without removing it
1214
+ */
1215
+ peek() {
1216
+ return this.heap[0];
1217
+ }
1218
+ /**
1219
+ * Inserts a new element into the heap
1220
+ */
1221
+ push(value) {
1222
+ this.heap.push(value);
1223
+ this.siftUp(this.heap.length - 1);
1224
+ }
1225
+ /**
1226
+ * Removes and returns the root element
1227
+ */
1228
+ pop() {
1229
+ if (this.isEmpty()) {
1230
+ return undefined;
1231
+ }
1232
+ const root = this.heap[0];
1233
+ const last = this.heap.pop();
1234
+ if (!this.isEmpty()) {
1235
+ this.heap[0] = last;
1236
+ this.siftDown(0);
1237
+ }
1238
+ return root;
1239
+ }
1240
+ /**
1241
+ * Removes all elements from the heap
1242
+ */
1243
+ clear() {
1244
+ this.heap = [];
1245
+ }
1246
+ /**
1247
+ * Creates a heap from an array of elements
1248
+ */
1249
+ static heapify(array, comparator) {
1250
+ const heap = this instanceof MinHeap ? new MinHeap(comparator) : new MaxHeap(comparator);
1251
+ array.forEach(item => heap.push(item));
1252
+ return heap;
1253
+ }
1254
+ /**
1255
+ * Gets the parent index of a node
1256
+ */
1257
+ getParentIndex(index) {
1258
+ return Math.floor((index - 1) / 2);
1259
+ }
1260
+ /**
1261
+ * Gets the left child index of a node
1262
+ */
1263
+ getLeftChildIndex(index) {
1264
+ return 2 * index + 1;
1265
+ }
1266
+ /**
1267
+ * Gets the right child index of a node
1268
+ */
1269
+ getRightChildIndex(index) {
1270
+ return 2 * index + 2;
1271
+ }
1272
+ /**
1273
+ * Swaps two elements in the heap
1274
+ */
1275
+ swap(i, j) {
1276
+ const temp = this.heap[i];
1277
+ this.heap[i] = this.heap[j];
1278
+ this.heap[j] = temp;
1279
+ }
1280
+ }
1281
+ /**
1282
+ * MinHeap implementation where the root is the smallest element
1283
+ */
1284
+ class MinHeap extends Heap {
1285
+ constructor(comparator) {
1286
+ super(comparator);
1287
+ }
1288
+ siftUp(index) {
1289
+ while (index > 0) {
1290
+ const parentIndex = this.getParentIndex(index);
1291
+ if (this.compare(this.heap[index], this.heap[parentIndex]) >= 0) {
1292
+ break;
1293
+ }
1294
+ this.swap(index, parentIndex);
1295
+ index = parentIndex;
1296
+ }
1297
+ }
1298
+ siftDown(index) {
1299
+ const size = this.heap.length;
1300
+ while (true) {
1301
+ let smallest = index;
1302
+ const left = this.getLeftChildIndex(index);
1303
+ const right = this.getRightChildIndex(index);
1304
+ if (left < size && this.compare(this.heap[left], this.heap[smallest]) < 0) {
1305
+ smallest = left;
1306
+ }
1307
+ if (right < size && this.heap[right] !== undefined && this.compare(this.heap[right], this.heap[smallest]) < 0) {
1308
+ smallest = right;
1309
+ }
1310
+ if (smallest === index) {
1311
+ break;
1312
+ }
1313
+ this.swap(index, smallest);
1314
+ index = smallest;
1315
+ }
1316
+ }
1317
+ }
1318
+ /**
1319
+ * MaxHeap implementation where the root is the largest element
1320
+ */
1321
+ class MaxHeap extends Heap {
1322
+ constructor(comparator) {
1323
+ super(comparator);
1324
+ }
1325
+ siftUp(index) {
1326
+ while (index > 0) {
1327
+ const parentIndex = this.getParentIndex(index);
1328
+ if (this.compare(this.heap[index], this.heap[parentIndex]) <= 0) {
1329
+ break;
1330
+ }
1331
+ this.swap(index, parentIndex);
1332
+ index = parentIndex;
1333
+ }
1334
+ }
1335
+ siftDown(index) {
1336
+ const size = this.heap.length;
1337
+ while (true) {
1338
+ let largest = index;
1339
+ const left = this.getLeftChildIndex(index);
1340
+ const right = this.getRightChildIndex(index);
1341
+ if (left < size && this.heap[left] !== undefined && this.compare(this.heap[left], this.heap[largest]) > 0) {
1342
+ largest = left;
1343
+ }
1344
+ if (right < size && this.heap[right] !== undefined && this.compare(this.heap[right], this.heap[largest]) > 0) {
1345
+ largest = right;
1346
+ }
1347
+ if (largest === index) {
1348
+ break;
1349
+ }
1350
+ this.swap(index, largest);
1351
+ index = largest;
1352
+ }
1353
+ }
1354
+ }
1355
+ /**
1356
+ * Custom comparator for large numbers
1357
+ */
1358
+ function createLargeNumberComparator() {
1359
+ return (a, b) => {
1360
+ return a > b ? 1 : a < b ? -1 : 0;
1361
+ };
1362
+ }
1363
+
1364
+ /**
1365
+ * Class representing the Ackermann function computation structure
1366
+ * Implements caching and relationship tracking between values
1367
+ */
1368
+ class AckermannStructure {
1369
+ constructor() {
1370
+ this.nodes = new Map();
1371
+ this.maxComputedM = -1;
1372
+ this.maxComputedN = -1;
1373
+ this.heap = new MaxHeap(createLargeNumberComparator());
1374
+ }
1375
+ /**
1376
+ * Generates a unique key for node storage
1377
+ */
1378
+ static getNodeKey(m, n) {
1379
+ return `${m},${n}`;
1380
+ }
1381
+ /**
1382
+ * Computes the Ackermann function value
1383
+ * Uses recursion with memoization
1384
+ */
1385
+ computeAckermann(m, n) {
1386
+ // Handle invalid inputs
1387
+ if (m < 0 || n < 0) {
1388
+ throw new Error('Ackermann function undefined for negative numbers');
1389
+ }
1390
+ // Check if already computed
1391
+ const key = AckermannStructure.getNodeKey(m, n);
1392
+ const existing = this.nodes.get(key);
1393
+ if (existing) {
1394
+ return existing.value;
1395
+ }
1396
+ // Compute based on Ackermann function definition
1397
+ let value;
1398
+ try {
1399
+ if (m === 0) {
1400
+ value = BigInt(n + 1);
1401
+ }
1402
+ else if (n === 0) {
1403
+ value = this.computeAckermann(m - 1, 1);
1404
+ }
1405
+ else {
1406
+ const inner = this.computeAckermann(m, n - 1);
1407
+ // Convert bigint to number for recursion, being careful about size
1408
+ const innerNum = inner <= BigInt(Number.MAX_SAFE_INTEGER)
1409
+ ? Number(inner)
1410
+ : Number.MAX_SAFE_INTEGER;
1411
+ value = this.computeAckermann(m - 1, innerNum);
1412
+ }
1413
+ }
1414
+ catch (error) {
1415
+ // Handle stack overflow or computation limits
1416
+ if (error instanceof RangeError) {
1417
+ return BigInt(Number.MAX_SAFE_INTEGER);
1418
+ }
1419
+ throw error;
1420
+ }
1421
+ return value;
1422
+ }
1423
+ /**
1424
+ * Adds a new node to the structure
1425
+ */
1426
+ addNode(m, n) {
1427
+ const key = AckermannStructure.getNodeKey(m, n);
1428
+ if (this.nodes.has(key)) {
1429
+ return this.nodes.get(key);
1430
+ }
1431
+ // Create new node
1432
+ const value = this.computeAckermann(m, n);
1433
+ const node = { m, n, value };
1434
+ this.nodes.set(key, node);
1435
+ // Link to existing nodes
1436
+ const prevMKey = AckermannStructure.getNodeKey(m - 1, n);
1437
+ const prevNKey = AckermannStructure.getNodeKey(m, n - 1);
1438
+ if (this.nodes.has(prevMKey)) {
1439
+ const prevM = this.nodes.get(prevMKey);
1440
+ node.prevM = prevM;
1441
+ prevM.nextM = node;
1442
+ }
1443
+ if (this.nodes.has(prevNKey)) {
1444
+ const prevN = this.nodes.get(prevNKey);
1445
+ node.prevN = prevN;
1446
+ prevN.nextN = node;
1447
+ }
1448
+ // Update tracking
1449
+ this.maxComputedM = Math.max(this.maxComputedM, m);
1450
+ this.maxComputedN = Math.max(this.maxComputedN, n);
1451
+ this.heap.push(value);
1452
+ return node;
1453
+ }
1454
+ /**
1455
+ * Builds nodes for a range of m and n values
1456
+ */
1457
+ buildRange(mRange, nRange) {
1458
+ for (let m = 0; m <= mRange; m++) {
1459
+ for (let n = 0; n <= nRange; n++) {
1460
+ this.addNode(m, n);
1461
+ }
1462
+ }
1463
+ }
1464
+ /**
1465
+ * Gets the computation path to reach A(m,n)
1466
+ */
1467
+ getComputationPath(m, n) {
1468
+ const path = [];
1469
+ const key = AckermannStructure.getNodeKey(m, n);
1470
+ let current = this.nodes.get(key);
1471
+ while (current) {
1472
+ path.push({
1473
+ m: current.m,
1474
+ n: current.n,
1475
+ value: current.value
1476
+ });
1477
+ // Follow computation path backwards
1478
+ if (current.m === 0) {
1479
+ break;
1480
+ }
1481
+ else if (current.n === 0) {
1482
+ current = this.nodes.get(AckermannStructure.getNodeKey(current.m - 1, 1));
1483
+ }
1484
+ else {
1485
+ const prevN = this.nodes.get(AckermannStructure.getNodeKey(current.m, current.n - 1));
1486
+ if (prevN) {
1487
+ path.push({
1488
+ m: prevN.m,
1489
+ n: prevN.n,
1490
+ value: prevN.value
1491
+ });
1492
+ }
1493
+ // Convert bigint to number safely for the next lookup
1494
+ const nextValue = prevN?.value ?? BigInt(0);
1495
+ const safeNextValue = nextValue <= BigInt(Number.MAX_SAFE_INTEGER)
1496
+ ? Number(nextValue)
1497
+ : Number.MAX_SAFE_INTEGER;
1498
+ current = this.nodes.get(AckermannStructure.getNodeKey(current.m - 1, safeNextValue));
1499
+ }
1500
+ }
1501
+ return path.reverse();
1502
+ }
1503
+ /**
1504
+ * Analyzes growth rate for a fixed m value
1505
+ */
1506
+ analyzeGrowthRate(m) {
1507
+ const growth = new Map();
1508
+ let prevValue = BigInt(1);
1509
+ for (let n = 0; n <= this.maxComputedN; n++) {
1510
+ const key = AckermannStructure.getNodeKey(m, n);
1511
+ const node = this.nodes.get(key);
1512
+ if (!node || node.value >= BigInt(Number.MAX_SAFE_INTEGER)) {
1513
+ break;
1514
+ }
1515
+ growth.set(n, {
1516
+ value: node.value,
1517
+ increase: node.value - prevValue,
1518
+ multiplier: prevValue === BigInt(0) ? BigInt(0) : node.value / prevValue
1519
+ });
1520
+ prevValue = node.value;
1521
+ }
1522
+ return growth;
1523
+ }
1524
+ /**
1525
+ * Gets the largest computed value
1526
+ */
1527
+ getLargestValue() {
1528
+ return this.heap.peek() ?? BigInt(0);
1529
+ }
1530
+ /**
1531
+ * Gets a specific Ackermann value if it exists
1532
+ */
1533
+ getValue(m, n) {
1534
+ return this.nodes.get(AckermannStructure.getNodeKey(m, n))?.value;
1535
+ }
1536
+ }
1537
+
1538
+ /**
1539
+ * A specialized array implementation for handling large numbers and providing
1540
+ * efficient operations with segment tree support
1541
+ */
1542
+ class BigArray {
1543
+ constructor(options = {}) {
1544
+ const { initialCapacity = 16, growthFactor = 2, comparator = ((a, b) => {
1545
+ if (a < b)
1546
+ return -1;
1547
+ if (a > b)
1548
+ return 1;
1549
+ return 0;
1550
+ }) } = options;
1551
+ this.capacity = initialCapacity;
1552
+ this.growthFactor = growthFactor;
1553
+ this.comparator = comparator;
1554
+ this.size = 0;
1555
+ this.data = new Array(this.capacity);
1556
+ this.segmentTree = new Array(4 * this.capacity).fill(null);
1557
+ }
1558
+ /**
1559
+ * Gets the current size of the array
1560
+ */
1561
+ getSize() {
1562
+ return this.size;
1563
+ }
1564
+ /**
1565
+ * Gets the current capacity of the array
1566
+ */
1567
+ getCapacity() {
1568
+ return this.capacity;
1569
+ }
1570
+ /**
1571
+ * Resizes the internal array when needed
1572
+ */
1573
+ resize(newCapacity) {
1574
+ const newData = new Array(newCapacity);
1575
+ for (let i = 0; i < this.size; i++) {
1576
+ newData[i] = this.data[i];
1577
+ }
1578
+ this.data = newData;
1579
+ this.capacity = newCapacity;
1580
+ this.rebuildSegmentTree();
1581
+ }
1582
+ /**
1583
+ * Appends an element to the end of the array
1584
+ */
1585
+ push(value) {
1586
+ try {
1587
+ if (this.size >= this.capacity) {
1588
+ this.resize(this.capacity * this.growthFactor);
1589
+ }
1590
+ this.data[this.size] = value;
1591
+ this.updateSegmentTree(0, this.size, value);
1592
+ this.size++;
1593
+ return { success: true, value: this.size - 1 };
1594
+ }
1595
+ catch (error) {
1596
+ return {
1597
+ success: false,
1598
+ error: error instanceof Error ? error.message : 'Unknown error during push'
1599
+ };
1600
+ }
1601
+ }
1602
+ /**
1603
+ * Removes and returns the last element
1604
+ */
1605
+ pop() {
1606
+ if (this.size === 0) {
1607
+ return { success: false, error: 'Array is empty' };
1608
+ }
1609
+ const value = this.data[this.size - 1];
1610
+ this.size--;
1611
+ // Shrink array if it's too sparse
1612
+ if (this.size < this.capacity / (this.growthFactor * 2)) {
1613
+ this.resize(Math.max(16, Math.floor(this.capacity / this.growthFactor)));
1614
+ }
1615
+ return { success: true, value };
1616
+ }
1617
+ /**
1618
+ * Gets element at specified index
1619
+ */
1620
+ get(index) {
1621
+ if (index < 0 || index >= this.size) {
1622
+ return { success: false, error: 'Index out of bounds' };
1623
+ }
1624
+ return { success: true, value: this.data[index] };
1625
+ }
1626
+ /**
1627
+ * Sets element at specified index
1628
+ */
1629
+ set(index, value) {
1630
+ if (index < 0 || index >= this.size) {
1631
+ return { success: false, error: 'Index out of bounds' };
1632
+ }
1633
+ const oldValue = this.data[index];
1634
+ this.data[index] = value;
1635
+ this.updateSegmentTree(0, index, value);
1636
+ return { success: true, value: oldValue };
1637
+ }
1638
+ /**
1639
+ * Rebuilds the segment tree after major changes
1640
+ */
1641
+ rebuildSegmentTree() {
1642
+ this.segmentTree = new Array(4 * this.capacity).fill(null);
1643
+ if (this.size > 0) {
1644
+ this.buildSegmentTree(0, 0, this.size - 1);
1645
+ }
1646
+ }
1647
+ /**
1648
+ * Builds a segment tree node recursively
1649
+ */
1650
+ buildSegmentTree(node, start, end) {
1651
+ if (start === end) {
1652
+ this.segmentTree[node] = {
1653
+ value: this.data[start],
1654
+ start,
1655
+ end
1656
+ };
1657
+ return;
1658
+ }
1659
+ const mid = Math.floor((start + end) / 2);
1660
+ this.buildSegmentTree(2 * node + 1, start, mid);
1661
+ this.buildSegmentTree(2 * node + 2, mid + 1, end);
1662
+ const leftNode = this.segmentTree[2 * node + 1];
1663
+ const rightNode = this.segmentTree[2 * node + 2];
1664
+ if (leftNode && rightNode) {
1665
+ this.segmentTree[node] = {
1666
+ value: this.comparator(leftNode.value, rightNode.value) >= 0
1667
+ ? leftNode.value
1668
+ : rightNode.value,
1669
+ start,
1670
+ end
1671
+ };
1672
+ }
1673
+ }
1674
+ /**
1675
+ * Updates the segment tree after a value change
1676
+ */
1677
+ updateSegmentTree(node, index, value) {
1678
+ if (!this.segmentTree[node]) {
1679
+ return;
1680
+ }
1681
+ const currentNode = this.segmentTree[node];
1682
+ if (currentNode.start === currentNode.end) {
1683
+ currentNode.value = value;
1684
+ return;
1685
+ }
1686
+ const mid = Math.floor((currentNode.start + currentNode.end) / 2);
1687
+ if (index <= mid) {
1688
+ this.updateSegmentTree(2 * node + 1, index, value);
1689
+ }
1690
+ else {
1691
+ this.updateSegmentTree(2 * node + 2, index, value);
1692
+ }
1693
+ const leftNode = this.segmentTree[2 * node + 1];
1694
+ const rightNode = this.segmentTree[2 * node + 2];
1695
+ if (leftNode && rightNode) {
1696
+ currentNode.value = this.comparator(leftNode.value, rightNode.value) >= 0
1697
+ ? leftNode.value
1698
+ : rightNode.value;
1699
+ }
1700
+ }
1701
+ /**
1702
+ * Queries the maximum value in a range
1703
+ */
1704
+ queryRange(start, end) {
1705
+ if (start < 0 || end >= this.size || start > end) {
1706
+ return { success: false, error: 'Invalid range' };
1707
+ }
1708
+ const result = this.querySegmentTree(0, start, end);
1709
+ return result
1710
+ ? { success: true, value: result }
1711
+ : { success: false, error: 'Range query failed' };
1712
+ }
1713
+ /**
1714
+ * Recursively queries the segment tree
1715
+ */
1716
+ querySegmentTree(node, queryStart, queryEnd) {
1717
+ const currentNode = this.segmentTree[node];
1718
+ if (!currentNode) {
1719
+ return null;
1720
+ }
1721
+ if (queryStart <= currentNode.start && queryEnd >= currentNode.end) {
1722
+ return currentNode.value;
1723
+ }
1724
+ if (queryEnd < currentNode.start || queryStart > currentNode.end) {
1725
+ return null;
1726
+ }
1727
+ const leftResult = this.querySegmentTree(2 * node + 1, queryStart, queryEnd);
1728
+ const rightResult = this.querySegmentTree(2 * node + 2, queryStart, queryEnd);
1729
+ if (leftResult === null)
1730
+ return rightResult;
1731
+ if (rightResult === null)
1732
+ return leftResult;
1733
+ return this.comparator(leftResult, rightResult) >= 0 ? leftResult : rightResult;
1734
+ }
1735
+ /**
1736
+ * Creates a heap from the current array
1737
+ */
1738
+ toHeap(isMin = true) {
1739
+ const heap = isMin
1740
+ ? new MinHeap(this.comparator)
1741
+ : new MaxHeap(this.comparator);
1742
+ for (let i = 0; i < this.size; i++) {
1743
+ if (this.data[i] !== undefined) {
1744
+ if (this.data[i] !== undefined) {
1745
+ heap.push(this.data[i]);
1746
+ }
1747
+ }
1748
+ }
1749
+ return heap;
1750
+ }
1751
+ /**
1752
+ * Sorts the array in-place
1753
+ */
1754
+ sort(ascending = true) {
1755
+ const heap = this.toHeap(!ascending);
1756
+ for (let i = this.size - 1; i >= 0; i--) {
1757
+ const value = heap.pop();
1758
+ if (value !== undefined) {
1759
+ this.data[i] = value;
1760
+ }
1761
+ }
1762
+ this.rebuildSegmentTree();
1763
+ }
1764
+ /**
1765
+ * Returns array as native array
1766
+ */
1767
+ toArray() {
1768
+ return this.data.slice(0, this.size);
1769
+ }
1770
+ }
1771
+
1772
+ /**
1773
+ * Class representing a node in the number tree
1774
+ */
1775
+ class NumberNode {
1776
+ constructor(value) {
1777
+ this.value = typeof value === 'bigint' ? value : BigInt(value);
1778
+ this.left = null;
1779
+ this.right = null;
1780
+ this.parent = null;
1781
+ this.height = 1;
1782
+ this.size = 1;
1783
+ this.sum = this.value;
1784
+ }
1785
+ /**
1786
+ * Updates node statistics based on children
1787
+ */
1788
+ updateStats() {
1789
+ this.height = 1 + Math.max(this.left?.height ?? 0, this.right?.height ?? 0);
1790
+ this.size = 1 + (this.left?.size ?? 0) + (this.right?.size ?? 0);
1791
+ this.sum = this.value +
1792
+ (this.left?.sum ?? BigInt(0)) +
1793
+ (this.right?.sum ?? BigInt(0));
1794
+ }
1795
+ /**
1796
+ * Gets balance factor of the node
1797
+ */
1798
+ getBalance() {
1799
+ return (this.left?.height ?? 0) - (this.right?.height ?? 0);
1800
+ }
1801
+ /**
1802
+ * Gets complete statistics for the node and its subtree
1803
+ */
1804
+ getStats() {
1805
+ return {
1806
+ height: this.height,
1807
+ size: this.size,
1808
+ sum: this.sum,
1809
+ min: this.findMin().value,
1810
+ max: this.findMax().value
1811
+ };
1812
+ }
1813
+ /**
1814
+ * Finds minimum value node in the subtree
1815
+ */
1816
+ findMin() {
1817
+ let current = this;
1818
+ while (current.left) {
1819
+ current = current.left;
1820
+ }
1821
+ return current;
1822
+ }
1823
+ /**
1824
+ * Finds maximum value node in the subtree
1825
+ */
1826
+ findMax() {
1827
+ let current = this;
1828
+ while (current.right) {
1829
+ current = current.right;
1830
+ }
1831
+ return current;
1832
+ }
1833
+ }
1834
+ /**
1835
+ * AVL Tree implementation specialized for handling large numbers
1836
+ */
1837
+ class NumberTree {
1838
+ constructor(comparator) {
1839
+ this.root = null;
1840
+ this.comparator = comparator ?? ((a, b) => {
1841
+ if (a < b)
1842
+ return -1;
1843
+ if (a > b)
1844
+ return 1;
1845
+ return 0;
1846
+ });
1847
+ }
1848
+ /**
1849
+ * Gets the root node if it exists
1850
+ */
1851
+ getRoot() {
1852
+ return this.root;
1853
+ }
1854
+ /**
1855
+ * Inserts a new value into the tree
1856
+ */
1857
+ insert(value) {
1858
+ const newValue = typeof value === 'bigint' ? value : BigInt(value);
1859
+ this.root = this.insertNode(this.root, newValue);
1860
+ return this.find(newValue);
1861
+ }
1862
+ /**
1863
+ * Recursively inserts a new node
1864
+ */
1865
+ insertNode(node, value) {
1866
+ if (!node) {
1867
+ return new NumberNode(value);
1868
+ }
1869
+ const compareResult = this.comparator(value, node.value);
1870
+ if (compareResult < 0) {
1871
+ node.left = this.insertNode(node.left, value);
1872
+ node.left.parent = node;
1873
+ }
1874
+ else if (compareResult > 0) {
1875
+ node.right = this.insertNode(node.right, value);
1876
+ node.right.parent = node;
1877
+ }
1878
+ else {
1879
+ return node; // Duplicate value, return existing node
1880
+ }
1881
+ node.updateStats();
1882
+ return this.balance(node);
1883
+ }
1884
+ /**
1885
+ * Balances a node using AVL rotations
1886
+ */
1887
+ balance(node) {
1888
+ const balance = node.getBalance();
1889
+ // Left heavy
1890
+ if (balance > 1) {
1891
+ if (node.left && node.left.getBalance() < 0) {
1892
+ node.left = this.rotateLeft(node.left);
1893
+ }
1894
+ return this.rotateRight(node);
1895
+ }
1896
+ // Right heavy
1897
+ if (balance < -1) {
1898
+ if (node.right && node.right.getBalance() > 0) {
1899
+ node.right = this.rotateRight(node.right);
1900
+ }
1901
+ return this.rotateLeft(node);
1902
+ }
1903
+ return node;
1904
+ }
1905
+ /**
1906
+ * Performs left rotation
1907
+ */
1908
+ rotateLeft(node) {
1909
+ const rightChild = node.right;
1910
+ const rightLeftChild = rightChild.left;
1911
+ rightChild.left = node;
1912
+ node.right = rightLeftChild;
1913
+ if (rightLeftChild) {
1914
+ rightLeftChild.parent = node;
1915
+ }
1916
+ rightChild.parent = node.parent;
1917
+ node.parent = rightChild;
1918
+ node.updateStats();
1919
+ rightChild.updateStats();
1920
+ return rightChild;
1921
+ }
1922
+ /**
1923
+ * Performs right rotation
1924
+ */
1925
+ rotateRight(node) {
1926
+ const leftChild = node.left;
1927
+ const leftRightChild = leftChild.right;
1928
+ leftChild.right = node;
1929
+ node.left = leftRightChild;
1930
+ if (leftRightChild) {
1931
+ leftRightChild.parent = node;
1932
+ }
1933
+ leftChild.parent = node.parent;
1934
+ node.parent = leftChild;
1935
+ node.updateStats();
1936
+ leftChild.updateStats();
1937
+ return leftChild;
1938
+ }
1939
+ /**
1940
+ * Removes a value from the tree
1941
+ */
1942
+ remove(value) {
1943
+ const searchValue = typeof value === 'bigint' ? value : BigInt(value);
1944
+ const nodeToRemove = this.find(searchValue);
1945
+ if (!nodeToRemove) {
1946
+ return false;
1947
+ }
1948
+ this.root = this.removeNode(this.root, searchValue);
1949
+ return true;
1950
+ }
1951
+ /**
1952
+ * Recursively removes a node
1953
+ */
1954
+ removeNode(node, value) {
1955
+ if (!node) {
1956
+ return null;
1957
+ }
1958
+ const compareResult = this.comparator(value, node.value);
1959
+ if (compareResult < 0) {
1960
+ node.left = this.removeNode(node.left, value);
1961
+ if (node.left) {
1962
+ node.left.parent = node;
1963
+ }
1964
+ }
1965
+ else if (compareResult > 0) {
1966
+ node.right = this.removeNode(node.right, value);
1967
+ if (node.right) {
1968
+ node.right.parent = node;
1969
+ }
1970
+ }
1971
+ else {
1972
+ // Node to delete found
1973
+ if (!node.left) {
1974
+ return node.right;
1975
+ }
1976
+ if (!node.right) {
1977
+ return node.left;
1978
+ }
1979
+ // Node has two children
1980
+ const successor = node.right.findMin();
1981
+ node.value = successor.value;
1982
+ node.right = this.removeNode(node.right, successor.value);
1983
+ if (node.right) {
1984
+ node.right.parent = node;
1985
+ }
1986
+ }
1987
+ node.updateStats();
1988
+ return this.balance(node);
1989
+ }
1990
+ /**
1991
+ * Finds a node by value
1992
+ */
1993
+ find(value) {
1994
+ const searchValue = typeof value === 'bigint' ? value : BigInt(value);
1995
+ let current = this.root;
1996
+ while (current) {
1997
+ const compareResult = this.comparator(searchValue, current.value);
1998
+ if (compareResult === 0) {
1999
+ return current;
2000
+ }
2001
+ current = compareResult < 0 ? current.left : current.right;
2002
+ }
2003
+ return null;
2004
+ }
2005
+ /**
2006
+ * Traverses the tree in specified order and returns values
2007
+ */
2008
+ traverse(order = 'inOrder', config = {}) {
2009
+ const result = [];
2010
+ const traverse = (node, depth = 0) => {
2011
+ if (!node || (config.maxDepth !== undefined && depth >= config.maxDepth)) {
2012
+ return;
2013
+ }
2014
+ if (order === 'preOrder') {
2015
+ result.push(node.value);
2016
+ }
2017
+ if (!config.skipSubtrees) {
2018
+ traverse(node.left, depth + 1);
2019
+ }
2020
+ if (order === 'inOrder') {
2021
+ result.push(node.value);
2022
+ }
2023
+ if (!config.skipSubtrees) {
2024
+ traverse(node.right, depth + 1);
2025
+ }
2026
+ if (order === 'postOrder') {
2027
+ result.push(node.value);
2028
+ }
2029
+ };
2030
+ traverse(this.root);
2031
+ return result;
2032
+ }
2033
+ /**
2034
+ * Gets overall tree statistics
2035
+ */
2036
+ getTreeStats() {
2037
+ return this.root?.getStats() ?? null;
2038
+ }
2039
+ /**
2040
+ * Gets the nth smallest value in the tree
2041
+ */
2042
+ getNthValue(n) {
2043
+ if (!this.root || n < 1 || n > this.root.size) {
2044
+ return null;
2045
+ }
2046
+ const findNth = (node, position) => {
2047
+ if (!node) {
2048
+ return null;
2049
+ }
2050
+ const leftSize = node.left?.size ?? 0;
2051
+ if (position === leftSize + 1) {
2052
+ return node.value;
2053
+ }
2054
+ if (position <= leftSize) {
2055
+ return findNth(node.left, position);
2056
+ }
2057
+ return findNth(node.right, position - leftSize - 1);
2058
+ };
2059
+ return findNth(this.root, n);
2060
+ }
2061
+ /**
2062
+ * Gets a range of values between start and end (inclusive)
2063
+ */
2064
+ getRange(start, end) {
2065
+ const startValue = typeof start === 'bigint' ? start : BigInt(start);
2066
+ const endValue = typeof end === 'bigint' ? end : BigInt(end);
2067
+ const result = [];
2068
+ const collectRange = (node) => {
2069
+ if (!node) {
2070
+ return;
2071
+ }
2072
+ if (this.comparator(node.value, startValue) >= 0 &&
2073
+ this.comparator(node.value, endValue) <= 0) {
2074
+ collectRange(node.left);
2075
+ result.push(node.value);
2076
+ collectRange(node.right);
2077
+ }
2078
+ else if (this.comparator(node.value, startValue) > 0) {
2079
+ collectRange(node.left);
2080
+ }
2081
+ else {
2082
+ collectRange(node.right);
2083
+ }
2084
+ };
2085
+ collectRange(this.root);
2086
+ return result;
2087
+ }
2088
+ }
2089
+
2090
+ /**
2091
+ * Default options for power tower computations
2092
+ */
2093
+ const DEFAULT_OPTIONS$4 = {
2094
+ maxHeight: 100,
2095
+ maxValue: BigInt(Number.MAX_SAFE_INTEGER),
2096
+ checkOverflow: true,
2097
+ precision: 0
2098
+ };
2099
+ /**
2100
+ * Class representing a power tower (tetration) computation structure
2101
+ * Handles expressions of the form: a↑↑b = a^(a^(a^...)) (b times)
2102
+ */
2103
+ class PowerTower {
2104
+ constructor(options = {}) {
2105
+ this.options = { ...DEFAULT_OPTIONS$4, ...options };
2106
+ this.head = null;
2107
+ this.tail = null;
2108
+ this.size = 0;
2109
+ }
2110
+ /**
2111
+ * Creates a new power tower node
2112
+ */
2113
+ createNode(value, height) {
2114
+ return {
2115
+ value,
2116
+ height,
2117
+ evaluated: false,
2118
+ previous: null,
2119
+ next: null
2120
+ };
2121
+ }
2122
+ /**
2123
+ * Validates power tower height
2124
+ */
2125
+ validateHeight(height) {
2126
+ if (height < 0) {
2127
+ throw new ValidationError$1('Height cannot be negative');
2128
+ }
2129
+ if (height > this.options.maxHeight) {
2130
+ throw new ValidationError$1(`Height exceeds maximum of ${this.options.maxHeight}`);
2131
+ }
2132
+ }
2133
+ /**
2134
+ * Validates value for computation
2135
+ */
2136
+ validateValue(value) {
2137
+ validateNonNegative(value);
2138
+ if (this.options.checkOverflow && value > this.options.maxValue) {
2139
+ throw new OverflowError(`Value exceeds maximum of ${this.options.maxValue}`);
2140
+ }
2141
+ }
2142
+ /**
2143
+ * Computes power with overflow checking
2144
+ */
2145
+ computePower(base, exponent) {
2146
+ if (exponent === BigInt(0)) {
2147
+ return BigInt(1);
2148
+ }
2149
+ if (exponent === BigInt(1)) {
2150
+ return base;
2151
+ }
2152
+ let result = base;
2153
+ for (let i = BigInt(1); i < exponent; i++) {
2154
+ if (this.options.checkOverflow) {
2155
+ // Check if next multiplication would overflow
2156
+ const next = result * base;
2157
+ if (next > this.options.maxValue) {
2158
+ throw new OverflowError('Power computation would overflow');
2159
+ }
2160
+ result = next;
2161
+ }
2162
+ else {
2163
+ result *= base;
2164
+ }
2165
+ }
2166
+ return result;
2167
+ }
2168
+ /**
2169
+ * Builds a power tower of specified height with given base
2170
+ */
2171
+ build(base, height) {
2172
+ this.validateHeight(height);
2173
+ const baseValue = typeof base === 'bigint' ? base : BigInt(base);
2174
+ this.validateValue(baseValue);
2175
+ this.clear(); // Clear existing tower
2176
+ for (let i = 0; i < height; i++) {
2177
+ const node = this.createNode(baseValue, i + 1);
2178
+ if (!this.head) {
2179
+ this.head = node;
2180
+ this.tail = node;
2181
+ }
2182
+ else {
2183
+ node.previous = this.tail;
2184
+ this.tail.next = node;
2185
+ this.tail = node;
2186
+ }
2187
+ this.size++;
2188
+ }
2189
+ }
2190
+ /**
2191
+ * Evaluates the power tower up to specified height
2192
+ */
2193
+ evaluate(height) {
2194
+ if (!this.head) {
2195
+ return BigInt(1); // Empty tower evaluates to 1
2196
+ }
2197
+ const targetHeight = height ?? this.size;
2198
+ this.validateHeight(targetHeight);
2199
+ let current = this.head;
2200
+ let result = current.value;
2201
+ let currentHeight = 1;
2202
+ try {
2203
+ while (current.next && currentHeight < targetHeight) {
2204
+ result = this.computePower(current.next.value, result);
2205
+ current.evaluated = true;
2206
+ current = current.next;
2207
+ currentHeight++;
2208
+ }
2209
+ current.evaluated = true;
2210
+ return result;
2211
+ }
2212
+ catch (error) {
2213
+ if (error instanceof OverflowError) {
2214
+ // Mark nodes up to current height as evaluated
2215
+ let node = this.head;
2216
+ while (node !== current) {
2217
+ node.evaluated = true;
2218
+ node = node.next;
2219
+ }
2220
+ throw error;
2221
+ }
2222
+ throw error;
2223
+ }
2224
+ }
2225
+ /**
2226
+ * Gets the current height of the power tower
2227
+ */
2228
+ getHeight() {
2229
+ return this.size;
2230
+ }
2231
+ /**
2232
+ * Checks if the tower can be evaluated to a given height
2233
+ */
2234
+ isComputable(height) {
2235
+ try {
2236
+ const targetHeight = height ?? this.size;
2237
+ this.validateHeight(targetHeight);
2238
+ // Check first few levels without full computation
2239
+ let current = this.head;
2240
+ let currentHeight = 0;
2241
+ while (current && currentHeight < targetHeight) {
2242
+ // Quick check for obvious overflow conditions
2243
+ if (current.value > BigInt(4) && currentHeight > 3) {
2244
+ return false;
2245
+ }
2246
+ current = current.next;
2247
+ currentHeight++;
2248
+ }
2249
+ // Try actual computation with a lower overflow threshold
2250
+ const safeOptions = { ...this.options, maxValue: this.options.maxValue >> BigInt(1) };
2251
+ const safeTower = new PowerTower(safeOptions);
2252
+ safeTower.build(this.head.value, targetHeight);
2253
+ safeTower.evaluate();
2254
+ return true;
2255
+ }
2256
+ catch {
2257
+ return false;
2258
+ }
2259
+ }
2260
+ /**
2261
+ * Gets the computation state at each level
2262
+ */
2263
+ getState() {
2264
+ const state = [];
2265
+ let current = this.head;
2266
+ while (current) {
2267
+ state.push({
2268
+ height: current.height,
2269
+ value: current.value,
2270
+ evaluated: current.evaluated
2271
+ });
2272
+ current = current.next;
2273
+ }
2274
+ return state;
2275
+ }
2276
+ /**
2277
+ * Clears the power tower
2278
+ */
2279
+ clear() {
2280
+ this.head = null;
2281
+ this.tail = null;
2282
+ this.size = 0;
2283
+ }
2284
+ /**
2285
+ * Gets the maximum computationally feasible height for a given base
2286
+ */
2287
+ static getMaxFeasibleHeight(base) {
2288
+ const baseValue = typeof base === 'bigint' ? base : BigInt(base);
2289
+ validateNonNegative(baseValue);
2290
+ if (baseValue === BigInt(0))
2291
+ return 0;
2292
+ if (baseValue === BigInt(1))
2293
+ return Infinity;
2294
+ if (baseValue === BigInt(2))
2295
+ return 4; // 2↑↑4 is already enormous
2296
+ if (baseValue === BigInt(3))
2297
+ return 3; // 3↑↑3 is already astronomical
2298
+ if (baseValue === BigInt(4))
2299
+ return 2;
2300
+ return 1; // For bases > 4, only height 1 is reliably computable
2301
+ }
2302
+ /**
2303
+ * Creates a string representation of the power tower
2304
+ */
2305
+ toString() {
2306
+ if (!this.head) {
2307
+ return "Empty Tower";
2308
+ }
2309
+ let result = this.head.value.toString();
2310
+ let current = this.head;
2311
+ while (current.next) {
2312
+ result = `${current.next.value}^(${result})`;
2313
+ current = current.next;
2314
+ }
2315
+ return result;
2316
+ }
2317
+ }
2318
+
2319
+ /**
2320
+ * Formatting utilities for Hypernum library
2321
+ * Provides functions for formatting large numbers and converting between different representations
2322
+ */
2323
+ // Default formatting options
2324
+ const DEFAULT_OPTIONS$3 = {
2325
+ notation: 'standard',
2326
+ precision: 0,
2327
+ grouping: true,
2328
+ groupSize: 3,
2329
+ decimalSeparator: '.',
2330
+ groupSeparator: ',',
2331
+ };
2332
+ /**
2333
+ * Formats a BigInt value according to specified options
2334
+ */
2335
+ const formatBigInt = (value, options = {}) => {
2336
+ const opts = { ...DEFAULT_OPTIONS$3, ...options };
2337
+ // Handle negative numbers
2338
+ const isNegative = value < BigInt(0);
2339
+ const absValue = isNegative ? -value : value;
2340
+ let result;
2341
+ switch (opts.notation) {
2342
+ case 'scientific':
2343
+ result = formatScientific(absValue, opts).coefficient + 'e' +
2344
+ formatScientific(absValue, opts).exponent;
2345
+ break;
2346
+ case 'engineering':
2347
+ result = formatEngineering(absValue, opts);
2348
+ break;
2349
+ case 'compact':
2350
+ result = formatCompact(absValue, opts);
2351
+ break;
2352
+ default:
2353
+ result = formatStandard(absValue, opts);
2354
+ }
2355
+ return isNegative ? '-' + result : result;
2356
+ };
2357
+ /**
2358
+ * Formats a number in standard notation with grouping
2359
+ */
2360
+ const formatStandard = (value, options) => {
2361
+ let str = value.toString();
2362
+ if (!options.grouping) {
2363
+ return str;
2364
+ }
2365
+ // Apply grouping from the right
2366
+ const result = [];
2367
+ let position = str.length;
2368
+ while (position > 0) {
2369
+ const start = Math.max(0, position - options.groupSize);
2370
+ result.unshift(str.slice(start, position));
2371
+ position = start;
2372
+ }
2373
+ return result.join(options.groupSeparator);
2374
+ };
2375
+ /**
2376
+ * Converts a number to scientific notation
2377
+ */
2378
+ const formatScientific = (value, options) => {
2379
+ if (value === BigInt(0)) {
2380
+ return { coefficient: '0', exponent: 0 };
2381
+ }
2382
+ const str = value.toString();
2383
+ const exponent = str.length - 1;
2384
+ let coefficient = str[0] || '';
2385
+ coefficient += options.decimalSeparator + str.slice(1, options.precision + 1);
2386
+ return {
2387
+ coefficient: coefficient,
2388
+ exponent: exponent,
2389
+ };
2390
+ };
2391
+ /**
2392
+ * Formats a number in engineering notation (exponents divisible by 3)
2393
+ */
2394
+ const formatEngineering = (value, options) => {
2395
+ if (value === BigInt(0)) {
2396
+ return '0';
2397
+ }
2398
+ const str = value.toString();
2399
+ const len = str.length;
2400
+ const exponent = Math.floor((len - 1) / 3) * 3;
2401
+ let coefficient = '';
2402
+ const digitsBeforePoint = len - exponent;
2403
+ for (let i = 0; i < Math.min(len, digitsBeforePoint + options.precision); i++) {
2404
+ if (i === digitsBeforePoint && i < len) {
2405
+ coefficient += options.decimalSeparator;
2406
+ }
2407
+ coefficient += str[i];
2408
+ }
2409
+ return `${coefficient}e${exponent}`;
2410
+ };
2411
+ /**
2412
+ * Formats a number in compact notation (K, M, B, T)
2413
+ */
2414
+ const formatCompact = (value, options) => {
2415
+ const suffixes = ['', 'K', 'M', 'B', 'T', 'Q'];
2416
+ const str = value.toString();
2417
+ const len = str.length;
2418
+ if (len <= 3) {
2419
+ return formatStandard(value, options);
2420
+ }
2421
+ const suffixIndex = Math.min(Math.floor((len - 1) / 3), suffixes.length - 1);
2422
+ const suffix = suffixes[suffixIndex];
2423
+ const scale = BigInt(10) ** BigInt(suffixIndex * 3);
2424
+ const scaledValue = value / scale;
2425
+ let result = scaledValue.toString();
2426
+ if (options.precision > 0) {
2427
+ const remainder = value % scale;
2428
+ if (remainder > BigInt(0)) {
2429
+ const decimalPart = remainder.toString().padStart(3, '0').slice(0, options.precision);
2430
+ result += options.decimalSeparator + decimalPart;
2431
+ }
2432
+ }
2433
+ return result + suffix;
2434
+ };
2435
+ /**
2436
+ * Parses a formatted string back to BigInt
2437
+ */
2438
+ const parseBigIntString = (str, options = {}) => {
2439
+ const opts = { ...DEFAULT_OPTIONS$3, ...options };
2440
+ // Remove grouping separators
2441
+ let cleanStr = str.replace(new RegExp(`\\${opts.groupSeparator}`, 'g'), '');
2442
+ // Handle scientific notation
2443
+ if (cleanStr.toLowerCase().includes('e')) {
2444
+ const [coefficient, exponent] = cleanStr.toLowerCase().split('e');
2445
+ const base = BigInt(10);
2446
+ const exp = BigInt(exponent || '0');
2447
+ return BigInt(Math.floor(Number(coefficient))) * (base ** exp);
2448
+ }
2449
+ // Handle suffixes
2450
+ const suffixMap = new Map([
2451
+ ['k', BigInt(1000)],
2452
+ ['m', BigInt(1000000)],
2453
+ ['b', BigInt(1000000000)],
2454
+ ['t', BigInt(1000000000000)],
2455
+ ['q', BigInt(1000000000000000)],
2456
+ ]);
2457
+ const suffix = cleanStr.slice(-1).toLowerCase();
2458
+ const multiplier = suffixMap.get(suffix);
2459
+ if (multiplier) {
2460
+ cleanStr = cleanStr.slice(0, -1);
2461
+ const value = BigInt(Math.floor(Number(cleanStr)));
2462
+ return value * multiplier;
2463
+ }
2464
+ // Handle regular numbers
2465
+ return BigInt(cleanStr);
2466
+ };
2467
+ /**
2468
+ * Normalizes a string representation for comparison
2469
+ */
2470
+ const normalizeNumberString = (str) => {
2471
+ // Remove all spaces and separators
2472
+ str = str.replace(/[\s,]/g, '');
2473
+ // Handle scientific notation
2474
+ if (str.toLowerCase().includes('e')) {
2475
+ const [coefficient, exponent] = str.toLowerCase().split('e');
2476
+ const exp = parseInt(exponent || '0');
2477
+ const coef = parseFloat(coefficient || '0');
2478
+ return (coef * Math.pow(10, exp)).toString();
2479
+ }
2480
+ return str;
2481
+ };
2482
+
2483
+ /**
2484
+ * Main Hypernum class that provides a high-level interface to all library functionality
2485
+ */
2486
+ class Hypernum {
2487
+ constructor(config = {}) {
2488
+ this.config = {
2489
+ precision: config.precision ?? DEFAULT_OPTIONS$8.precision,
2490
+ roundingMode: config.roundingMode ?? DEFAULT_OPTIONS$8.roundingMode,
2491
+ checkOverflow: config.checkOverflow ?? DEFAULT_OPTIONS$8.checkOverflow,
2492
+ maxSteps: config.maxSteps ?? DEFAULT_OPTIONS$8.maxSteps,
2493
+ debug: config.debug ?? FEATURES.DEBUG_MODE
2494
+ };
2495
+ // Validate configuration
2496
+ if (this.config.precision < 0 || this.config.precision > MAX_PRECISION) {
2497
+ throw new ValidationError(`Precision must be between 0 and ${MAX_PRECISION}`);
2498
+ }
2499
+ if (this.config.maxSteps < 1 || this.config.maxSteps > MAX_COMPUTATION_STEPS) {
2500
+ throw new ValidationError(`Max steps must be between 1 and ${MAX_COMPUTATION_STEPS}`);
2501
+ }
2502
+ // Initialize data structure storage
2503
+ this.structures = {
2504
+ arrays: new Map(),
2505
+ trees: new Map(),
2506
+ heaps: new Map()
2507
+ };
2508
+ }
2509
+ // Arithmetic Operations
2510
+ add(a, b) {
2511
+ return add(a, b, this.config);
2512
+ }
2513
+ subtract(a, b) {
2514
+ return subtract(a, b, this.config);
2515
+ }
2516
+ multiply(a, b) {
2517
+ return multiply(a, b, this.config);
2518
+ }
2519
+ divide(a, b) {
2520
+ return divide(a, b, this.config);
2521
+ }
2522
+ mod(a, b) {
2523
+ return remainder(a, b, this.config);
2524
+ }
2525
+ // Power Operations
2526
+ power(base, exponent) {
2527
+ return power(base, exponent, this.config);
2528
+ }
2529
+ sqrt(value) {
2530
+ return sqrt(value, this.config);
2531
+ }
2532
+ nthRoot(value, n) {
2533
+ return nthRoot(value, n, this.config);
2534
+ }
2535
+ // Bitwise Operations
2536
+ and(a, b) {
2537
+ return and(a, b);
2538
+ }
2539
+ or(a, b) {
2540
+ return or(a, b);
2541
+ }
2542
+ xor(a, b) {
2543
+ return xor(a, b);
2544
+ }
2545
+ not(value) {
2546
+ return not(value);
2547
+ }
2548
+ /**
2549
+ * Calculates the greatest common divisor of two numbers
2550
+ */
2551
+ gcd(a, b) {
2552
+ return gcd(a, b);
2553
+ }
2554
+ /**
2555
+ * Calculates the least common multiple of two numbers
2556
+ */
2557
+ lcm(a, b) {
2558
+ return lcm(a, b);
2559
+ }
2560
+ // Data Structure Management
2561
+ createArray(id) {
2562
+ if (this.structures.arrays.has(id)) {
2563
+ throw new ValidationError(`Array with id '${id}' already exists`);
2564
+ }
2565
+ const array = new BigArray();
2566
+ this.structures.arrays.set(id, array);
2567
+ return array;
2568
+ }
2569
+ getArray(id) {
2570
+ const array = this.structures.arrays.get(id);
2571
+ if (!array) {
2572
+ throw new ValidationError(`Array with id '${id}' not found`);
2573
+ }
2574
+ return array;
2575
+ }
2576
+ createTree(id) {
2577
+ if (this.structures.trees.has(id)) {
2578
+ throw new ValidationError(`Tree with id '${id}' already exists`);
2579
+ }
2580
+ const tree = new NumberTree();
2581
+ this.structures.trees.set(id, tree);
2582
+ return tree;
2583
+ }
2584
+ getTree(id) {
2585
+ const tree = this.structures.trees.get(id);
2586
+ if (!tree) {
2587
+ throw new ValidationError(`Tree with id '${id}' not found`);
2588
+ }
2589
+ return tree;
2590
+ }
2591
+ createHeap(id, isMinHeap = true) {
2592
+ if (this.structures.heaps.has(id)) {
2593
+ throw new ValidationError(`Heap with id '${id}' already exists`);
2594
+ }
2595
+ const heap = isMinHeap ? new MinHeap(this.compareValues) : new MaxHeap(this.compareValues);
2596
+ this.structures.heaps.set(id, heap);
2597
+ return heap;
2598
+ }
2599
+ getHeap(id) {
2600
+ const heap = this.structures.heaps.get(id);
2601
+ if (!heap) {
2602
+ throw new ValidationError(`Heap with id '${id}' not found`);
2603
+ }
2604
+ return heap;
2605
+ }
2606
+ // Special Functions
2607
+ createAckermannStructure() {
2608
+ return new AckermannStructure();
2609
+ }
2610
+ // Formatting and Validation
2611
+ format(value, options) {
2612
+ const bigValue = toBigInt(value);
2613
+ return formatBigInt(bigValue, options);
2614
+ }
2615
+ validate(value) {
2616
+ try {
2617
+ toBigInt(value);
2618
+ return true;
2619
+ }
2620
+ catch {
2621
+ return false;
2622
+ }
2623
+ }
2624
+ // Configuration Management
2625
+ updateConfig(newConfig) {
2626
+ Object.assign(this.config, newConfig);
2627
+ }
2628
+ getConfig() {
2629
+ return { ...this.config };
2630
+ }
2631
+ // Utility Functions
2632
+ compareValues(a, b) {
2633
+ if (a < b)
2634
+ return -1;
2635
+ if (a > b)
2636
+ return 1;
2637
+ return 0;
2638
+ }
2639
+ // Cleanup
2640
+ dispose() {
2641
+ this.structures.arrays.clear();
2642
+ this.structures.trees.clear();
2643
+ this.structures.heaps.clear();
2644
+ }
2645
+ }
2646
+
2647
+ /**
2648
+ * Comparison operations module for Hypernum library
2649
+ * Provides functions for comparing large numbers with precision support
2650
+ */
2651
+ const DEFAULT_OPTIONS$2 = {
2652
+ precision: 0,
2653
+ roundingMode: exports.RoundingMode.HALF_EVEN,
2654
+ tolerance: 0
2655
+ };
2656
+ /**
2657
+ * Compares two numbers with optional precision
2658
+ */
2659
+ function compare(a, b, options = {}) {
2660
+ const opts = { ...DEFAULT_OPTIONS$2, ...options };
2661
+ const bigA = toBigInt(a);
2662
+ const bigB = toBigInt(b);
2663
+ if (opts.precision === 0 && opts.tolerance === 0) {
2664
+ if (bigA < bigB)
2665
+ return -1;
2666
+ if (bigA > bigB)
2667
+ return 1;
2668
+ return 0;
2669
+ }
2670
+ const [scaledA, scaledB] = normalizePrecision(bigA, bigB, opts.precision, opts.precision);
2671
+ if (opts.tolerance > 0) {
2672
+ const diff = scaledA - scaledB;
2673
+ const toleranceValue = BigInt(10) ** BigInt(opts.tolerance);
2674
+ if (diff < -toleranceValue)
2675
+ return -1;
2676
+ if (diff > toleranceValue)
2677
+ return 1;
2678
+ return 0;
2679
+ }
2680
+ if (scaledA < scaledB)
2681
+ return -1;
2682
+ if (scaledA > scaledB)
2683
+ return 1;
2684
+ return 0;
2685
+ }
2686
+ /**
2687
+ * Checks if two numbers are equal
2688
+ */
2689
+ function equals(a, b, options = {}) {
2690
+ return compare(a, b, options) === 0;
2691
+ }
2692
+ /**
2693
+ * Checks if first number is less than second
2694
+ */
2695
+ function lessThan(a, b, options = {}) {
2696
+ return compare(a, b, options) === -1;
2697
+ }
2698
+ /**
2699
+ * Checks if first number is less than or equal to second
2700
+ */
2701
+ function lessThanOrEqual(a, b, options = {}) {
2702
+ const result = compare(a, b, options);
2703
+ return result === -1 || result === 0;
2704
+ }
2705
+ /**
2706
+ * Checks if first number is greater than second
2707
+ */
2708
+ function greaterThan(a, b, options = {}) {
2709
+ return compare(a, b, options) === 1;
2710
+ }
2711
+ /**
2712
+ * Checks if first number is greater than or equal to second
2713
+ */
2714
+ function greaterThanOrEqual(a, b, options = {}) {
2715
+ const result = compare(a, b, options);
2716
+ return result === 1 || result === 0;
2717
+ }
2718
+ /**
2719
+ * Checks if a number is between two others (inclusive)
2720
+ */
2721
+ function between(value, min, max, options = {}) {
2722
+ return greaterThanOrEqual(value, min, options) && lessThanOrEqual(value, max, options);
2723
+ }
2724
+ /**
2725
+ * Finds the maximum value in an array of numbers
2726
+ */
2727
+ function max(values, options = {}) {
2728
+ if (values.length === 0) {
2729
+ throw new ValidationError$1('Cannot find maximum of empty array');
2730
+ }
2731
+ return values.reduce((max, current) => {
2732
+ const bigMax = toBigInt(max);
2733
+ const bigCurrent = toBigInt(current);
2734
+ return greaterThan(bigCurrent, bigMax, options) ? bigCurrent : bigMax;
2735
+ }, toBigInt(values[0]));
2736
+ }
2737
+ /**
2738
+ * Finds the minimum value in an array of numbers
2739
+ */
2740
+ function min(values, options = {}) {
2741
+ if (values.length === 0) {
2742
+ throw new ValidationError$1('Cannot find minimum of empty array');
2743
+ }
2744
+ return values.reduce((min, current) => {
2745
+ const bigMin = toBigInt(min);
2746
+ const bigCurrent = toBigInt(current);
2747
+ return lessThan(bigCurrent, bigMin, options) ? bigCurrent : bigMin;
2748
+ }, toBigInt(values[0]));
2749
+ }
2750
+ /**
2751
+ * Clamps a value between minimum and maximum bounds
2752
+ */
2753
+ function clamp(value, min, max, options = {}) {
2754
+ const bigValue = toBigInt(value);
2755
+ const bigMin = toBigInt(min);
2756
+ const bigMax = toBigInt(max);
2757
+ if (lessThan(bigMax, bigMin, options)) {
2758
+ throw new ValidationError$1('Maximum bound must be greater than or equal to minimum bound');
2759
+ }
2760
+ if (lessThan(bigValue, bigMin, options))
2761
+ return bigMin;
2762
+ if (greaterThan(bigValue, bigMax, options))
2763
+ return bigMax;
2764
+ return bigValue;
2765
+ }
2766
+ /**
2767
+ * Checks if all values in array are equal within tolerance
2768
+ */
2769
+ function allEqual(values, options = {}) {
2770
+ if (values.length <= 1)
2771
+ return true;
2772
+ const first = toBigInt(values[0]);
2773
+ return values.every(value => equals(value, first, options));
2774
+ }
2775
+ /**
2776
+ * Checks if values are in ascending order
2777
+ */
2778
+ function isAscending(values, options = {}) {
2779
+ if (values.length <= 1)
2780
+ return true;
2781
+ for (let i = 1; i < values.length; i++) {
2782
+ if (values[i] === undefined || values[i - 1] === undefined || !greaterThanOrEqual(values[i], values[i - 1], options)) {
2783
+ return false;
2784
+ }
2785
+ }
2786
+ return true;
2787
+ }
2788
+ /**
2789
+ * Checks if values are in descending order
2790
+ */
2791
+ function isDescending(values, options = {}) {
2792
+ if (values.length <= 1)
2793
+ return true;
2794
+ for (let i = 1; i < values.length; i++) {
2795
+ if (values[i] === undefined || values[i - 1] === undefined || !lessThanOrEqual(values[i], values[i - 1], options)) {
2796
+ return false;
2797
+ }
2798
+ }
2799
+ return true;
2800
+ }
2801
+ /**
2802
+ * Creates a comparator function for sorting
2803
+ */
2804
+ function createComparator(options = {}) {
2805
+ return (a, b) => compare(a, b, options);
2806
+ }
2807
+
2808
+ /**
2809
+ * Conversion operations module for Hypernum library
2810
+ * Provides functions for converting numbers between different formats and bases
2811
+ */
2812
+ const DEFAULT_OPTIONS$1 = {
2813
+ precision: 0,
2814
+ roundingMode: exports.RoundingMode.HALF_EVEN,
2815
+ uppercase: false,
2816
+ prefix: false,
2817
+ minDigits: 1
2818
+ };
2819
+ /**
2820
+ * Converts number to binary string representation
2821
+ */
2822
+ function toBinary(value, options = {}) {
2823
+ const opts = { ...DEFAULT_OPTIONS$1, ...options };
2824
+ const bigValue = toBigInt(value);
2825
+ let binary = bigValue.toString(2);
2826
+ // Pad with zeros if needed
2827
+ while (binary.length < opts.minDigits) {
2828
+ binary = '0' + binary;
2829
+ }
2830
+ return opts.prefix ? '0b' + binary : binary;
2831
+ }
2832
+ /**
2833
+ * Converts number to octal string representation
2834
+ */
2835
+ function toOctal(value, options = {}) {
2836
+ const opts = { ...DEFAULT_OPTIONS$1, ...options };
2837
+ const bigValue = toBigInt(value);
2838
+ let octal = bigValue.toString(8);
2839
+ while (octal.length < opts.minDigits) {
2840
+ octal = '0' + octal;
2841
+ }
2842
+ return opts.prefix ? '0o' + octal : octal;
2843
+ }
2844
+ /**
2845
+ * Converts number to hexadecimal string representation
2846
+ */
2847
+ function toHexadecimal(value, options = {}) {
2848
+ const opts = { ...DEFAULT_OPTIONS$1, ...options };
2849
+ const bigValue = toBigInt(value);
2850
+ let hex = bigValue.toString(16);
2851
+ if (opts.uppercase) {
2852
+ hex = hex.toUpperCase();
2853
+ }
2854
+ while (hex.length < opts.minDigits) {
2855
+ hex = '0' + hex;
2856
+ }
2857
+ return opts.prefix ? '0x' + hex : hex;
2858
+ }
2859
+ /**
2860
+ * Converts number to string in specified base
2861
+ */
2862
+ function toBase(value, base, options = {}) {
2863
+ if (base < 2 || base > 36) {
2864
+ throw new ValidationError$1('Base must be between 2 and 36');
2865
+ }
2866
+ const opts = { ...DEFAULT_OPTIONS$1, ...options };
2867
+ const bigValue = toBigInt(value);
2868
+ let result = bigValue.toString(base);
2869
+ if (opts.uppercase) {
2870
+ result = result.toUpperCase();
2871
+ }
2872
+ while (result.length < opts.minDigits) {
2873
+ result = '0' + result;
2874
+ }
2875
+ return result;
2876
+ }
2877
+ /**
2878
+ * Converts string from specified base to bigint
2879
+ */
2880
+ function fromBase(value, base) {
2881
+ if (base < 2 || base > 36) {
2882
+ throw new ValidationError$1('Base must be between 2 and 36');
2883
+ }
2884
+ // Remove base prefixes if present
2885
+ const cleanValue = value.toLowerCase()
2886
+ .replace(/^0x/, '') // hex
2887
+ .replace(/^0b/, '') // binary
2888
+ .replace(/^0o/, ''); // octal
2889
+ try {
2890
+ return BigInt(`${base}n${cleanValue}`);
2891
+ }
2892
+ catch (error) {
2893
+ throw new ValidationError$1(`Invalid number format for base ${base}: ${value}`);
2894
+ }
2895
+ }
2896
+ /**
2897
+ * Converts decimal string to fraction representation
2898
+ */
2899
+ function toFraction(value) {
2900
+ // Split into integer and decimal parts
2901
+ const [intPart, decPart = ''] = value.split('.');
2902
+ if (!decPart) {
2903
+ return [toBigInt(intPart), 1n];
2904
+ }
2905
+ // Convert decimal to fraction
2906
+ const numerator = toBigInt(intPart + decPart);
2907
+ const denominator = 10n ** BigInt(decPart.length);
2908
+ // Simplify fraction
2909
+ const gcd = calculateGCD(numerator, denominator);
2910
+ return [numerator / gcd, denominator / gcd];
2911
+ }
2912
+ /**
2913
+ * Converts fraction to decimal string with specified precision
2914
+ */
2915
+ function fromFraction(numerator, denominator, options = {}) {
2916
+ const opts = { ...DEFAULT_OPTIONS$1, ...options };
2917
+ const bigNumerator = toBigInt(numerator);
2918
+ const bigDenominator = toBigInt(denominator);
2919
+ if (bigDenominator === 0n) {
2920
+ throw new ValidationError$1('Denominator cannot be zero');
2921
+ }
2922
+ const quotient = bigNumerator / bigDenominator;
2923
+ const remainder = bigNumerator % bigDenominator;
2924
+ if (remainder === 0n || opts.precision === 0) {
2925
+ return quotient.toString();
2926
+ }
2927
+ // Calculate decimal part
2928
+ const scaleFactor = 10n ** BigInt(opts.precision);
2929
+ const scaledRemainder = (remainder * scaleFactor) / bigDenominator;
2930
+ return `${quotient}.${scaledRemainder.toString().padStart(opts.precision, '0')}`;
2931
+ }
2932
+ /**
2933
+ * Converts scientific notation to decimal string
2934
+ */
2935
+ function fromScientific(value) {
2936
+ // Parse scientific notation format
2937
+ const match = value.match(/^(-?\d+\.?\d*)[eE]([+-]?\d+)$/);
2938
+ if (!match) {
2939
+ throw new ValidationError$1('Invalid scientific notation format');
2940
+ }
2941
+ const [, significand, exponent] = match;
2942
+ const exp = parseInt(exponent || '0', 10);
2943
+ // Convert to regular decimal
2944
+ if (exp >= 0) {
2945
+ if (significand === undefined) {
2946
+ throw new ValidationError$1('Invalid scientific notation format');
2947
+ }
2948
+ return (BigInt(significand.replace('.', '')) * (10n ** BigInt(exp))).toString();
2949
+ }
2950
+ else {
2951
+ const absExp = Math.abs(exp);
2952
+ if (significand === undefined) {
2953
+ throw new ValidationError$1('Invalid scientific notation format');
2954
+ }
2955
+ const scaledValue = BigInt(significand.replace('.', ''));
2956
+ return (scaledValue / (10n ** BigInt(absExp))).toString();
2957
+ }
2958
+ }
2959
+ /**
2960
+ * Converts decimal to scientific notation
2961
+ */
2962
+ function toScientific(value, options = {}) {
2963
+ const opts = { ...DEFAULT_OPTIONS$1, ...options };
2964
+ const bigValue = toBigInt(value);
2965
+ if (bigValue === 0n) {
2966
+ return '0e0';
2967
+ }
2968
+ const str = bigValue.toString();
2969
+ const firstDigit = str[0] === '-' ? str[1] : str[0];
2970
+ const exponent = str.length - (str[0] === '-' ? 2 : 1);
2971
+ let result = firstDigit;
2972
+ if (str.length > 1) {
2973
+ const restDigits = str.slice(str[0] === '-' ? 2 : 1);
2974
+ if (opts.precision > 0) {
2975
+ result += '.' + restDigits.slice(0, opts.precision);
2976
+ }
2977
+ }
2978
+ if (str[0] === '-') {
2979
+ result = '-' + result;
2980
+ }
2981
+ return `${result}e${exponent}`;
2982
+ }
2983
+ /**
2984
+ * Calculates Greatest Common Divisor (helper function)
2985
+ */
2986
+ function calculateGCD(a, b) {
2987
+ a = a < 0n ? -a : a;
2988
+ b = b < 0n ? -b : b;
2989
+ while (b !== 0n) {
2990
+ const temp = b;
2991
+ b = a % b;
2992
+ a = temp;
2993
+ }
2994
+ return a;
2995
+ }
2996
+ /**
2997
+ * Converts Roman numeral to number
2998
+ */
2999
+ function fromRoman(value) {
3000
+ const romanValues = new Map([
3001
+ ['I', 1],
3002
+ ['V', 5],
3003
+ ['X', 10],
3004
+ ['L', 50],
3005
+ ['C', 100],
3006
+ ['D', 500],
3007
+ ['M', 1000]
3008
+ ]);
3009
+ let result = 0;
3010
+ let prevValue = 0;
3011
+ // Process from right to left
3012
+ for (let i = value.length - 1; i >= 0; i--) {
3013
+ const char = value[i]?.toUpperCase() ?? '';
3014
+ const current = romanValues.get(char);
3015
+ if (current === undefined) {
3016
+ throw new ValidationError$1(`Invalid Roman numeral character: ${char}`);
3017
+ }
3018
+ if (current >= prevValue) {
3019
+ result += current;
3020
+ }
3021
+ else {
3022
+ result -= current;
3023
+ }
3024
+ prevValue = current;
3025
+ }
3026
+ return BigInt(result);
3027
+ }
3028
+ /**
3029
+ * Converts number to Roman numeral
3030
+ */
3031
+ function toRoman(value, options = {}) {
3032
+ const opts = { ...DEFAULT_OPTIONS$1, ...options };
3033
+ const num = Number(toBigInt(value));
3034
+ if (num <= 0 || num > 3999) {
3035
+ throw new ValidationError$1('Number must be between 1 and 3999 for Roman numerals');
3036
+ }
3037
+ const romanSymbols = [
3038
+ ['I', 'V'], // ones
3039
+ ['X', 'L'], // tens
3040
+ ['C', 'D'], // hundreds
3041
+ ['M'] // thousands
3042
+ ];
3043
+ let result = '';
3044
+ let position = 0;
3045
+ let remaining = num;
3046
+ while (remaining > 0) {
3047
+ const digit = remaining % 10;
3048
+ const symbols = romanSymbols[position];
3049
+ if (!symbols) {
3050
+ break; // Safety check for position overflow
3051
+ }
3052
+ const unit = symbols[0];
3053
+ const five = symbols[1] ?? '';
3054
+ const next = position < 3 ? romanSymbols[position + 1]?.[0] ?? '' : '';
3055
+ let digitStr = '';
3056
+ if (digit === 9 && next) {
3057
+ digitStr = unit + next;
3058
+ }
3059
+ else if (digit >= 5 && five) {
3060
+ digitStr = five + unit.repeat(digit - 5);
3061
+ }
3062
+ else if (digit === 4 && five) {
3063
+ digitStr = unit + five;
3064
+ }
3065
+ else {
3066
+ digitStr = unit.repeat(digit);
3067
+ }
3068
+ result = digitStr + result;
3069
+ remaining = Math.floor(remaining / 10);
3070
+ position++;
3071
+ }
3072
+ return opts.uppercase ? result : result.toLowerCase();
3073
+ }
3074
+
3075
+ /**
3076
+ * Factorial operations module for Hypernum library
3077
+ * Provides efficient implementations for factorial and related computations
3078
+ */
3079
+ const DEFAULT_OPTIONS = {
3080
+ maxValue: 1000,
3081
+ checkOverflow: true,
3082
+ useCache: true
3083
+ };
3084
+ // Cache for factorial values
3085
+ const factorialCache = new Map();
3086
+ /**
3087
+ * Calculates factorial of a number (n!)
3088
+ */
3089
+ function factorial(value, options = {}) {
3090
+ const opts = { ...DEFAULT_OPTIONS, ...options };
3091
+ const n = toBigInt(value);
3092
+ validateNonNegative(n);
3093
+ if (opts.checkOverflow && n > BigInt(opts.maxValue)) {
3094
+ throw new OverflowError(`Factorial input too large: maximum allowed is ${opts.maxValue}`);
3095
+ }
3096
+ // Handle base cases
3097
+ if (n <= 1n) {
3098
+ return 1n;
3099
+ }
3100
+ // Check cache
3101
+ if (opts.useCache && factorialCache.has(n)) {
3102
+ return factorialCache.get(n);
3103
+ }
3104
+ // Calculate factorial
3105
+ let result = 1n;
3106
+ for (let i = 2n; i <= n; i++) {
3107
+ result *= i;
3108
+ }
3109
+ // Cache result
3110
+ if (opts.useCache) {
3111
+ factorialCache.set(n, result);
3112
+ }
3113
+ return result;
3114
+ }
3115
+ /**
3116
+ * Calculates binomial coefficient (n choose k)
3117
+ */
3118
+ function binomial(n, k, options = {}) {
3119
+ const opts = { ...DEFAULT_OPTIONS, ...options };
3120
+ const bigN = toBigInt(n);
3121
+ const bigK = toBigInt(k);
3122
+ validateNonNegative(bigN);
3123
+ validateNonNegative(bigK);
3124
+ if (bigK > bigN) {
3125
+ throw new ValidationError$1('K cannot be greater than N in binomial coefficient');
3126
+ }
3127
+ // Optimize for k > n/2 by using symmetry
3128
+ if (bigK > bigN / 2n) {
3129
+ return binomial(bigN, bigN - bigK, opts);
3130
+ }
3131
+ // Use multiplicative formula instead of factorial for efficiency
3132
+ let result = 1n;
3133
+ for (let i = 0n; i < bigK; i++) {
3134
+ result = (result * (bigN - i)) / (i + 1n);
3135
+ }
3136
+ return result;
3137
+ }
3138
+ /**
3139
+ * Calculates subfactorial (derangement number)
3140
+ * Number of permutations of n elements with no fixed points
3141
+ */
3142
+ function subfactorial(value, options = {}) {
3143
+ const opts = { ...DEFAULT_OPTIONS, ...options };
3144
+ const n = toBigInt(value);
3145
+ validateNonNegative(n);
3146
+ if (opts.checkOverflow && n > BigInt(opts.maxValue)) {
3147
+ throw new OverflowError(`Subfactorial input too large: maximum allowed is ${opts.maxValue}`);
3148
+ }
3149
+ // Handle base cases
3150
+ if (n === 0n)
3151
+ return 1n;
3152
+ if (n === 1n)
3153
+ return 0n;
3154
+ // Use recursive formula !n = n * !(n-1) + (-1)^n
3155
+ let result = 0n;
3156
+ const nFact = factorial(n, opts);
3157
+ for (let k = 0n; k <= n; k++) {
3158
+ const term = factorial(n - k, opts) * (k % 2n === 0n ? 1n : -1n);
3159
+ result += term;
3160
+ }
3161
+ return nFact - result;
3162
+ }
3163
+ /**
3164
+ * Calculates rising factorial (Pochhammer symbol)
3165
+ * x^(n) = x(x+1)(x+2)...(x+n-1)
3166
+ */
3167
+ function risingFactorial(x, n, options = {}) {
3168
+ const opts = { ...DEFAULT_OPTIONS, ...options };
3169
+ const bigX = toBigInt(x);
3170
+ const bigN = toBigInt(n);
3171
+ validateNonNegative(bigN);
3172
+ if (opts.checkOverflow && bigN > BigInt(opts.maxValue)) {
3173
+ throw new OverflowError(`Rising factorial input too large: maximum allowed is ${opts.maxValue}`);
3174
+ }
3175
+ let result = 1n;
3176
+ for (let i = 0n; i < bigN; i++) {
3177
+ result *= (bigX + i);
3178
+ }
3179
+ return result;
3180
+ }
3181
+ /**
3182
+ * Calculates falling factorial
3183
+ * x_(n) = x(x-1)(x-2)...(x-n+1)
3184
+ */
3185
+ function fallingFactorial(x, n, options = {}) {
3186
+ const opts = { ...DEFAULT_OPTIONS, ...options };
3187
+ const bigX = toBigInt(x);
3188
+ const bigN = toBigInt(n);
3189
+ validateNonNegative(bigN);
3190
+ if (opts.checkOverflow && bigN > BigInt(opts.maxValue)) {
3191
+ throw new OverflowError(`Falling factorial input too large: maximum allowed is ${opts.maxValue}`);
3192
+ }
3193
+ let result = 1n;
3194
+ for (let i = 0n; i < bigN; i++) {
3195
+ result *= (bigX - i);
3196
+ }
3197
+ return result;
3198
+ }
3199
+ /**
3200
+ * Calculates multifactorial (n!!)
3201
+ * Product of numbers from 1 to n that leave the same remainder as n when divided by k
3202
+ */
3203
+ function multiFactorial(value, k = 2n, options = {}) {
3204
+ const opts = { ...DEFAULT_OPTIONS, ...options };
3205
+ const n = toBigInt(value);
3206
+ const bigK = toBigInt(k);
3207
+ validateNonNegative(n);
3208
+ if (bigK <= 0n) {
3209
+ throw new ValidationError$1('K must be positive in multifactorial');
3210
+ }
3211
+ if (opts.checkOverflow && n > BigInt(opts.maxValue)) {
3212
+ throw new OverflowError(`Multifactorial input too large: maximum allowed is ${opts.maxValue}`);
3213
+ }
3214
+ let result = 1n;
3215
+ let current = n;
3216
+ while (current > 0n) {
3217
+ result *= current;
3218
+ current -= bigK;
3219
+ }
3220
+ return result;
3221
+ }
3222
+ /**
3223
+ * Calculates primorial (product of primes up to n)
3224
+ */
3225
+ function primorial(value, options = {}) {
3226
+ const opts = { ...DEFAULT_OPTIONS, ...options };
3227
+ const n = toBigInt(value);
3228
+ validateNonNegative(n);
3229
+ if (opts.checkOverflow && n > BigInt(opts.maxValue)) {
3230
+ throw new OverflowError(`Primorial input too large: maximum allowed is ${opts.maxValue}`);
3231
+ }
3232
+ if (n <= 1n)
3233
+ return 1n;
3234
+ // Generate primes up to n using Sieve of Eratosthenes
3235
+ const num = Number(n);
3236
+ const sieve = new Array(num + 1).fill(true);
3237
+ sieve[0] = sieve[1] = false;
3238
+ for (let i = 2; i * i <= num; i++) {
3239
+ if (sieve[i]) {
3240
+ for (let j = i * i; j <= num; j += i) {
3241
+ sieve[j] = false;
3242
+ }
3243
+ }
3244
+ }
3245
+ // Calculate product of all primes up to n
3246
+ let result = 1n;
3247
+ for (let i = 2; i <= num; i++) {
3248
+ if (sieve[i]) {
3249
+ result *= BigInt(i);
3250
+ }
3251
+ }
3252
+ return result;
3253
+ }
3254
+
3255
+ /**
3256
+ * Hypernum - A TypeScript/JavaScript library for large number operations
3257
+ */
3258
+ const packagePath = path.resolve(path.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)))), '../package.json');
3259
+ const { version: VERSION } = JSON.parse(fs.readFileSync(packagePath, 'utf-8'));
3260
+ /**
3261
+ * Creates a new Hypernum instance with custom configuration
3262
+ */
3263
+ function createHypernum(config) {
3264
+ const mergedConfig = mergeConfig(config || {});
3265
+ validateConfig(mergedConfig);
3266
+ const instanceConfig = {
3267
+ precision: 'arithmetic' in mergedConfig
3268
+ ? mergedConfig.arithmetic.defaultPrecision
3269
+ : mergedConfig.precision ?? 0,
3270
+ roundingMode: 'arithmetic' in mergedConfig
3271
+ ? mergedConfig.arithmetic.defaultRoundingMode
3272
+ : mergedConfig.roundingMode ?? exports.RoundingMode.HALF_EVEN,
3273
+ checkOverflow: 'arithmetic' in mergedConfig
3274
+ ? mergedConfig.arithmetic.checkOverflow
3275
+ : mergedConfig.checkOverflow ?? true,
3276
+ maxSteps: 'arithmetic' in mergedConfig
3277
+ ? mergedConfig.arithmetic.maxComputationSteps
3278
+ : mergedConfig.maxSteps ?? 1000,
3279
+ debug: 'debug' in mergedConfig && typeof mergedConfig.debug === 'object'
3280
+ ? mergedConfig.debug.verbose
3281
+ : false
3282
+ };
3283
+ return new Hypernum(instanceConfig);
3284
+ }
3285
+ // Default instance
3286
+ const defaultHypernum = createHypernum();
3287
+
3288
+ exports.AckermannStructure = AckermannStructure;
3289
+ exports.BigArray = BigArray;
3290
+ exports.ComputationLimitError = ComputationLimitError;
3291
+ exports.DEFAULT_ARRAY_GROWTH_FACTOR = DEFAULT_ARRAY_GROWTH_FACTOR;
3292
+ exports.DEFAULT_BASIC_CONFIG = DEFAULT_BASIC_CONFIG;
3293
+ exports.DEFAULT_CACHE_SIZE = DEFAULT_CACHE_SIZE;
3294
+ exports.DEFAULT_DECIMAL_SEPARATOR = DEFAULT_DECIMAL_SEPARATOR;
3295
+ exports.DEFAULT_FULL_CONFIG = DEFAULT_FULL_CONFIG;
3296
+ exports.DEFAULT_GROUP_SEPARATOR = DEFAULT_GROUP_SEPARATOR;
3297
+ exports.DEFAULT_GROUP_SIZE = DEFAULT_GROUP_SIZE;
3298
+ exports.DEFAULT_HEAP_INITIAL_CAPACITY = DEFAULT_HEAP_INITIAL_CAPACITY;
3299
+ exports.DEFAULT_OPTIONS = DEFAULT_OPTIONS$8;
3300
+ exports.DEFAULT_TREE_MAX_DEPTH = DEFAULT_TREE_MAX_DEPTH;
3301
+ exports.DataStructureError = DataStructureError;
3302
+ exports.DivisionByZeroError = DivisionByZeroError;
3303
+ exports.ERROR_MESSAGES = ERROR_MESSAGES;
3304
+ exports.FEATURES = FEATURES;
3305
+ exports.FormatError = FormatError;
3306
+ exports.HeapPropertyError = HeapPropertyError;
3307
+ exports.Hypernum = Hypernum;
3308
+ exports.HypernumError = HypernumError;
3309
+ exports.IndexError = IndexError;
3310
+ exports.MAX_ACKERMANN_M = MAX_ACKERMANN_M;
3311
+ exports.MAX_ACKERMANN_N = MAX_ACKERMANN_N;
3312
+ exports.MAX_BITS = MAX_BITS;
3313
+ exports.MAX_CACHE_SIZE = MAX_CACHE_SIZE;
3314
+ exports.MAX_COMPUTATION_STEPS = MAX_COMPUTATION_STEPS;
3315
+ exports.MAX_FACTORIAL_INPUT = MAX_FACTORIAL_INPUT;
3316
+ exports.MAX_GROUP_SIZE = MAX_GROUP_SIZE;
3317
+ exports.MAX_POWER_BASE = MAX_POWER_BASE;
3318
+ exports.MAX_POWER_EXPONENT = MAX_POWER_EXPONENT;
3319
+ exports.MAX_PRECISION = MAX_PRECISION;
3320
+ exports.MAX_ROMAN_VALUE = MAX_ROMAN_VALUE;
3321
+ exports.MAX_SAFE_INTEGER = MAX_SAFE_INTEGER;
3322
+ exports.MAX_TETRATION_HEIGHT = MAX_TETRATION_HEIGHT;
3323
+ exports.MIN_ARRAY_CAPACITY = MIN_ARRAY_CAPACITY;
3324
+ exports.MIN_ROMAN_VALUE = MIN_ROMAN_VALUE;
3325
+ exports.MIN_SAFE_INTEGER = MIN_SAFE_INTEGER;
3326
+ exports.MaxHeap = MaxHeap;
3327
+ exports.MinHeap = MinHeap;
3328
+ exports.NEGATIVE_ONE = NEGATIVE_ONE;
3329
+ exports.NUMBER_UNITS = NUMBER_UNITS;
3330
+ exports.NumberTree = NumberTree;
3331
+ exports.ONE = ONE;
3332
+ exports.PERFORMANCE = PERFORMANCE;
3333
+ exports.PowerTower = PowerTower;
3334
+ exports.PrecisionError = PrecisionError;
3335
+ exports.RomanNumeralError = RomanNumeralError;
3336
+ exports.TEN = TEN;
3337
+ exports.TWO = TWO;
3338
+ exports.TreeError = TreeError;
3339
+ exports.UnderflowError = UnderflowError;
3340
+ exports.VERSION = VERSION;
3341
+ exports.ZERO = ZERO;
3342
+ exports.abs = abs;
3343
+ exports.add = add;
3344
+ exports.allEqual = allEqual;
3345
+ exports.and = and;
3346
+ exports.between = between;
3347
+ exports.binomial = binomial;
3348
+ exports.checkAdditionOverflow = checkAdditionOverflow;
3349
+ exports.checkMultiplicationOverflow = checkMultiplicationOverflow;
3350
+ exports.checkPowerOverflow = checkPowerOverflow;
3351
+ exports.clamp = clamp;
3352
+ exports.clearBit = clearBit;
3353
+ exports.compare = compare;
3354
+ exports.convertToBasicConfig = convertToBasicConfig;
3355
+ exports.createComparator = createComparator;
3356
+ exports.createHypernum = createHypernum;
3357
+ exports.default = Hypernum;
3358
+ exports.defaultHypernum = defaultHypernum;
3359
+ exports.divide = divide;
3360
+ exports.equals = equals;
3361
+ exports.factorial = factorial;
3362
+ exports.fallingFactorial = fallingFactorial;
3363
+ exports.formatBigInt = formatBigInt;
3364
+ exports.fromBase = fromBase;
3365
+ exports.fromFraction = fromFraction;
3366
+ exports.fromRoman = fromRoman;
3367
+ exports.fromScientific = fromScientific;
3368
+ exports.gcd = gcd;
3369
+ exports.getBit = getBit;
3370
+ exports.greaterThan = greaterThan;
3371
+ exports.greaterThanOrEqual = greaterThanOrEqual;
3372
+ exports.isAscending = isAscending;
3373
+ exports.isBasicConfig = isBasicConfig;
3374
+ exports.isDescending = isDescending;
3375
+ exports.isFullConfig = isFullConfig;
3376
+ exports.lcm = lcm;
3377
+ exports.leadingZeros = leadingZeros;
3378
+ exports.leftShift = leftShift;
3379
+ exports.lessThan = lessThan;
3380
+ exports.lessThanOrEqual = lessThanOrEqual;
3381
+ exports.max = max;
3382
+ exports.mergeConfig = mergeConfig;
3383
+ exports.min = min;
3384
+ exports.multiFactorial = multiFactorial;
3385
+ exports.multiply = multiply;
3386
+ exports.normalizeNumberString = normalizeNumberString;
3387
+ exports.normalizePrecision = normalizePrecision;
3388
+ exports.not = not;
3389
+ exports.nthRoot = nthRoot;
3390
+ exports.or = or;
3391
+ exports.parseBigIntString = parseBigIntString;
3392
+ exports.popCount = popCount;
3393
+ exports.power = power;
3394
+ exports.primorial = primorial;
3395
+ exports.remainder = remainder;
3396
+ exports.rightShift = rightShift;
3397
+ exports.risingFactorial = risingFactorial;
3398
+ exports.rotateLeft = rotateLeft;
3399
+ exports.rotateRight = rotateRight;
3400
+ exports.round = round;
3401
+ exports.scaleByPowerOfTen = scaleByPowerOfTen;
3402
+ exports.scaledDivision = scaledDivision;
3403
+ exports.setBit = setBit;
3404
+ exports.sign = sign;
3405
+ exports.sqrt = sqrt;
3406
+ exports.subfactorial = subfactorial;
3407
+ exports.subtract = subtract;
3408
+ exports.superRoot = superRoot;
3409
+ exports.tetration = tetration;
3410
+ exports.toBase = toBase;
3411
+ exports.toBigInt = toBigInt;
3412
+ exports.toBinary = toBinary;
3413
+ exports.toFraction = toFraction;
3414
+ exports.toHexadecimal = toHexadecimal;
3415
+ exports.toOctal = toOctal;
3416
+ exports.toRoman = toRoman;
3417
+ exports.toScientific = toScientific;
3418
+ exports.toggleBit = toggleBit;
3419
+ exports.trailingZeros = trailingZeros;
3420
+ exports.unsignedRightShift = unsignedRightShift;
3421
+ exports.validateConfig = validateConfig;
3422
+ exports.validateNonNegative = validateNonNegative;
3423
+ exports.validatePositive = validatePositive;
3424
+ exports.xor = xor;
3425
+ //# sourceMappingURL=index.cjs.map