# Euler Problem 19¶

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 remember someone doing this by estimation. So let's try that first and then code a solution:

We have one hundred years which equal 1200 months. Every month starts with a weekday and $\frac{1}{7}$ of all weekdays are Sundays. So, 1200 divided by 7 is 171 point something.

Which turns out to be the correct solution.

Let's still code a solution because we were not that smart back then. We create two generators, zip, them and search for 1st and Sunday.

In [1]:

    def weekday_generator_function():
        while True:
            yield 'Monday'
            yield 'Tuesday'
            yield 'Wednesday'
            yield 'Thursday'
            yield 'Friday'
            yield 'Saturday'
            yield 'Sunday'

    def day_of_month_generator_function():
        day, month, year = 1, 1, 1901
        while year < 2001:
            yield day
            day += 1
            if month == 2:
                if year % 4 == 0 and (not year % 100 == 0 or year % 400 == 0):
                    if day == 30:
                        month += 1
                        day = 1
                elif day == 29:
                    month += 1
                    day = 1
            elif month in [9, 4, 6, 11] and day == 31:
                day = 1
                month += 1
            elif month in [1, 3, 5, 7, 8, 10] and day == 32:
                day = 1
                month += 1
            elif month == 12 and day == 32:
                day = 1
                month = 1
                year += 1

    ds = zip(weekday_generator_function(), day_of_month_generator_function())
    s = len([1 for weekday, date in ds if weekday == "Sunday" and date == 1])
    print(s)

    172

Okay, this is actually kind of embarrassing. Why am I even zipping when I have the month right there in my function. Problem is, that my weekday generator starts with Monday, but Monday was the start in 1900 not in 1901. Let's try to do better. 1.1.1901 was a Tuesday, so we drop Monday from the generator.

In [2]:

    wds = weekday_generator_function()
    next(wds) # get rid of first Monday
    ds = zip(wds, day_of_month_generator_function())
    s = len([1 for weekday, date in ds if weekday == "Sunday" and date == 1])
    print(s)

    171

And finally, here we go. Actually not a dummy exercise and shows how imporessive the shortcut from the beginning is. Raw power is not always the best solution if we can also use brain.