Correctness of Sakamoto's algorithm to find the day of week

后端 未结 4 662
余生分开走
余生分开走 2020-11-29 15:58

I am using Sakamoto\'s algorithm to find out the day of week from a given date. Can anybody tell me the correctness of this algorithm? I just want this from 2000 to 2099.

4条回答
  •  孤独总比滥情好
    2020-11-29 16:29

    For Gregorian Calendar

    int dayToWeekG(int d,int m,int y){
        int i;
        int t[12]={0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4};
                //{0, 3, 3, 6, 1, 4, 6, 2, 5, 0, 3, 5};
        y-=m<3;
        i=(y+y/4-y/100+y/400 +t[m-1]+d)%7;
        return i;
    }
    

    Explanation:

    • See the commented array for
     t[] = {0, 3, 3, 6, 1, 4, 6, 2, 5, 0, 3, 5};
    

    and compare it with a calendar of a whole year (run cal 2to generate calendar in terminal in linux/unix) notice the starting day of the week of the day for each month.

    • Every normal year shifting one day of the week and leap year shifting two days of the week. as (365%7)=1 and (366%7)=2
     i= y+y/4-y/100+y/400
    
    • But we are should not calculate the extra day if y is a leap year for month 0 and 1
    y-=m<3
    
    • but by this way we are also removing the extra day from non-leap years too. so we will fill up the gap by subtracting 1 day for every month after February.

      int t[12]={0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4};

提交回复
热议问题