Ray's playground

 

Project Euler 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)?

 

 1 #include <iostream>
 2 using namespace std;
 3 
 4 bool IsLeapYear(int year)
 5 {
 6     if(year % 400 == 0)
 7     {
 8         return true;
 9     }
10     else if(year % 4 == 0 && year % 100 != 0)
11     {
12         return true;
13     } 
14 
15     return false;
16 }
17 
18 int CountOfDays(int year, int month)
19 {
20     switch(month)
21     {
22         case 1:
23         case 3:
24         case 5:
25         case 7:
26         case 8:
27         case 10:
28         case 12:
29             return 31;
30 
31         case 4:
32         case 6:
33         case 9:
34         case 11:
35             return 30;
36             
37         case 2
38             if(IsLeapYear(year))
39             {
40                 return 29;
41             }
42             return 28;
43     }
44     return 0;
45 }
46 
47 int main()
48 {
49     int initialDay = 365 % 7;
50     int count = 0;
51     int sum = 0;
52     for(int year=1901; year<=2000; year++)
53     {
54         for(int month=1; month<=12; month++)
55         {
56             int days = CountOfDays(year, month);
57             if((1+initialDay) % 7 == 0)
58             {
59                 count++;
60             }
61             initialDay += days % 7;
62             initialDay = initialDay % 7;
63         }
64     }
65 
66     cout << count << endl;
67     cin.get();
68 }

 

posted on 2011-03-13 12:07  Ray Z  阅读(370)  评论(0编辑  收藏  举报

导航