原题链接:http://projecteuler.net/problem=19
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日是星期一。
- 30天的月份有:9月,4月,6月,11月。
- 此外的月份都是31天,当然2月除外。
- 2月在闰年有29天,其他时候有28天。
- 年份可以被4整除的时候是闰年,但是不能被400整除的世纪年(100的整数倍年)除外。
20世纪(1901年1月1日到2000年12月31日)一共有多少个星期日落在了当月的第一天?
解法1:
1.初始化平年里的12个月的天数
2.先计算1901年1月1日是星期几
3.每次都加本月的天数再对7求余,对于当月是2月的情况则需要当年是否是闰年,余数6即是下个月的第一天是星期几,一直到2012年11月为止。
php代码:
function is_leap_year($year){
$is_leap_year = FALSE;
if($year%4==0){
$is_leap_year = TRUE;
if($year%100==0){
$is_leap_year = FALSE;
if($year%400==0){
$is_leap_year = TRUE;
}
}
}
return $is_leap_year;
}
$days_of_month = array(
1=>31,
2=>28,
3=>31,
4=>30,
5=>31,
6=>30,
7=>31,
8=>31,
9=>30,
10=>31,
11=>30,
12=>31,
);
$Jan_1_of_1900 = 1;
$days_of_1900 = is_leap_year(1900)?366:365;
$Jan_1_of_1901 = (($days_of_1900%7)+$Jan_1_of_1900)%7;
$first_day_of_last_month = $Jan_1_of_1901;
$start = 1901;
$end = 2000;
$months = ($end-$start+1)*12;
$sunday_fell_on_first_day_of_month = ($Jan_1_of_1901==0)?1:0;
for($i=1;$i<$months;$i++){
$month = $i%12;
if($month==0){
$month = 12;
}
$days = $days_of_month[$month];
$current_year = $start+intval($i/12);
if($month==2&&is_leap_year($current_year)){
$days+=1;
}
$first_day_of_last_month = ($first_day_of_last_month+$days)%7;
if($first_day_of_last_month==0){
$sunday_fell_on_first_day_of_month += 1;
}
}
echo $sunday_fell_on_first_day_of_month;
注:题目的中文翻译源自http://pe.spiritzhang.com
本文探讨了一个有趣的日期相关问题:20世纪(1901年1月1日至2000年12月31日)中,有多少个月的第一天恰好是周日。通过详细的算法描述及PHP实现,展示了如何计算这一特殊日期模式。
1245

被折叠的 条评论
为什么被折叠?



