Sunday, August 17, 2014

Perl GCD

O Perl, how I love you.  Here is a Perl subroutine that finds the greatest common divisor of two integers:

sub gcd
{
  (my $x, my $y ) =

    map abs, grep { $_ } @_;
  $y ? gcd( $y, $x % $y ) : $x
}


and here is  a Perl subroutine that finds the greatest common divisor of any number of integers (including 0 integers, for which it returns undef):

sub gcd
{
  (my $x, my $y, my @others) =

    map abs, grep { $_ } @_;
  $y ? gcd( $y, $x % $y, @others ) : $x
}


note the difference, and how small it is.

No comments: