計算某一年末日演算法的程式


末日演算法也稱為星期幾的末日,指的是每年都落在同一天的特定星期幾。末日演算法的概念基於末日演算法,該演算法允許我們確定任何給定日期的星期幾。

末日演算法是由數學家約翰·霍頓·康威開發的,其思想是基於每年某些日期落在同一天(稱為末日)的星期幾。末日出現在以下日期:

  • 1月3日

  • 閏年2月7日或14日

  • 3月7日

  • 4月4日

  • 5月9日

  • 6月6日

  • 7月11日

  • 8月8日

  • 9月5日

  • 10月10日

  • 11月7日

  • 12月12日

以下是計算末日演算法的步驟。

確定世紀基日

基日指的是一個特定的星期幾,作為計算任何給定日期的星期幾的參考點。它充當計算中確定星期幾的起點或基準。

為了計算世紀基日,將年份除以100以確定世紀。然後使用世紀來查詢該特定世紀的基日。該基日對於該世紀內的所有年份都是相同的。不同世紀的基日是預定義的,並基於末日演算法規則。

確定年份基日

取年份的後兩位數字。將這兩位數字除以12以獲得商和餘數。將餘數除以4以獲得閏年數。將商、餘數和閏年數加在一起。最後,將此總和模7(結果模7)以獲得年份基日。

確定月份基日

檢索給定月份的相應數字。月份基日只是指定的數字。為每個月份分配一個特定的數字,如下所示:

  • 一月 - 3

  • 二月 - 0

  • 三月 - 0

  • 四月 - 4

  • 五月 - 9

  • 六月 - 6

  • 七月 - 11

  • 八月 - 8

  • 九月 - 5

  • 十月 - 10

  • 十一月 - 7

  • 十二月 - 12

計算末日

將世紀基日、年份基日和月份基日加在一起。將此總和模7(結果模7)以獲得末日。末日用 0 到 6 的整數表示,其中 0 表示星期日,1 表示星期一,依此類推。

示例

我們可以透過使用 Python 和以下程式碼,一步一步地實現上述步驟來計算末日。

def calculate_doomsday(year, month, day):
   # Calculate the century anchor day
   century = year // 100
   anchor = (5 * (century % 4) + 2) % 7

   # Calculate the year anchor day
   year_within_century = year % 100
   quotient = year_within_century // 12
   remainder = year_within_century % 12
   num_leap_years = year_within_century // 4
   year_anchor = (anchor + quotient + remainder + num_leap_years) % 7

   # Calculate the month anchor day
   month_anchors = [3, 0, 0, 4, 9, 6, 11, 8, 5, 10, 7, 12]
   month_anchor = month_anchors[month - 1]

   # Calculate the weekday
   day_of_week = (year_anchor + month_anchor + day) % 7
   return day_of_week

year = 1995
month = 1
day = 22
day_of_week = calculate_doomsday(year, month, day)
days_of_week = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
print(f"The Dooms day of the week for {month}/{day}/{year} is {days_of_week[day_of_week]}.")

輸出

The Dooms day of the week for 1/22/1995 is Saturday.

更新於:2023年8月2日

149 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.