法一看代码:
#include <iostream>
using namespace std;
bool function_year(int year) {
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
return true;
else
return false;
}
int main() {
int a[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int b[12] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int sum = 0, t = 0;
for (int i = 1901; i < 2001; i++) {
if (function_year(i)) {
for (int j = 0; j < 12; j++) {
if (t == 5) {
sum++;
cout << "Year: " << i << ", Month: " << j + 1 << ", First day: " << t << endl;
}
t = (b[j] % 7 + t) % 7;
}
} else {
for (int j = 0; j < 12; j++) {
if (t == 5) {
sum++;
cout << "Year: " << i << ", Month: " << j + 1 << ", First day: " << t << endl;
}
t = (a[j] % 7 + t) % 7;
}
}
}
cout << sum;
return 0;
}
注意:在t==5时次数加一的原因是因为t=0时表示1901年1月1日,加上当月总数后你会发现确实等于下月1号,但是放在星期这个度量来讲就是你加了k个星期期+1天,意思是你多加了一天,加完之后从t=6表示周天变成了t=5表示周天,这是t在加天数取余操作不规范导致的
法二:蔡勒公式
视频讲解:<iframe src="//player.bilibili.com/player.html?aid=334604795&bvid=BV1jA411P71s&cid=382818797&p=1" scrolling="no" border="0" frameborder="no" framespacing="0" allowfullscreen="true"> </iframe>
31 30 31 30 31 这五个整体可以循环两次
综上为原理讲解,一下为代码实现:
#include <iostream>
using namespace std;
int flag=1;
int cl(int y, int m, int d){
if(m == 1 || m == 2){
y--;
m += 12;
}
int w;
if(y==1582&&m==9&&d==3) flag=0;
if(flag)
w = (d+2*m+3*(m+1)/5+y+y/4-y/100+y/400)% 7;
else w = (d+2*m+3*(m+1)/5+y+y/4+5)% 7;
return w;
}
int main(){
int s = 0;
for(int y = 1901; y <= 2000; y++){
for(int m = 1; m <= 12; m++){
if(cl(y, m, 1) == 6){ s++;}
}
}
cout<<s;
return 0;
}