Leap year function; how does this solution work?

2442 views javascript
7

The problem is this:

Given a year, report if it is a leap year.

The tricky thing here is that a leap year in the Gregorian calendar occurs:

on every year that is evenly divisible by 4
  except every year that is evenly divisible by 100
    unless the year is also evenly divisible by 400

My solution(that works) was this:

export const isLeap = (year) => {
    const yearModFour = (year % 4) === 0 
    const yearModHundred = (year % 100) === 0
    const yearModFourHundred = (year % 400) === 0 
    const isLeapYear = yearModFour === yearModHundred === yearModFourHundred
    return isLeapYear
}

I came to this conclusion because I miss read the logic as:

on every year that is evenly divisible by 4
  and also evenly divisible by 100
    and also evenly divisible by 400

My question is, why does this somehow work?

answered question

It's more like yearModFour && (!yearModHundred || yearModFourHundred)

I think the OP is stating that his code works - which it does - but he doesn't understand why

or also yearModFour && !(yearModHundred && !yearModFourHundred)

1 Answer

4

Let's look at the predicate yearModFour === yearModHundred === yearModFourHundred, and list a few numbers that will lead to all possibilities.

For year 1, the predicate evaluates to:

(False === False) === False
             True === False
                 False

For year 4, the predicate evaluates to:

(True === False) === False
           False === False
                 True

For year 100, the predicate evalueates to:

(True === True) === False
           True === False
               False

For year 400, the predicate evaluates to:

(True === True) === True
           True === True
                True

So your conclusion is not quite correct, as it implies logical "and" between all of the modulo operations.

posted this

Have an answer?

JD

Please login first before posting an answer.