airnet
airnet

Reputation: 2673

leap year, and the boolean logic behind it

The rules for leap year is :
(1) Most years that can be divided evenly by 4 are leap years.

(2) Century years are NOT leap years UNLESS they can be evenly divided by 400.

I can't help but think I should AND everywhere if ( y%4==0 and y%100!=0 and y%400 == 0 ): which I know is wrong but why exactly ?

This is the real solution :

def year_days(y):
  if ( y%4==0 and y%100!=0 ) or ( y%400 == 0 ):
    return True

return False

Upvotes: 2

Views: 2576

Answers (2)

Priyansh Goel
Priyansh Goel

Reputation: 2660

Take the year 2004. Now 2004 % 4 = 0 , 2004 % 100 != 0 , 2004 % 400 != 0 So last condition fails and so it will give you false despite 2004 is a leap year.

Logic behind the boolean logic :

Century years are NOT leap years UNLESS they can be evenly divided by 400. --- > This gives you that all years divided by 400 will be leap for sure BUT all years divided by 100 may be not.

Most years that can be divided evenly by 4 are leap years. --- > Any year divided by 4 is a leap year other than some of those century years

So now think it this way : y divisible by 400 is always leap . Also y divisible by 4 is always leap unless they are not century years (Exclude years % 400 as they have been taken care of previously). So this gives rise to the condition : y%4 == 0 and y%100 != 0 As if one of them fails the year is not leap. Also, now if (y%4 == 0 and y%100 != 0) is true or (y%400 == 0) is true, the year is leap , so you put an or between them giving you :

(y%4 == 0 and y%100 != 0) or (y%400 == 0)

Upvotes: 2

simleo
simleo

Reputation: 2975

y % 400 == 0 implies y % 4 == 0 and y % 100 == 0, so anding with y % 4 == 0 is useless and anding with y % 100 != 0 leads to an expression that's always false.

Upvotes: 0

Related Questions