Thursday, July 31, 2008

How to find out if a given year is a leap year or not?

Well, for that, how do you define a leap year?
Leap year is every year the number of which is a multiple of four, except those devisible by 100 and not by 400.

Here are the steps to determine if a given year is a leap year or not:
if year modulo 400 is 0 then leap
    else if year modulo 100 is 0 then no_leap
    else if year modulo 4 is 0 then leap
    else no_leap

Here is one Perl implementation.

#!/usr/bin/perl
use strict;
use warnings;
###### is_leap_year ######
# Purpose : To determine whether a given year is a leap year or not
# Arguements : One
# First (Number): Year to be checked
# Returns : Boolean value indicating whether given year is a leap year or not
# true = given year is a leap year
# false = given year is not a leap year
############################
sub is_leap_year ($)
{
       my $year = shift;
       return unless ($year =~ m/^\d+$/);

       if (($year % 400) == 0) {
       # This year is completely divisible by 400
               return 1;     # This is a leap year
       }
       elsif (($year % 100) == 0) {
       # This year is completely divisible by 100
               return 0;     # This is not a leap year
       }
       elsif (($year % 4) == 0) {
       # This year is completely divisible by 4
               return 1;     # This is a leap year
       }
       return 0;     # This is not a leap year
}

my $this_year = 2040;
if (is_leap_year ($this_year)) {
       print $this_year, " is a leap year\n";
}
else {
       print $this_year, " is a not a leap year\n";
}

No comments:

Post a Comment