▼页尾

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

可以用数组把每月天数求出来

然后计算每个月第一天和某个基数的天数差来检查是不是星期天

但实际上,有公式直接由日期计算星期

我们先来说说蔡勒公式

W = [C/4] - 2C + y + [y/4] + [13 * (M+1) / 5] + d - 1

w:星期; w对7取模得:0-星期日,1-星期一,2-星期二,3-星期三,4-星期四,5-星期五,6-星期六   

c:世纪-1(前两位数)    

y:年(后两位数)   

m:月(m大于等于3,小于等于14,即在蔡勒公式中,某年的1、2月要看作上一年的13、14月来计算,比如2003年1月1日要看作2002年的13月1日来计算)    

d:日

而另一个改进公式为

Week=(Day + 2*Month + 3*(Month+1)/5 + Year + Year/4 - Year/100 + Year/400) % 7

这里的month也要按前面的规律来调整

我不想深究这个公式是怎么来的

但我们可以直接利用前人的结论

#include <iostream>
using namespace std;

int main()
{
    int count = 0;
    int year, month, day=1;
    int week;
    for(int i=1901; i<=2000; i++)
    {
        for(int j=1; j<=12; j++)
        {
            year = i;
            month = j;
            if (month == 1 || month == 2)
            {
                month += 12;
                year -= 1;
            }
            week = (day+2*month+3*(month+1)/5+year+year/4-year/100+year/400)%7;
            if(week==6 || week==-1)
            {
                count++;
            }
        }
    }
    cout << count << endl;
    return 0;
}

好了,传统思路的方法比较懒写了

posted @ 2011-03-05 09:42  xiatwhu  阅读(447)  评论(0编辑  收藏  举报
▲页首
西