Project Euler Problem 19 (C++和Python代码实现和解析)

100 篇文章 3 订阅
87 篇文章 1 订阅

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

1. 欧拉项目第19道题 计数星期日

你会得到以下信息,但你可能更愿意为自己做一些研究。

  • 1900年1月1日是星期一
  • 30天有9月、4月、6月和11月。除2月外,其余的月有31天。所有的闰年,2月有29天,无论下雨还是晴天,否则,2月有28天。
  • 闰年发生在任何可以被4整除的年份,但除非它可以被400整除,否则不能发生在一个世纪。

2. 求解分析

这道题我们只用自己的函数来计算,不用第三方的库或函数来计算。

为了统计20世纪(从1901年1月1日 to 2000年12月31日)的每个月的第一天是星期日,我们需要判断闰年,要统计每年的每个月的第一天的总天数(相对于1900年1月1日),然后总天数模7,如果结果是0,累加求和。

为了让整个计算过程模块化,程序设计的时候,要分解为几个模块或函数:

  1. 判断某年是否为闰年
  2. 统计一年有多少天
  3. 判断某年的某个月有多少天
  4. 判断某年某月某日是星期几
  5. 从1901年1月1日 to 2000年12月31日判断每个月第一天是星期日的总数

3. C++ 代码实现

C++代码的实现完全按照求解分析的方法:

  1. 判断某年是否为闰年的函数 checkLeapYear(int year)
  2. 统计一年有多少天的函数 getDaysInYear(int year)
  3. 判断某年的某个月有多少天的函数 getDaysInMonth(int year, int month)
  4. 判断某年某月某日是星期几的函数 getDayOfTheWeek(int year, int month, int day)
  5. 判断20世纪的每个月的第一天是星期日的总数的函数 getTotalOfSundays()

C++的类图如下:
在这里插入图片描述

C++ 代码

#include <iostream>
#include <cassert>

using namespace std;

class PE0019
{
private:
    bool checkLeapYear(int year);
    int  getDaysInMonth(int year, int month);
    int  getDaysInYear(int year);

public:
    int getDayOfTheWeek(int year, int month, int day);
    int getTotalOfSundays();
};

int PE0019::getTotalOfSundays()
{
    int totalOfSundays = 0;

    for (int year = 1901; year <= 2000; year++)
    {
        for (int month = 1; month <= 12; month++)
        {
            // check whether the fist day of the month is Sunday
            if (0 == getDayOfTheWeek(year, month, 1))
            {
                totalOfSundays++;
            }
        }
    }

    return totalOfSundays;
}

bool PE0019::checkLeapYear(int year)
{
    if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0))
    {
        return true;
    }
    else
    {
        return false;
    }
}
    
int PE0019::getDaysInYear(int year)
{
    if (true == checkLeapYear(year))
    {
        return 366;
    }
    else
    {
        return 365;
    }
}

int PE0019::getDaysInMonth(int year, int month)
{
    //              month   1   2   3   4   5   6   7   8   9  10  11  12
    int daysInMonth[12] = { 31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

    if (month != 2)
    {
        return daysInMonth[month - 1];
    }
    else
    {
        if (true == checkLeapYear(year))
        {
            return 29;
        }
        else
        {
            return 28;
        }
    }
}

int PE0019::getDayOfTheWeek(int year, int month, int day)
{
    int totalDays = 0;

    for (int y = 1900; y < year; y++)  // from 1900 to (year-1)
    {
        totalDays += getDaysInYear(y);
    }

    for (int m = 1; m < month; m++)    // from Jan to (month-1)
    {
        totalDays += getDaysInMonth(year, m);
    }

    totalDays += day;                  // from 1 to (day-1)

    int dayOfWeek = totalDays % 7;     // 1 Jan 1900 was a Monday

    return dayOfWeek;
}
    
int main()
{
    PE0019 pe0019;

    assert(1 == pe0019.getDayOfTheWeek(1900, 1, 1));
    assert(0 == pe0019.getDayOfTheWeek(1999, 10, 10));

    cout << pe0019.getTotalOfSundays() << " Sundays fell on the first of ";
    cout << "the month during the twentieth century." << endl;

    return 0;
}

4. Python 代码实现

Python代码的实现跟C++一样,也完全按照求解分析的方法:

  1. 判断某年是否为闰年的函数 checkLeapYear(year)
  2. 统计一年有多少天的函数 getDaysInYear(year)
  3. 判断某年的某个月有多少天的函数 getDaysInMonth (year, month)
  4. 判断某年某月某日是星期几的函数 getDayOfWeek(year, month, day)
  5. 判断20世纪的每个月的第一天是星期日的总数的函数 getTotalOfSundays()

Python 代码

import time

def checkLeapYear(year):
    if ((year % 4 ==0) and (year % 100 != 0)) or (year % 400 == 0):
        return True
    return False

def getDaysInMonth (year, month):
    #      month   1   2   3   4   5   6   7   8   9  10  11  12
    daysInMonth_list = [31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    
    if month != 2:
        return daysInMonth_list[month-1]
    else:
        if True == checkLeapYear(year):  
            return 29
        else: 
            return 28
    
def getDaysInYear(year):
    if True == checkLeapYear(year):
        return 366
    else:
        return 365

def getDayOfWeek(year, month, day):
    totalDays = 0 
    for y in range(1900, year):   # from 1900 to (year-1)
        totalDays += getDaysInYear(y)
    for m in range(1, month):     # from Jan to (month-1)
        totalDays += getDaysInMonth(year, m)   
    totalDays += day              # from 1 to (day-1)
    dayOfWeek = totalDays % 7     # 1 Jan 1900 was a Monday
    
    return dayOfWeek

def getTotalOfSundays():
    totalOfSundays = 0
    for year in range(1901, 2001):
        for month in range(1, 13):
            # check whether the fist day of the month is Sunday
            if 0 == getDayOfWeek(year, month, 1): 
                totalOfSundays += 1

    return totalOfSundays
    
def main():
    start = time.process_time()

    assert 1 == getDayOfWeek(1900, 1,  1)

    print(getTotalOfSundays(),"Sundays fell on the first of the", end='')
    print("month during the twentieth century.")

    end = time.process_time()
    print('CPU processing time : %.5f' %(end-start))

if  __name__ == '__main__':
    main()      
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值