Problem Description
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)?
Analysis
There are 1200 months (therefore 1200 firsts of the month) in 100 years (1/1/1901 – 12/31/2000). One in every 7 days is a Sunday (or Monday, Tuesday, etc.) which are (roughly) uniformly distributed over the date range. An estimate of 1200/7 Sundays should be close to the answer. As the date range widens this estimate becomes less precise.
We wrote a quick piece of JavaScript (great native calendar support) to prove it to ourselves.
Solution
Runs < 1 second in Javascript.
var count=0, y=1901, years=100; for (var m=0; m<12*years; m++) if (new Date(y,m,1).getDay()==0) count ++; document.write ('answer to PE19 = ' + count + ' Sundays')
Comments
JavaScript numbers the months starting from 0 to 11 so month m=12 is the 1st month (January) of the next year (1902) and so month m=24 is January 1903. Also, getDay() returns 0 for Sunday. As an exercise you could pose questions for other date ranges and other days of the week and compare it to the estimating formula.





Discussion
No comments for “Project Euler Problem 19 Solution”