Thursday, November 10, 2011

Is it a Leap Year?

Well, really, the only reason we care is to know whether February has 28 days or 29 days, right?  Everything else is the same, because knowing that fact also tells us whether the year is 365 days long or 366.  So, the problem devolves to simply knowing the number of days in February, and that depends strictly upon the question 'what year is it?'.

   days.   = 31                        /* jan mar may jul aug oct dec*/
   days.04 = 30                        /* apr                        */
   days.06 = 30                        /* jun                        */
   days.09 = 30                        /* sep                        */
   days.11 = 30                        /* nov                        */
   days.02 = 28 + (ccyy//4=0) - (ccyy//100=0) + (ccyy//400=0)

(Presuming you have a 4-digit year available for the calculation)  the number of days in February is 28 plus...

One if the year is evenly divisible by 4  (ccyy//4 = 0),  unless...

The year is also evenly divisble by 100  (ccyy//100 = 0)  unless...

The year is also evenly divisble by 400  (ccyy//400 = 0)

Couldn't be simpler.  2000 was a leap year, and February had 28 + 1 - 1 + 1 (=29) days.  1900 was not a leap year;  it had 28 + 1 - 1 (=28) days.

No comments:

Post a Comment