今天看到一個很有趣的題目,題目描述如下:
根據下列信息計算在1901年1月1日至2000年12月31日間共有多少個星期天落在每月的第一天上?
a) 1900.1.1是星期一
b) 1月,3月,5月,7月,8月,10月和12月是31天
c) 4月,6月,9月和11月是30天
d) 2月是28天,在閏年是29天
e) 公元年數能被4整除且又不能被100整除是閏年
f) 能直接被400整除也是閏年
以下是C語言實現版本:
#include下來是最簡單的python:#include bool isLeapYear(int year); // start is the weekday of 1st, January // return the num of the first day of each month // is Sunday. // the start will change into the next year int getYearNum(int* start, int year); // Num of days of each month int days[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; int leapdays[13] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; int main(void) { int sum = 0; int start = 1901; int end = 2000; int startWeek = 1; int startYear = 1900; int i; for (i = 1; i < 13; ++i) days[i] += days[i - 1]; for (i = 1; i < 13; ++i) leapdays[i] += leapdays[i - 1]; for (i = startYear; i < start; ++i) getYearNum(&startWeek, i); for (i = start; i <= end; ++i) sum += getYearNum(&startWeek, i); printf("%d\n", sum); return 0; } bool isLeapYear(int year) { if (year % 4 == 0 && year % 100 != 0) return true; else if (year % 400 == 0) return true; return false; } int getYearNum(int* start, int year) { int i; int count = 0; int yeardays; if (isLeapYear(year)) { yeardays = 366; for (i = 0; i < 12; ++i) if ((leapdays[i] % 7 + *start)%7 == 0) ++count; } else { yeardays = 365; for (i = 0; i < 12; ++i) if ((days[i] % 7 + *start)%7 == 0) ++count; } *start = (yeardays % 7 + *start)%7; return count; }
import calendar sum = 0 startYear = 1901 endYear = 2000 for year in xrange(startYear, endYear + 1): for month in xrange(1, 13): if calendar.monthcalendar(year, month)[0].index(1) == 6: sum = sum + 1 print sum
OK,一個問題,多種語言,各有優劣。同時用多種語言是一種很不錯的體驗。