Leap Year

October 5, 2018

This is just a matter of performing the tests in the right order:

(define (leap? n)
  (if (positive? (modulo n 4)) #f
    (if (positive? (modulo n 100)) #t
      (if (positive? (modulo n 400)) #f
        #t))))

> (leap? 2018)
#f
> (leap? 2016)
#t
> (leap? 2000)
#t
> (leap? 2100)
#f

You can run the program at https://ideone.com/54HPvM. It is astonishing how many ways there are to get this wrong; about half the responses to the user who posted the question on the internet were incorrect. Which is why this makes a good exercise, even if it looks simple.

Advertisements

Pages: 1 2

4 Responses to “Leap Year”

  1. Steve said

    Klong version

    leap::{:[0=x!4;:[0=x!100;:[0=x!400;1;0];1];0]}
    

    Examples:
    {.p(x,” –> “,leap(x))}'[2018 2016 2000 2100];””
    [2018 –> 0]
    [2016 –> 1]
    [2000 –> 1]
    [2100 –> 0]
    “”

  2. Daniel said

    Here are two solutions in Python.

    def is_leap_year1(y):
        return (y % 4 == 0) and ((y % 100 != 0) or (y % 400 == 0))
    
    def is_leap_year2(y):
        if y % 4: return False
        if not (y % 400): return True
        return (y % 100) != 0
    
    for i in range(1, 2019):
        leap1 = is_leap_year1(i)
        leap2 = is_leap_year2(i)
        assert leap1 == leap2
        if leap1:
            print(i)
    

    Output:

    4
    8
    12
    16
    ...
    92
    96
    104
    108
    ...
    392
    396
    400
    404
    408
    ...
    1996
    2000
    2004
    2008
    2012
    2016
    
  3. Globules said

    A Haskell version.

    import Text.Printf (printf)
    
    isLeapYear :: Integral a => a -> Bool
    isLeapYear yr = yr `divBy` 4 && not (yr `divBy` 100) || yr `divBy` 400
      where x `divBy` y = x `rem` y == 0
    
    test :: Int -> IO ()
    test yr = printf "%4d -> %s\n" yr $ show $ isLeapYear yr
    
    main :: IO ()
    main = mapM_ test [1, 4, 8, 100, 300, 400, 2018]
    
    $ ./leapyear
       1 -> False
       4 -> True
       8 -> True
     100 -> False
     300 -> False
     400 -> True
    2018 -> False
    
  4. V said

    Built-in in Ruby

    require 'date';
    Date.parse("2020-01-01").leap?
    

    => true

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: