daynumber2b.cpp


      #include "library.h"
      
      bool is_leap_year(int Y)
      { if (Y%4!=0) return false;
        if (Y%100!=0) return true;
        if (Y%400!=0) return false;
        return true; }
      
      int day_of_year(int Y, int M, int D)
      { int ans=0;
        if (M>1) ans=ans+31;
        if (M>2)
        { if (is_leap_year(Y))
            ans=ans+29;
          else
            ans=ans+28; }
        if (M>3) ans=ans+31;
        if (M>4) ans=ans+30;
        if (M>5) ans=ans+31;
        if (M>6) ans=ans+30;
        if (M>7) ans=ans+31;
        if (M>8) ans=ans+31;
        if (M>9) ans=ans+30;
        if (M>10) ans=ans+31;
        if (M>11) ans=ans+30;
        return ans+D; }
      
      int day_number(int Y, int M, int D)
      { int ans=day_of_year(Y, M, D);
        ans=ans+Y*365;
        ans=ans+(Y+3)/4;
        ans=ans-(Y-1)/100;
        ans=ans+(Y-1)/400;
        return ans; }
      
      string day_of_week(int Y, int M, int D)
      { const int dn = day_number(Y, M, D);
        const int wdn = dn % 7;
        if (wdn==0) return "Friday";
        if (wdn==1) return "Saturday";
        if (wdn==2) return "Sunday";
        if (wdn==3) return "Monday";
        if (wdn==4) return "Tuesday";
        if (wdn==5) return "Wednesday";
        if (wdn==6) return "Thursday";
        return "ERROR"; }
      
      void test(int Y, int M, int D)
      { printf("%04d %02d %02d -> day %d which is a ",
                Y, M, D, day_number(Y, M, D));
        print(day_of_week(Y, M, D));
        newline(); }
      
      void main(void)
      { test(2005, 10, 11);
        test(2005, 10, 12);
        test(2005, 10, 13);
        test(2005, 10, 20);
        test(2005, 10, 27);
        test(2005, 1, 1);
        test(2004, 12, 31);
        test(2000, 1, 1);
        test(1999, 12, 31);
        test(1900, 1, 1);
        test(1899, 12, 31);
        test(1777, 4, 22); }