Problem 19 :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)?
思路 :
这题就是让我们计算二十世纪中,每月一号是星期日的个数,据题意我们知道了一些条件,可是有一些附加条件需要我们去挖掘,比如我们是从1901年算到2000年,题目给出的是1900年1月1日是星期一,那我们需要计算一下1901年第一个星期日是几号,很显然这是一个循环,俗话说日复一日,年复一年,就是这个道理。
我得到这道题的思路就是从这里想到的,因为我们是从1901年开始,所以我先想到从1900年1月1日星期一算出1901年1月1日是星期几,因为一周是7天,而刚好1900年1月1日作为循环的起点,所以
即刚好1901年1月1日就是星期二,然后找到1901年第一个星期日是1月6号,作为计算起始点,然后把迭代
month | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 |
First Sunday | 6 | 3 | 3 | 7 | 5 | 2 | 7 | 4 | 1 | 6 | 3 | 1 |
Two Sunday | 13 | 10 | 10 | 14 | 12 | 9 | 14 | 11 | 8 | 13 | 10 | 8 |
Three Sunday | 20 | 17 | 17 | 21 | 19 | 16 | 21 | 18 | 15 | 20 | 17 | 15 |
Four Sunday | 27 | 24 | 24 | 28 | 26 | 23 | 28 | 25 | 22 | 27 | 24 | 22 |
Five Sunday | 34 | 31 | 31 | 35 | 33 | 30 | 35 | 32 | 29 | 34 | 31 | 29 |
36 | 36 |
output | 3 | 3 | 31-31+7=7 | 5 | 2 | 7 | 4 | 1 | 6 | 3 | 1 | 36-31=5(下一年的) |
表格没规划好,本来应该是8行,但我比较懒,不想重画了,凑合看看!
这其实就是一个不断迭代的过程。具体见代码:
代码 :
clear,clc;
tic
day = 6;
count = 0;
i = 1;
for year = 1901:2000
if (mod(year,4)==0 && mod(year,100)~=0)|| (mod(year,400)==0) %is leap yearear
Feb = 29;
else
Feb = 28;
end
month = [31,Feb,31,30,31,30,31,31,30,31,30,31]; %month matrix
i = 1;
while i < 13
while day < month(i)
day = day + 7; %lteration---one cycle every seven days
end
while day >= month(i)
day = day - month(i);
break
end
if day == 1
count = count + 1;
%disp(year),disp(i+1),disp(day); %set the output format
if i == 12
formatSpec = ('%d/%d/%d.\n');
fprintf(formatSpec,year+1,1,day);
else
formatSpec = ('%d/%d/%d.\n'); %set the output format
fprintf(formatSpec,year,i + 1,day);
end
end
i = i + 1;
end
end
count %disp result
toc
代码运行起来还是非常高效的。(Elapsed time is 0.266348 seconds.)
结果 :171
补充:前两天有点忙,没来得及更新!