Problem 19
Counting Sundays
Problem 19
14 June 2002
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)?
#include "pub.h" int count=0; void ct(int y, int m, int week_day) { //y:year //m:month //week_day: 0-monday,1-tuesday,...6-sunday if(y==2000 && m==12) { if(week_day==6) count++; return; } else { if(week_day==6) count++; if(m==12) { week_day = (week_day+31%7)%7; //the next year return ct(y+1, 1,week_day); } else { if(m==2) { if(y%400==0 || y%4==0&&y%100!=0) week_day = (week_day+29%7)%7; else week_day = (week_day+28%7)%7; } else if(m==1 || m==3 ||m==5 ||m==7 ||m==8 ||m==10|| m==12) week_day = (week_day+31%7)%7; else week_day = (week_day+30%7)%7; //next month return ct(y, m+1,week_day); } } } void p19() { //1901.1.1 is tuesday ct(1901, 1,1); cout<<count<<endl; }

浙公网安备 33010602011771号