Wednesday, June 10, 2009

Leap Year checking

What is Leap Year?

The standard Gregorian Calendar that we follow in our daily life, has a leap year every four years. In such a year the month of February contains one extra day in order to keep the calendar year synchronized with the Astronomical Year. So the number of days in the month of February becomes 29 and the number of days in the leap year becomes 366.

The Rule

The full rule for checking a leap year is not very well known, and I often find many of my juniors and fellow pupils lacking the exact knowledge of the full rule. What most people know is that if the year is divisible by 4 then it is a leap year. But although this rule is good for nearly all practical purposes, it is not the full rule. The exact rule for finding out whether a year is leap year or not, is best described by a flowchart:

leap2

It was of course designed keeping the programmers in mind. But non programmers too, should not have much of a problem to understand the logic. Just to aid them, a%b denotes a mod b, which in simple terms mean the remainder obtained when a is divided by b. The numbers a and b are positive numbers only. The above diagram is technically called a flowchart.

Programming Language Construct

We can of course translate this to a programming language with the use of three if-then-else constructs. But there is an easier way of doing this as I will demonstrate:

Let us denote the three condition checks by three boolean variables, A, B and C (as shown beside flowchart). So the condition for leap year is:

AB’ + ABC
= A ( B’ + BC )
= A ( B’ + C )

The reduced boolean expression when expressed in C-like constructs become:

year%4==0 && (year%100!=0 || year%400==0)

Conclusion

What prompted me to write the article was the popular misconception to the rule and the ability to demonstrate the boolean reduction technique. The article took shape while I was trying to explain the rule to my brother Bikkhan for the the n-th time and decided to draw the flowchart to make matters easy for him. Lastly, I also figured out that this could be an excellent way of showing him the practical usage of boolean reductions that he has learnt in his Std XI curriculum, but never grasped the true significance of.

References

  1. To know more about Leap Year, Gregorian Calendar and Astronomical Year, just follow the links. You will also get an insight on the exact scientific reasons behind the rule.

  2. For a similar discussion and actual program in C language, consult the book “The C Programming Language”, 2nd Ed., by Brian Kernighan and Dennis Ritchie. They have given a similar construct along with a full program on date computation.

  3. For non-programmers reading this blog, here are some links on Boolean Algebra and Flowcharts.

3 comments:

I'd love to hear from you !