Problem 19 of Project Euler is a curious little problem. It states
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)?
I thought a while about this, before I realised that the easiest way to solve this is most likely to exploit the .NET API. Like many other high level languages .NET offers a really good day/time API, which is easy to use for a problem like this.
The solution is two simple loops to reach all the dates we need to check, and then check if that is a Sunday. In C# this can be implemented as
int sundays = 0;
for (int year = 1901; year <= 2000; year++) {
for (int month = 1; month <= 12; month++) {
if ((new DateTime(year, month, 1)).DayOfWeek == DayOfWeek.Sunday) {
sundays++;
}
}
}
Pretty simple, and an output as
There are 171 sundays on the first of a month
Solution took 0 ms
I have seen a solution proposed which works for the exact question. Since there are 12 month and 100 years, we have 1200 months with a uniform distribution 1/7th of them is mondays, totalling 171 mondays. This solution works nicely for this period, but not for 1903 – 2002.
Closing remarks
It was a curious little problem to find an answer for, however using the date/time API it was fairly easy to provide a brute force solution. As usual I have uploaded the source code for you.