本文主要是介绍Project Euler 题解 #19 Counting Sundays,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目: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.
解题思路
这个公式太牛B了,没看的很明白。
参考下这几个:
蔡勒公式的由来
求某一天是星期几
星期的计算
代码实现
//https://projecteuler.net/problem=19
//Counting Sundays
#include <cassert>
#include <iostream>
using namespace std;
const char *DayInWeek[] = {"momday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"};
//返回值
//0:星期一
//...
//6:星期天
int DayOfWeek(int year, int month, int day)
{
assert(year > 0);
assert(1 <= month && month <= 12);
assert(1 <= day && day <= 31);
int dayofweek = 0;
if (month == 1 || month == 2)
{
month += 12;
year--;
}
if ((year < 1752) || (year == 1752 && month < 9) || (year == 1752 && month == 9 && day < 3))
{
dayofweek = (day + 2*month + 3*(month + 1)/5 + year + year/4 + 5)%7;
}
else
{
dayofweek = (day + 2*month + 3*(month + 1)/5 + year + year/4 - year/100 + year/400)%7;
}
return dayofweek;
}
int _tmain(int argc, _TCHAR* argv[])
{
cout<<DayInWeek[DayOfWeek(2013, 9, 27)]<<endl;
int count = 0;
for (int year = 1901; year <= 2000; ++year)
{
for (int month = 1; month <= 12; ++month)
{
if (6 == DayOfWeek(year, month, 1))
{
++count;
}
}
}
cout<<"There are "<<count<<" Sundays fell on the first of the month during the twentieth century"<<endl;
system("pause");
return 0;
}
输出:171
有位读者提出公式1200/7 = 171
这篇关于Project Euler 题解 #19 Counting Sundays的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!