ðŸ“˜ Computing leap years in Perl 6

ðŸ“˜ Computing leap years in Raku

N. B. Perl 6 has been renamed to Raku. Click to read more.

Tell if the given year is leap or common.

The algorithm for detecting whether the year is leap includes a few divisibility tests. Take an extract in the pseudocode from Wikipedia:

ifÂ (yearÂ is notÂ divisibleÂ by 4)Â thenÂ (it is a common year)
else ifÂ (yearÂ is not divisible by 100)Â thenÂ (it is a leap year)
else ifÂ (yearÂ is not divisible by 400)Â thenÂ (it is a common year)
elseÂ (it is a leap year)

It is possible to implement the above sequence of ifs and elses in Perl 6, but it is a better idea to join conditions using the logical operators.

`my \$year = 2018;say (\$year %% 400 or \$year % 100 and \$year %% 4) ??    'Leap' !! 'Common';`

Notice that both the moduloÂ `%` and divisibilityÂ `%%` operators are used, which allow avoiding Boolean negations in the sub-conditions.

The following program prints the list of leap years in the range 1800â€“2400:

`for 1800 .. 2400 -> \$year {    say \$year if \$year %% 400 or \$year % 100 and \$year %% 4;}`

There may be some considerations regarding the efficiency of the sequence of the checks because each year is first tested against 400, while it may be more optimal to check first if the year is divisible by 4. If this becomes an important argument, then theÂ `if``else` chain may be more efficient. To achieve an even higher speed, a pre-calculated array of leap years is better.