Project Euler #19: Counting Sundays

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

Here is my solution in C++; solved on my system in .016 seconds.

#include <iostream>
//////////////////////////////////////////////////////////////////
bool isLeapYear(unsigned long long passedYear);
//////////////////////////////////////////////////////////////////
int main(void)
{
	struct dayStruct
	{
		int day = 1;
		int weekMark = 2, monthMark = 1, yearMark = 1901;
		std::string dayOfWeek;
		bool leapYear = false;
	};

	
	dayStruct currentDay;
	int leapMonths[] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
	int regularMonths[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
	int sundayCount = 0;

	while(currentDay.yearMark < 2001) { if((currentDay.day) == 1 && currentDay.weekMark == 7) { sundayCount++; } currentDay.day += 1; currentDay.weekMark += 1; if(currentDay.weekMark > 7)
		{
			currentDay.weekMark = 1;
		}


		if((currentDay.leapYear) && (currentDay.day > leapMonths[currentDay.monthMark-1]))
		{
			currentDay.monthMark += 1;
			currentDay.day = 1;
		}

		else if(currentDay.day > regularMonths[currentDay.monthMark-1])
		{
			currentDay.monthMark += 1;
			currentDay.day = 1;
		}

		if(currentDay.monthMark > 12)
		{
			currentDay.monthMark = 1;
			currentDay.yearMark++;
			currentDay.leapYear = isLeapYear(currentDay.yearMark);
		}

	}

	std::cout << "Total Sundays: " << sundayCount << "\n";

}
//////////////////////////////////////////////////////////////////
bool isLeapYear(unsigned long long passedYear)
{
	if(passedYear % 4) 
	{
		return true;
	}

	return false;
}
//////////////////////////////////////////////////////////////////

Leave a Reply

Your email address will not be published. Required fields are marked *