news.volyx.in

A leap year check in three instructions (hueffner.de)

434 points by gnabgib · 442 days ago · 164 comments on HN

Article summary

The article discusses a leap year check algorithm that can determine whether a year is a leap year using only three CPU instructions. The algorithm uses bit-twiddling and multiplication to achieve this. The author explains how the algorithm works and provides a proof of its correctness. The algorithm is optimized for a specific range of years, but the author also explores how to extend it to other ranges and bit widths.

Main themes

  • bit-twiddling optimizations
  • leap year algorithms
  • compiler optimizations
  • performance trade-offs
  • magic numbers
  • algorithm readability
  • historical context of multiplications and divisions

What commenters say

  • Some commenters appreciate the use of magic numbers and bit-twiddling optimizations in the algorithm, while others find them incomprehensible and potentially missed in the past due to the high cost of multiplications.
  • The cost of multiplications and divisions has decreased significantly over time, making such optimizations more viable.
  • Branch prediction and pipelining can affect the performance of the algorithm, and some commenters discuss the trade-offs between different implementations.
  • The use of compiler optimizations and SMT solvers can help simplify and improve the algorithm, but may not always be effective.
  • Some commenters mention alternative algorithms and optimizations, such as the Karatsuba algorithm and the fast inverse square root.
  • The readability and accuracy of the algorithm are also discussed, with some commenters preferring simpler and more readable implementations.
  • The compiler's ability to optimize the algorithm is limited, and some commenters discuss the reasons for this limitation.