sqrt-bn-enhanced
v2.0.9
Published
A TypeScript library for calculating square roots of arbitrary-precision numbers using the `bn.js` library.
Readme
sqrt-enhanced
A TypeScript library for calculating square roots of arbitrary-precision numbers using the bn.js library.
Features
- ✅ TypeScript Support: Full TypeScript support with type definitions
- ✅ Arbitrary Precision: Handle numbers of any size using
bn.js - ✅ Multiple Algorithms: Babylonian method (Newton's method) implementation
- ✅ Enhanced Features: Configurable options, metadata, and utility functions
- ✅ Error Handling: Comprehensive error handling and validation
- ✅ Documentation: Full JSDoc documentation
Installation
npm install sqrt-enhancedQuick Start
import { sqrt_bn, sqrt_bn_enhanced, BN } from 'sqrt-enhanced';
// Basic usage
const result = await sqrt_bn(16);
console.log(result.toString()); // "4"
// With big numbers
const bigNumber = new BN('123456789012345678901234567890');
const sqrt = await sqrt_bn(bigNumber);
console.log(sqrt.toString());
// Enhanced version with metadata
const enhanced = await sqrt_bn_enhanced(100, { verbose: true });
console.log(`Result: ${enhanced.result}`);
console.log(`Iterations: ${enhanced.iterations}`);
console.log(`Execution time: ${enhanced.executionTime}ms`);API Reference
sqrt_bn(input: SqrtInput): Promise<SqrtResult>
Calculates the integer square root of a number using the Babylonian method.
Parameters:
input: The number to find the square root of (string, number, or BN)
Returns: Promise that resolves to the square root as a BN instance
Example:
const result = await sqrt_bn(25); // Returns BN(5)
const result2 = await sqrt_bn('1000000'); // Returns BN(1000)
const result3 = await sqrt_bn(new BN('123456789')); // Returns BN(11111)sqrt_bn_enhanced(input: SqrtInput, options?: SqrtOptions): Promise<SqrtResultWithMetadata>
Enhanced version with configurable options and metadata.
Parameters:
input: The number to find the square root ofoptions: Configuration options (optional)
Options:
verbose: Whether to log results to console (default: false)maxIterations: Maximum number of iterations (default: 1000)tolerance: Precision tolerance for convergence (default: BN(1))
Returns: Promise that resolves to an object with result and metadata
Example:
const result = await sqrt_bn_enhanced(100, {
verbose: true,
maxIterations: 500,
tolerance: new BN(1)
});
console.log(result.result); // BN(10)
console.log(result.iterations); // Number of iterations performed
console.log(result.converged); // Whether algorithm converged
console.log(result.executionTime); // Execution time in millisecondsUtility Functions
isValidBN(value: any): boolean
Validates if a value can be converted to a valid BN.
toBN(value: any): BN
Converts a value to BN with validation.
isPerfectSquare(n: BN): boolean
Checks if a number is a perfect square.
formatBN(bn: BN): string
Formats a BN number with commas for better readability.
getDigitCount(bn: BN): number
Calculates the number of digits in a BN.
roundBN(bn: BN, decimals: number): BN
Rounds a BN to a specified number of decimal places.
Types
type SqrtInput = string | number | BN;
type SqrtResult = BN;
type EnvVars = Record<string, string>;
interface SqrtOptions {
verbose?: boolean;
maxIterations?: number;
tolerance?: BN;
}
interface SqrtResultWithMetadata {
result: BN;
iterations: number;
converged: boolean;
executionTime: number;
}Development
Prerequisites
- Node.js (v14 or higher)
- npm or yarn
Setup
# Clone the repository
git clone <repository-url>
cd sqrt-enhanced
# Install dependencies
npm install
# Build the project
npm run build
# Run tests
npm test
# Development mode (watch for changes)
npm run devScripts
npm run build: Compile TypeScript to JavaScriptnpm run test: Run the test scriptnpm run dev: Watch mode for development
Algorithm
The library uses the Babylonian method (also known as Newton's method) for calculating square roots:
- Start with an initial guess:
x = n >> (bitLength/2) - Iteratively refine the guess:
x = (n/x + x) / 2 - Continue until convergence:
x < y
This method provides fast convergence and works well with arbitrary-precision arithmetic.
Error Handling
The library includes comprehensive error handling:
- Invalid input validation
- Negative number detection
- Overflow protection
- Convergence monitoring
License
MIT License - see LICENSE file for details.
Contributing
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests if applicable
- Submit a pull request
Changelog
v2.0.3
- Converted to TypeScript
- Added comprehensive type definitions
- Enhanced API with metadata and options
- Added utility functions
- Improved error handling and documentation
- Removed security vulnerabilities from original code
