Sakamoto's Algorithm

Tomohiko Sakamoto came up with a terse program for calculating the day of the week in 1993. His code was written in the C language. The non-portable code goes like this:

int dayofweek(unsigned int y, unsigned int m, unsigned int d)
{
y -= m < 3;
return (y + y/4 - y/100 + y/400 + "-bed=pen+mad."[m] + d) % 7;
}


Here is the portable version:

int dayofweek(int y, int m, int d)
{
static int t[] = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 };

y -= m < 3;
return (y + y/4 - y/100 + y/400 + t[m-1] + d) % 7;
}

Comments

Popular posts from this blog

Doomsday Timeline

A Perpetual Calendar based on Lego™