Project Euler 19 Counting Sundays

Question

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

Analysis

  1. 闰年影响到二月的天数,闰年的判断可以用函数实现。
  2. 星期天的判断方法就是所要求的日期距1900.1.1的天数对7取余。

Program

def isLeapYear(year):
    if (year % 400 == 0):
        return True
    elif (year % 100 == 0):
        return False
    elif (year % 4 == 0):
        return True
    else:
        return False


def isSunday(day):
    if (day % 7 == 6):
        return True
    else:
        return False


days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
num_sundays = 0
index = sum(days)
if (isLeapYear(1900)):
    index += 1

for year in range(1901, 2001):
    if (isLeapYear(year)):
        days[1] = 29
    else:
        days[1] = 28

    for mouth in range(12):
        if (isSunday(index)):
            num_sundays += 1
        index += days[mouth]

print(num_sundays)
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,448评论 0 10
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,916评论 0 23
  • 我最不了解的人 是妈妈 在我的眼中 妈妈是没有棱角的 可外婆说 年轻的时候, 她桀骜不驯,犹如野马 小时候挨的打最...
    杨加糖阅读 542评论 0 8
  • 渐渐的,少了联系 慢慢的,越来越远 我知道 你在刻意 你知道 我在克制 其实我们都一样 其实我们不一样 到最后 曾...
    和尚的后脑勺阅读 242评论 0 0
  • 你的身躯 站成了妖娆的姿态 你的枝叶 变幻成金色的灿烂 你的理想 永远是不变的坚守 你的生命 显现出不屈的品格 你...
    沙鸥_f44c阅读 370评论 0 4