Leap Year
October 5, 2018
Today’s exercise comes from a student who asked for homework help on the internet:
Write a program that determines whether or not a given year is a leap year. A year is a leap year if it is divisible by 4, except that it is not a leap year if it is divisible by 100, except that it is a leap year if it is divisible by 400.
Your task is to write a program to identify leap years. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
Klong version
Examples:
{.p(x,” –> “,leap(x))}'[2018 2016 2000 2100];””
[2018 –> 0]
[2016 –> 1]
[2000 –> 1]
[2100 –> 0]
“”
Here are two solutions in Python.
Output:
A Haskell version.
Built-in in Ruby
=> true
Here’s a short one in Python, two of the mods can be replaced with bitmasks (if we don’t have to worry about negative years):
Recently covered this question in an MATLAB introductory course, so here’s a nice version for vector (or scalar) inputs:
function leap = is_leap_year(year)
mask = mod(year, 100) == 0;
year(mask) = year(mask) / 100;
leap = mod(year, 4) == 0;
end
@Appable: is that like “if year%100 == 0: year //= 100; return year%4 == 0” but for vectorized inputs (‘year(mask)’ is something like ‘the elements of year that have a 1 in mask’)? Interesting.