Hasty Briefsbeta

Bilingual

A leap year check in three instructions

a year ago
  • #bit-twiddling
  • #leap-year
  • #optimization
  • A fast leap year check using bit-twiddling and magic numbers is introduced.
  • The standard leap year check involves modulo operations for 4, 100, and 400.
  • Optimizations include replacing modulo operations with bit masking and multiplication tricks.
  • A branchless version of the leap year check is presented for predictable performance.
  • A brute-force approach using z3 solver finds optimal constants for a 32-bit fast leap year check.
  • The fast method works correctly for years 0 to 102499 and is explained via bit manipulation.
  • A 64-bit version extends the correct range up to year 5965232499.
  • Benchmarks show the fast method is 3.8x faster for random inputs but slightly slower for predictable ones.