# Checking for Leap Year in Detail

Every programmer face leap year problem at least once and most of them just memorise following formula.

`return (year % 4 == 0 and year % 100 != 0) or year % 400 == 0`

I am going to tell you math behind this formula.

Total actual days in a year = 365.2422
Days in a Non leap year = 365
Now, we have to settle fraction part of days i.e. 0.2422 somehow. Because we can’t increase or decrease a day in fraction. So, we increase 1 day in certain years called leap years. when we should increase it? is an interesting question which I am going to tell you in this article.

Let’s try to convert fraction part (0.2422) into from of 1/a where a is an integer.
1/4 = 0.25 (which is greater than 0.2422).

Let’s try to decrease it a little bit.
1/4 - 1/100
= 0.25 – 0.01
= 0.24 (It is smaller than 0.2422).

1/4 – 1/100 + 1/400
= 0.25 – 0.01 + 0.0025
= 0.2425
It’s became greater again. But we are closer this time.

Let’s decrease it
1/4 – 1/100 + 1/400 – 1/2500
= 0.25 – 0.01 + 0.0025 – 0.0004
= 0.2421
It’s working! one more and we done.

1/4 – 1/100 + 1/400 – 1/2500 + 1/10000
= 0.25 – 0.01 + 0.0025 – 0.0004 + 0.0001
= 0.2422
Great! we solved it.

To make a decision for a leap year, look last expression. When we should declare a leap year?
Every 4th year: Yes
Every 100th year: No
Every 400th year: Yes
Every 2500th year: No
Every 10,000th year: Yes

Let’s consider every case.
we can easily see that every number above divisible by 4. So, we have to neglect specific case as follow.

`year % 4 == 0 and year % 100 != 0`

above code included 4th but neglected 100th. And by neglecting 100 we neglected all further years because they are divisible by 100.
i.e. `400 % 100 == 0` ,`2500 % 100 == 0` and `1000 % 100 == 0`
So, we have to specifically include 400th as follow.

`(year % 4 == 0 and year % 100 != 0) or year % 400 == 0`

We don’t need to work for 2500 because It is already neglected by 100. And didn’t included by 400 as `2500 % 100 == 0` But `2500 % 400 != 0` .

Similarly, By including 400, we already included 10,000.
i.e. `10000 % 400 == 0` So, we don’t need to check for 10,000.

Now we came to the point when we can write our program.

`return (year % 4 == 0 and year % 100 != 0) or year % 400 == 0`