1. 程式人生 > >計算某一天是星期幾的演算法

計算某一天是星期幾的演算法

如何計算某一天是星期幾?
—— 蔡勒(Zeller)公式 
歷史上的某一天是星期幾?未來的某一天是星期幾?關於這個問題,有很多計算公式(兩個通用計算公式和一些分段計算公式),其中最著名的是蔡勒(Zeller)公式。即w=y+[y/4]+[c/4]-2c+[26(m+1)/10]+d-1

公式中的符號含義如下,w:星期;c:世紀-1;y:年(兩位數);m:月(m大於等於3,小於等於14,即在蔡勒公式中,某年的1、2月要看作上一年的13、14月來計算,比如2003年1月1日要看作2002年的13月1日來計算);d:日;[ ]代表取整,即只要整數部分。(C是世紀數減一,y是年份後兩位,M是月份,d是日數。1月和2月要按上一年的13月和 14月來算,這時C和y均按上一年取值。)

算出來的W除以7,餘數是幾就是星期幾。如果餘數是0,則為星期日。

以2049年10月1日(100週年國慶)為例,用蔡勒(Zeller)公式進行計算,過程如下: 
蔡勒(Zeller)公式:w=y+[y/4]+[c/4]-2c+[26(m+1)/10]+d-1 
=49+[49/4]+[20/4]-2×20+[26× (10+1)/10]+1-1 
=49+[12.25]+5-40+[28.6] 
=49+12+5-40+28 
=54 (除以7餘5) 
即2049年10月1日(100週年國慶)是星期5。


這個是最簡單的演算法

蔡勒(Zeller)公式:w=y+[y/4]+[c/4]-2c+[26(m+1)/10]+d-1 


不過,以上公式只適合於1582年10月15日之後的情形(當時的羅馬教皇將愷撒大帝制訂的儒略曆修改成格里曆,即今天使用的公曆)。
http://codeup.cn/problem.php?cid=100000578&pid=1
http://ac.jobdu.com/problem.php?pid=1043
題目1043:Day of Week

時間限制:1 秒

記憶體限制:32 兆

特殊判題:

提交:5834

解決:2090

題目描述:

We now use the Gregorian style of dating in Russia. The leap years are years with number divisible by 4 but not divisible by 100, or divisible by 400.
For example, years 2004, 2180 and 2400 are leap. Years 2004, 2181 and 2300 are not leap.
Your task is to write a program which will compute the day of week corresponding to a given date in the nearest past or in the future using today’s agreement about dating.

輸入:

There is one single line contains the day number d, month name M and year number y(1000≤y≤3000). The month name is the corresponding English name starting from the capital letter.

輸出:

Output a single line with the English name of the day of week corresponding to the date, starting from the capital letter. All other letters must be in lower case.

樣例輸入:
9 October 2001
14 October 2001
樣例輸出:
Tuesday
Sunday
提示:

Month and Week name in Input/Output:
January, February, March, April, May, June, July, August, September, October, November, December
Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday

答疑:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<map>
using namespace std;
map<string,int>month;
int dayofweek(int y, int m, int d) /* 0 = Sunday */ 
{
       static int t[] = {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4};
       y -= m < 3;
       return (y + y/4 - y/100 + y/400 + t[m-1] + d) % 7; //引用了Tomohiko Sakamoto 提供的簡潔程式碼
}
int main()
{
	int y,m,d;
	
	string mon;
    char weekday[7][10]={"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"};
    
    month["January"]=1;month["February"]=2;month["March"]=3;month["April"]=4;
	month["May"]=5;month["June"]=6;month["July"]=7;month["August"]=8;
	month["September"]=9;month["October"]=10;month["November"]=11;month["December"]=12;
	
    while(cin>>d>>mon>>y)
    {
    	m=month[mon];
    	int week = dayofweek(y,m,d);
    	cout<<weekday[week]<<endl;
	}
   
    return 0;
}


受教了,自己真的沒轍,才發現這個的。還在努力切水題,爭取18號前切完所有codeup和PAT裡的水題。
之後要開始STL和資料結構的連結串列 隊 棧,之後兩週分別給樹 和圖。加油吧!