4 ms·
I also have my own algorithm for computing the day of the week, and I think that you're doing it the hard way. Of course, if it works for you, no problem. My
by pklausler 11y ago
I also have my own algorithm for computing the day of the week, and I think that you're doing it the hard way. Of course, if it works for you, no problem.
My technique:
day_of_week = (year_day(Y) + month_day[M] + D - leapyear(Y,M)) mod 7
year_day(Y) = let Y' = Y-1900 (or Y-1984) in Y' + trunc(Y' / 4)
month_day[] = { 0, 3, 3, 6, 1, 4, 6, 2, 5, 0, 3, 5 }
leapyear(Y,M) = 1 if M is Jan or Feb in a leap year, else 0
The year_day() is a constant for any year; in 2016, it's 5. The month_day[] table is easy to memorize in an inverted form that groups all the months that start on the same of the week in non-leap years:
0: Oct, Jan
1: May
2: Aug
3: Feb, Mar, Nov
4: Jun
5: Sep, Dec
6: Jul, Apr
And that's it. Today (13 Jan 2016) is 5 + 0 + 13 - 1, or 17 which is 3 mod 7, or Wed.
(EDITED to fix line spacing issues.)
- WolfeReader 11y agoFor year_day(2016), I get 145 (using the 1900 option). Can you check your formula?
- pklausler 11y ago145 = 5 mod 7, and I'll often reduce terms mod 7 when doing the math mentally. EDIT: I mean of course that 145 is equivalent to 5 (mod 7).
- WolfeReader 11y agoThanks! I can use this now.
- tzs 11y agoIf you use Saturday = 0, like Conway does, instead of Sunday = 0, then your month_day table becomes 1, 4, 4, 0, 2, 5, 0, 3, 6, 1, 4, 6. Martin Gardner gave a good suggestion for making that easy to memorize. Group it into sets of 3, giving 1 4 4 0 2 5 0 3 6 1 4 6 You can memorize the first three lines as 12^2, 5^2, and 6^2, and then just have to remember that the last line is 2 more than the first.