mirror of
https://github.com/mruby/mruby
synced 2026-06-08 16:11:16 +00:00
6190234e3d
Implement and integrate Barrett reduction algorithm to optimize modular arithmetic operations for moderate-sized moduli (64-512 bits). This algorithm provides significant performance improvements for cryptographic applications and repeated modular operations. Technical implementation: - Added mpz_barrett_mu() to compute Barrett parameter μ = ⌊2^(2k)/m⌋ - Added mpz_barrett_reduce() with full 7-step Barrett algorithm - Integrated into mpz_mod() with automatic selection criteria: * Single-limb modulus: existing fast path (unchanged) * Moderate moduli (2-8 limbs, dividend ≥ modulus + 2): Barrett reduction * Large moduli: general division fallback (unchanged) Performance characteristics: - Barrett reduction is most effective for 64-512 bit moduli - Complements existing single-limb optimization for small moduli - Transparent optimization with no API changes - All existing tests pass (1712 tests successful) Algorithm details: Barrett reduction avoids expensive division by precomputing a parameter and using only multiplications and bit shifts. The 7-step algorithm approximates the quotient, performs modular reduction using power-of-2 operations, and applies final corrections to ensure 0 ≤ result < modulus. Co-authored-by: Claude <noreply@anthropic.com>