Problem
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)?
Answer
1 | 171 |
Python1
2
3#!/usr/bin/env python
from calendar import monthrange; from itertools import product
print(len([(year, month) for year, month in product(list(range(1901, 2001)), list(range(1, 13))) if monthrange(year, month)[0] == 6]))
1 | #!/usr/bin/env python |
Ruby1
2
3#!/usr/bin/env ruby
require 'date'
puts Date.new(1901,1,1).upto(Date.new(2000,12,31)).find_all { |d| d.mday == 1 && d.wday == 0 }.count
Java1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40public final class p019 implements EulerSolution {
public static void main(String[] args) {
System.out.println(new p019().run());
}
/*
* We use Zeller's congruence to compute the day of week when given the year, month, and day.
* Then we simply check the first day of all the months in the given range by brute force.
*
* Zeller's congruence is well-known and a bit long to explain.
* See: https://en.wikipedia.org/wiki/Zeller%27s_congruence
*/
public String run() {
int count = 0;
for (int y = 1901; y <= 2000; y++) {
for (int m = 1; m <= 12; m++) {
if (dayOfWeek(y, m, 1) == 0) // Sunday
count++;
}
}
return Integer.toString(count);
}
// Return value: 0 = Sunday, 1 = Monday, ..., 6 = Saturday.
private static int dayOfWeek(int year, int month, int day) {
if (year < 0 || year > 10000 || month < 1 || month > 12 || day < 1 || day > 31)
throw new IllegalArgumentException();
// Zeller's congruence algorithm
int m = (month - 3 + 4800) % 4800;
int y = (year + m / 12) % 400;
m %= 12;
return (y + y/4 - y/100 + (13 * m + 2) / 5 + day + 2) % 7;
}
}
Mathematica1
2
3
4
5(*
* We simply use Mathematica's built-in date library to compute the answer by brute force.
*)
<< Miscellaneous`Calendar`
Sum[Boole[DayOfWeek[{y, m, 1}] === Sunday], {y, 1901, 2000}, {m, 1, 12}]