my-prime-library
v2.0.0
Published
My Prime Library is a comprehensive TypeScript/React package for prime number operations and visualization. This library provides optimized algorithms for prime checking, generation, factorization, and advanced prime analysis with a feature-rich React com
Readme
My Prime Library
My Prime Library is a comprehensive TypeScript/React package for prime number operations and visualization. This library provides optimized algorithms for prime checking, generation, factorization, and advanced prime analysis with a feature-rich React component for rendering prime numbers. Ideal for educational tools, number theory projects, mathematical applications, and performance-critical computations.
Features
Core Prime Operations
- Prime Check: Fast primality testing with memoization and optimized algorithms
- Prime Generation: Efficient Sieve of Eratosthenes implementation with caching
- Prime Factorization: Complete prime factorization for any integer
- Next/Previous Prime: Find adjacent prime numbers
- Prime Gaps Analysis: Calculate gaps between consecutive primes
- Miller-Rabin Test: Probabilistic primality testing for large numbers
React Component Features
- Multiple Display Modes: List, grid, and virtualized rendering
- Performance Optimized: Async processing for large ranges
- Interactive Features: Click handlers and custom formatting
- Pagination: Built-in pagination for large datasets
- Customizable Styling: Highlight and style specific primes
- Statistics Display: Real-time prime count and range information
- Responsive Design: Mobile-friendly layouts
Developer Experience
- TypeScript Support: Full type definitions included
- Comprehensive Testing: Unit tests, edge cases, and performance benchmarks
- Multiple Bundle Formats: ESM, CommonJS, and UMD support
- Bundle Analysis: Built-in bundle size analysis tools
Installation
To install the package, run:
npm install my-prime-libraryUsage
1. Prime Checking
Fast primality testing with memoization:
import { isPrime } from 'my-prime-library';
console.log(isPrime(7)); // true
console.log(isPrime(10)); // false
console.log(isPrime(7919)); // true (large prime)2. Prime Generation
Generate all prime numbers up to a limit using optimized Sieve of Eratosthenes:
import { generatePrimes } from 'my-prime-library';
console.log(generatePrimes(10)); // [2, 3, 5, 7]
console.log(generatePrimes(30)); // [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]3. Prime Factorization
Complete prime factorization for any integer:
import { primeFactorization } from 'my-prime-library';
console.log(primeFactorization(12)); // [2, 2, 3]
console.log(primeFactorization(84)); // [2, 2, 3, 7]
console.log(primeFactorization(97)); // [97] (prime number)4. Adjacent Prime Numbers
Find next and previous prime numbers:
import { getNextPrime, getPreviousPrime } from 'my-prime-library';
console.log(getNextPrime(10)); // 11
console.log(getNextPrime(17)); // 19
console.log(getPreviousPrime(10)); // 7
console.log(getPreviousPrime(17)); // 135. Prime Gaps Analysis
Analyze gaps between consecutive primes:
import { getPrimeGaps } from 'my-prime-library';
const gaps = getPrimeGaps(20);
console.log(gaps);
// [
// { prime1: 2, prime2: 3, gap: 1 },
// { prime1: 3, prime2: 5, gap: 2 },
// { prime1: 5, prime2: 7, gap: 2 },
// { prime1: 7, prime2: 11, gap: 4 },
// { prime1: 11, prime2: 13, gap: 2 },
// { prime1: 13, prime2: 17, gap: 4 },
// { prime1: 17, prime2: 19, gap: 2 }
// ]6. Miller-Rabin Primality Test
Probabilistic testing for very large numbers:
import { isPrimeMillerRabin } from 'my-prime-library';
// Test large numbers efficiently
console.log(isPrimeMillerRabin(982451653)); // true (large prime)
console.log(isPrimeMillerRabin(982451654)); // false7. Advanced React Component
Feature-rich prime rendering with multiple display modes:
import React from 'react';
import { PrimeRenderer } from 'my-prime-library';
const App = () => {
const handlePrimeClick = (prime, event) => {
console.log(`Clicked prime: ${prime}`);
};
const formatPrime = (prime) => {
return `🔢 ${prime}`;
};
return (
<div>
<h1>Prime Numbers Gallery</h1>
{/* Basic list view */}
<PrimeRenderer limit={50} />
{/* Grid view with custom styling */}
<PrimeRenderer
limit={100}
listType="grid"
highlightedPrimes={[2, 3, 5, 7]}
onPrimeClick={handlePrimeClick}
formatPrime={formatPrime}
/>
{/* Virtualized view for large ranges */}
<PrimeRenderer
limit={10000}
listType="virtualized"
pageSize={50}
containerHeight={300}
showStats={true}
showPagination={true}
/>
</div>
);
};
export default App;8. Cache Management
Control memory usage with cache management:
import { clearPrimeCache } from 'my-prime-library';
// Clear all cached prime computations
clearPrimeCache();API Reference
Core Functions
isPrime(number)
- Description: Fast primality testing with memoization and optimized algorithms
- Parameters:
number(number): The number to check (must be finite and non-negative)
- Returns:
boolean:trueif the number is prime,falseotherwise
- Features: Input validation, caching, optimized 6k±1 algorithm
generatePrimes(limit)
- Description: Generates all prime numbers up to a given limit using Sieve of Eratosthenes
- Parameters:
limit(number): The upper limit for generating primes (must be finite and non-negative)
- Returns:
number[]: An array of prime numbers
- Features: Memoization, efficient sieve algorithm, automatic caching
primeFactorization(num)
- Description: Complete prime factorization for any integer greater than 1
- Parameters:
num(number): The number to factorize (must be > 1)
- Returns:
number[]: An array of prime factors in ascending order
- Throws:
RangeErrorif number is less than or equal to 1
getNextPrime(num)
- Description: Finds the next prime number after the given number
- Parameters:
num(number): The starting number (must be finite and non-negative)
- Returns:
number: The next prime number
getPreviousPrime(num)
- Description: Finds the previous prime number before the given number
- Parameters:
num(number): The starting number (must be finite and non-negative)
- Returns:
number: The previous prime number
- Throws:
RangeErrorif no prime exists before the given number
getPrimeGaps(limit)
- Description: Calculates gaps between consecutive primes up to a limit
- Parameters:
limit(number): The upper limit for prime gap analysis
- Returns:
PrimeGap[]: Array of objects withprime1,prime2, andgapproperties
isPrimeMillerRabin(num, k)
- Description: Probabilistic primality test for large numbers using Miller-Rabin algorithm
- Parameters:
num(number): The number to testk(number): Number of witness rounds (default: 5)
- Returns:
boolean:trueif probably prime,falseif definitely composite
- Features: Automatically uses regular
isPrimefor numbers < 1,000,000
clearPrimeCache()
- Description: Clears all cached prime computations to free memory
- Parameters: None
- Returns:
void
React Component
<PrimeRenderer />
A comprehensive React component for rendering prime numbers with multiple display modes and customization options.
Props:
limit(number): The upper limit for generating primes (required)listType('list' | 'grid' | 'virtualized'): Display mode (default: 'list')itemHeight(number): Height of each item in virtualized mode (default: 40)containerHeight(number): Container height for virtualized mode (default: 400)pageSize(number): Number of items per page in virtualized mode (default: 100)asyncThreshold(number): Threshold for async processing (default: 10000)onPrimeClick(function): Click handler for prime itemsformatPrime(function): Custom formatting function for prime displayclassName(string): Additional CSS class namesshowStats(boolean): Show statistics panel (default: true)showPagination(boolean): Show pagination controls (default: true)highlightedPrimes(number[]): Array of primes to highlightcustomStyledPrimes(number[]): Array of primes with custom styling
TypeScript Interfaces:
interface PrimeGap {
prime1: number;
prime2: number;
gap: number;
}
interface PrimeRendererProps {
limit: number;
listType?: 'list' | 'grid' | 'virtualized';
itemHeight?: number;
containerHeight?: number;
pageSize?: number;
asyncThreshold?: number;
onPrimeClick?: (prime: number, event: React.MouseEvent) => void;
formatPrime?: (prime: number) => string;
className?: string;
showStats?: boolean;
showPagination?: boolean;
highlightedPrimes?: number[];
customStyledPrimes?: number[];
}Development
To work on the library locally:
Clone the repository:
git clone https://github.com/your-username/my-prime-library.git cd my-prime-libraryInstall dependencies:
npm installBuild the library:
npm run buildRun tests:
# Run all tests npm test # Run tests with coverage npm run test:coverage # Run tests with UI npm run test:ui # Watch mode for development npm run test:watchType checking:
# One-time type check npm run type-check # Watch mode for type checking npm run type-check:watchBundle analysis:
# Build and analyze bundle size npm run build:analyzeTest the library locally:
npm linkUse it in another project:
npm link my-prime-library
Project Structure
my-prime-library/
├── src/
│ ├── components/
│ │ └── PrimeRenderer.tsx # React component
│ ├── utils/
│ │ └── primes.ts # Core prime algorithms
│ └── test/
│ ├── primes.test.js # Core function tests
│ ├── PrimeRenderer.test.jsx # Component tests
│ ├── edge-cases.test.js # Edge case testing
│ ├── performance.test.js # Performance benchmarks
│ └── setup.js # Test configuration
├── dist/ # Built distributions
├── scripts/
│ └── analyze-bundle.js # Bundle analysis script
├── package.json # Dependencies and scripts
├── rollup.config.js # Build configuration
├── vitest.config.js # Test configuration
└── README.md # This fileBuild System
The library uses Rollup for bundling with the following outputs:
- ESM:
dist/index.esm.js- Modern ES modules - CommonJS:
dist/index.cjs.js- Node.js compatible - UMD:
dist/index.umd.js- Browser compatible - Type Definitions:
dist/index.d.ts- TypeScript support
Testing
Comprehensive test suite including:
- Unit tests for all core functions
- Component testing with React Testing Library
- Edge case validation
- Performance benchmarks
- Memory leak detection
- Type safety validation
Performance
Algorithmic Complexity
- isPrime(): O(√n) with 6k±1 optimization
- generatePrimes(): O(n log log n) using Sieve of Eratosthenes
- primeFactorization(): O(√n) in worst case
- isPrimeMillerRabin(): O(k log³n) where k is witness count
Benchmarks
Typical performance on modern hardware:
- Check primality of numbers up to 1,000,000: < 1ms
- Generate primes up to 100,000: < 10ms
- Generate primes up to 1,000,000: < 100ms
- Factorize numbers up to 1,000,000: < 5ms
Memory Usage
- Automatic caching for frequently accessed primes
- Configurable cache clearing with
clearPrimeCache() - Virtualized rendering for large prime lists in React component
- Memory-efficient sieve implementation
Browser Support
- React: 16.8+ (hooks support required)
- Modern Browsers: ES2018+ support recommended
- Node.js: 14+ for CommonJS/ESM modules
- TypeScript: 4.5+ for full type support
Version History
v1.0.5 (Current)
- Added Miller-Rabin primality test for large numbers
- Enhanced PrimeRenderer with virtualized rendering
- Improved caching algorithms and memory management
- Added comprehensive TypeScript definitions
- Extended test coverage with performance benchmarks
v1.0.0
- Initial release with core prime functions
- Basic React component implementation
- Sieve of Eratosthenes implementation
- Essential primality testing
License
This project is licensed under the MIT License. See the LICENSE file for details.
Contributing
Contributions are welcome! Please follow these guidelines:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Development Guidelines
- Write comprehensive tests for new features
- Ensure TypeScript types are updated
- Follow existing code style and patterns
- Update documentation for API changes
- Run full test suite before submitting
Areas for Contribution
- Additional prime algorithms (Sieve of Atkin, etc.)
- Performance optimizations
- New React component features
- Mathematical utilities
- Documentation improvements
- Benchmark enhancements
Support
For questions, issues, or contributions:
- 📧 Create an issue on GitHub
- 📖 Check the API documentation
- 🧪 Run the test suite for examples
- 📊 Use bundle analysis for optimization
Built with ❤️ for the mathematics and developer community
