Checking For A Leap Year

Wait! What? I’ve been programming most of my life and have a PhD in Mathematics but I’ve never seen this before. It’s about checking for a leap year. The first thing we all learn is that it’s a leap year if it’s divisible by 4 but that’s not quite right. It’s a bit more complicated. The usual check is something like

int is_a_leap_year( int y )
{
    if ( ( y % 4 ) != 0 ) return 0;
    if ( ( y % 100 ) != 0 ) return 1;
    if ( ( y % 400 ) == 0 ) return 1;
    return 0;
}    

Code like that has been written thousands (millions?) of times in just about every language there is.

What to make of this, then?

int is_a_leap_year( int y )
{
    return ( ( y * 1073750999 ) & 3221352463 ) <= 126976;
}

According to the link, you can make this check in 3 CPU instructions. It seems like magic but there’s a pretty good explanation of how it works at the link. Oddly enough, it’s a pretty direct translation of the normal check. Again, see the link for the details.

Checking for a leap year is not something you usually do in a loop—although it’s easy enough to imagine cases where you would—so it’s probably not a worthwhile project to replace your leap year checks with this code. Nonetheless, you have to love it if only as a curiosity.

Of course, if you’re one of those people who obsess about squeezing every cycle out of your code—I was like that when I was younger—this may seem like gold to you. If nothing else, it will confound and amaze your colleagues.

This entry was posted in Programming and tagged . Bookmark the permalink.