LoginSignup
1
1

More than 5 years have passed since last update.

Project Euler 19

Last updated at Posted at 2015-03-01

問題

次の情報が与えられている.

1900年1月1日は月曜日である.
9月, 4月, 6月, 11月は30日まであり, 2月を除く他の月は31日まである.
2月は28日まであるが, うるう年のときは29日である.
うるう年は西暦が4で割り切れる年に起こる. しかし, 西暦が400で割り切れず100で割り切れる年はうるう年でない.
20世紀(1901年1月1日から2000年12月31日)中に月の初めが日曜日になるのは何回あるか?
http://odz.sakura.ne.jp/projecteuler/index.php?cmd=read&page=Problem%2019

回答

日曜:0 月曜:1 火曜:2 水曜:3 木曜:4 金曜:5 土曜:6
とする。
前月の1日の曜日dateと前月の日数daysから次の式により次月の1日の曜日nextdateは算出できる。(7は曜日数)。これを利用して以下のコードを書いた。

nextdate = (date+days) % 7
# -*- coding: utf-8 -*-
def getdays(month, year):
  if month in [1,3,5,7,8,10,12]:
    return 31
  elif month in [4,6,9,11]:
    return 30
  elif year%400 == 0:
    return 29
  elif year%100 == 0:
    return 28
  elif year%4 == 0:
    return 29
  else:
    return 28

def nextdate(date, month, year):
   return (date + getdays(month, year)) % 7

def nextmonth(month, year):
   if month == 12:
      #12月であれば次の年へ
      return (1, year+1)
   else:
      return (month+1, year)

def main():
  STARTYEAR = 1901
  LASTYEAR = 2000
  (date, month, year) = (1, 1, 1900)
  ans = 0

  while year <= LASTYEAR:

    #前月のdate,month,yearから次月のdate(曜日)を取得
    date = nextdate(date, month, year)

    #month, yearをインクリメント
    (month,year) = nextmonth(month, year)

    #yearが範囲内でdateが0(日曜日)ならansに1を加える。
    if STARTYEAR <= year <= LASTYEAR and date == 0:
      ans += 1

  print ans

main()
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1