You are given the following information, but you may prefer to do some research for yourself.
1 Jan 1900 was a Monday.
Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
The key part of this solution is to use modular arthimetic. There will be two different set of "pushes" depending on if the year is a leap year or not. Every month, certain number of days are "pushed" from the prior month.
For example, if we start January 1st as a Monday, and January has 31 days, then we are pushing Monday on Feburary by 3 days since 31 is congruent to 3 (mod 7). Hence, it will be Thursday on Feb 1st. So, we assign numbers to each days: $$ Monday = 1 $$ $$ Tuesday = 2 $$ and so on. Sunday will be 0. Jan 1st of 1901 is a Wednesday, hence, the initial value is 2. Then we add the number of pushes correspinding to each month, and check if its 0 (mod 7) every month and keep track of how many 0 (mod 7) after each push.
Also have to keep track of Leap days which is indicated with using two different push arrays.
For example, lets do a sample calculation. The table below shows the number of days and "pushes" for a given month. Let's say Jan 1st is a Tuesday, then we indicate the initial day as 2. Then after January, Feb 1st will be 2 + 3 (mod 7), which is 5. This corresponds to Saturday. We keep doing this until we have iterated from year 1901 to 2000 Dec.
Jan | Feb | March | April | May | June | July | Aug | Sept | Oct | Nov | Dec | |
# of Days | 31 | 28 | 31 | 30 | 31 | 30 | 31 | 31 | 30 | 31 | 30 | 31 |
Pushes (mod 7) | 3 | 0 | 3 | 2 | 3 | 2 | 3 | 3 | 2 | 3 | 2 | 3 |
Answer: 171
Runtime: 0.29 ms