Find Related products on Amazon

Shop on Amazon

A leap year check in three instructions

Published on: 2025-07-06 23:57:19

With the following code, we can check whether a year 0 ≤ y ≤ 102499 is a leap year with only about 3 CPU instructions: bool is_leap_year_fast(uint32_t y) { return ((y * 1073750999) & 3221352463) <= 126976; } How does this work? The answer is surprisingly complex. This article explains it, mostly to have some fun with bit-twiddling; at the end, I'll briefly discuss the practical use. This is how a leap year check is typically implemented: bool is_leap_year(uint32_t y) { if ((y % 4) != 0) return false; if ((y % 100) != 0) return true; if ((y % 400) == 0) return true; return false; } We are using the proleptic Gregorian calendar, which extends the Gregorian calendar backward from its introduction in 1582 and includes a year 0. Thus, we don't need to treat years before 1582 any differently. For simplicity, we ignore negative years and use an unsigned year. Optimizing the standard approach Let's first do some simple speedups so that we get a good baseline. I'm not sure where to assig ... Read full article.