已知 1900-01-01 是星期一,計算 1901-01-01 至 2000-12-31 間,有多少個月的 1 號是星期日。需處理閏年規則:
#include#include bool is_leap(int y) { return (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0); } int main() { int month_days[12] = {31,28,31,30,31,30,31,31,30,31,30,31}; int leap_days[12] = {31,29,31,30,31,30,31,31,30,31,30,31}; int *days = month_days; int weekday = 1; // 1900-01-01 = Monday (0=Sun..6=Sat) int count = 0; for (int y = 1900; y <= 2000; y++) { days = is_leap(y) ? leap_days : month_days; for (int m = 0; m < 12; m++) { if (y >= 1901 && weekday == 0) count++; // Sunday weekday = (weekday + days[m]) % 7; } } printf("%d\n", count); // 171 return 0; }
import calendar
count = 0
for year in range(1901, 2001):
for month in range(1, 13):
# calendar.weekday: Monday=0 ... Sunday=6
if calendar.weekday(year, month, 1) == 6:
count += 1
print(count) # 171
function isLeap(y) {
return (y % 4 === 0 && y % 100 !== 0) || (y % 400 === 0);
}
const days = [31,28,31,30,31,30,31,31,30,31,30,31];
let weekday = 1; // 1900-01-01 Monday
let count = 0;
for (let y = 1900; y <= 2000; y++) {
const d = isLeap(y) ? [...days] : days;
d[1] = isLeap(y) ? 29 : 28;
for (let m = 0; m < 12; m++) {
if (y >= 1901 && weekday === 0) count++;
weekday = (weekday + d[m]) % 7;
}
}
console.log(count); // 171
| 維度 | C | Python | JavaScript |
|---|---|---|---|
| 代碼行數 | ~25 | ~8 | ~18 |
| 運行速度 | 極快 (ms) | 快 (ms) | 快 (ms) |
| 日期庫 | 手寫邏輯 | calendar 標準庫 | 手寫/Date 對象 |
| 部署 | 編譯執行 | 解釋執行 | 瀏覽器/Node 直跑 |
| 調試 | GDB/LLDB | pdb/IDE | DevTools/斷點 |
| 適用場景 | 嵌入式/高性能/系統級 | 腳本/數據分析/原型 | Web/全棧/可視化 |
三版本均輸出 171,與 Project Euler Problem 19 答案一致。
同一邏輯用不同語言實現,能深刻體會「工具選型取決於場景」:C 追求極致性能與資源控制,Python 追求開發效率與生態豐富,JavaScript 追求普適性與前端集成。多語言並用,拓寬技術視野。