【ProjectEuler】ProjectEuler_019

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

#include <iostream>
#include <windows.h>
using namespace std;

//每个月的天数,2月无视
int dayOfMonth[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

//星期
enum Week
{
    Sunday = 0,
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday
};

//月份
enum Month
{
    January = 0,
    February,
    March,
    April,
    May,
    June,
    July,
    August,
    September,
    October,
    November,
    December
};

//判断是否是闰年
bool isLeapYear(int year)
{
    if(year % 4 == 0)
    {
        if(year % 100 == 0)
        {
            if(year % 400 == 0)
            {
                return true;
            }

            return false;
        }

        return true;
    }

    return false;
}

//获取某年某月的天数,主要判断是否为闰年2月
int getDayOfMonth(int year, int month)
{
    if(month == February && isLeapYear(year))
    {
        return 29;
    }
    else
    {
        return dayOfMonth[month];
    }
}

void F1()
{
    cout << "void F1()" << endl;

    LARGE_INTEGER timeStart, timeEnd, freq;
    QueryPerformanceFrequency(&freq);
    QueryPerformanceCounter(&timeStart);

    int year = 1900;
    int month = January;	//January
    int week = Monday;		//Monday

    int result = 0;			//times Sundays fell on the first of the month

    for(; year <= 2000; year++)
    {
        for(; month <= December; month++)
        {
            week = (week + getDayOfMonth(year, month)) % 7;

            if(week == Sunday && year >= 1901)
            {
                result++;
            }
        }

        month = 0;	//initialize month value
    }

    cout << "The times Sundays fell on the first of the month is " << result << endl;

    QueryPerformanceCounter(&timeEnd);
    cout << "Total Milliseconds is " << (double)((double)(timeEnd.QuadPart - timeStart.QuadPart) * 1000 / (double)freq.QuadPart) << endl;
}

//主函数
int main()
{
    F1();
    return 0;
}

/*
void F1()
The times Sundays fell on the first of the month is 171
Total Milliseconds is 11.8723

By GodMoon
*/

你可能感兴趣的:(【ProjectEuler】ProjectEuler_019)