[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;
}

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

转载于:https://www.cnblogs.com/xianglan/archive/2011/03/05/1971409.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值