daynumber4.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; }
      
      int find_year(int day)
      { int min=0;
        int max=day/300+1;
        while (true)
        { int year = (min+max)/2;
          int first_day = day_number(year, 1, 1);
          int last_day = day_number(year, 12, 31);
          if (day>=first_day && day<=last_day)
            return year;
          else if (day<first_day)
            max=year-1;
          else
            min=year+1; } }
      
      int find_month(int year, int dn)
      { int month=1;
        while (month<12)
        { if (day_number(year, month+1, 1) > dn)
            return month;
          month=month+1; }
        return 12; }
      
      void test(int dn)
      { const int year = find_year(dn);
        const int month = find_month(year, dn);
        printf("day number %d is in year %d, month %d\n", dn, year, month); }
      
      void main(void)
      { test(732598);
        test(732597);
        test(732596);
        test(732313);
        test(732312);
        test(730486);
        test(730485);
        test(693962);
        test(693961);
        test(649149); }