Counting Sundays
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)?
周日计数
下列信息是已知的,当然你也不妨自己再验证一下:
- 1900年1月1日是周一。
- 三十天在九月中,
四六十一也相同。
剩下都是三十一,
除去二月不统一。
二十八天平常年,
多加一天在闰年。- 闰年指的是能够被4整除却不能被100整除,或者能够被400整除的年份。
在二十世纪(1901年1月1日到2000年12月31日)中,有多少个月的1号是周日?
这个题我认为最简单的做法就是蔡勒公式,把每年每个月一号带入公式就可以求得结果了;关于蔡勒公式
w:星期; w对7取模得:0-星期日,1-星期一,2-星期二,3-星期三,4-星期四,5-星期五,6-星期六
c:世纪-1(前两位数)
y:年(后两位数)
m:月(m大于等于3,小于等于14,即在蔡勒公式中,某年的1、2月要看作上一年的13、14月来计算,比如2003年1月1日要看作2002年的13月1日来计算)
d:日
[ ]代表取整,即只要整数部分 。(向下取整)现在有了公式,那就只需要两个循环来解决该题了,一个外循环年,一个内循环月,下面是代码实现:
#include <stdio.h> int func(int y, int m) { return ((y % 100) + (y % 100 / 4) + (y / 100 / 4) - 2 * y / 100 + (26 * (m + 1) / 10) + 1 - 1) % 7; } int main() { int ans = 0; for (int i = 1901; i <= 2000; i++) { for (int j = 3; j <= 14; j++) { if (j >= 13) { if (!func(i - 1, j)) ans += 1;//因为模等于0就是周日所以非0就成立所以ans + 1; } else { if (!func(i, j)) ans += 1; } } } printf("%d\n", ans); return 0; }
答案为:171