Euler Project – Problem 19 Solution: 171

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)?

Solution:

public class Problem19 {

    public static void main(String[] args) {

        final int JANUARY = 0;
        final int FEBRUARY = 1;
        final int MARCH = 2;
        final int APRIL = 3;
        final int MAY = 4;
        final int JUNE = 5;
        final int JULY = 6;
        final int AUGUST = 7;
        final int SEPTEMBER = 8;
        final int OCTOBER = 9;
        final int NOVEMBER = 10;
        final int DECEMBER = 11;

        final int MONDAY = 0;
        final int TUESDAY = 1;
        final int WEDNESDAY = 2;
        final int THURSDAY = 3;
        final int FRIDAY = 4;
        final int SATURDAY = 5;
        final int SUNDAY = 6;

        int count_for_first_of_month_sundays = 0;

        for (int y = 1900, weekday = MONDAY; y <= 2000; y++) {
            for (int m = 0; m < 12; m++) {
                int month_days = 31;
                if (m == FEBRUARY) {
                    if (isYearLeap(y)) {
                        month_days = 29;
                    } else {
                        month_days = 28;
                    }
                } else if (m == SEPTEMBER || m == APRIL || m == JUNE
                        || m == NOVEMBER) {
                    month_days = 30;
                }

                for (int d = 0; d < month_days; d++) {
                    if (d == 0 && weekday == SUNDAY && y > 1900) {
                        count_for_first_of_month_sundays++;
                    }
                    weekday = (weekday + 1) % 7;
                }
            }
        }

        System.out.println(count_for_first_of_month_sundays);

    }

    static Boolean isYearLeap(int year) {
        if (year % 4 == 0) {
            if (year % 100 == 0) {
                if (year % 400 == 0) {
                    return true;
                }
                return false;
            }
            return true;
        }
        return false;
    }
}