Dean Dean - 3 months ago 7
C++ Question

How does Tomohiko Sakamoto's Algorithm, for finding the day of week, work?

How does the following algorithm work?

enum DayOfWeek
{
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
};

static DayOfWeek GetDayOfWeek(unsigned int year, char month, char day) {
char monthTable[] = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 };

year -= (unsigned int)((month < 3) ? 1 : 0);

return (DayOfWeek)((year + year / 4 - year / 100 + year / 400 + monthTable[month - 1] + day) % 7);
}


source is here

Can someone explain why does it work and how?

Answer

Basically t[] holds offsets for each month (in relation to 1st January), while the /4 /100 /400 account for leap years and double leap years.

You can find a quite detailed explanation of this particular algorithm here: https://www.quora.com/How-does-Tomohiko-Sakamotos-Algorithm-work