[NBLUG/talk] Euclid's algorithm in Perl

mrp mrp at sonic.net
Thu May 29 09:53:00 PDT 2003


> #!/usr/bin/perl -w
> use strict;
>
> # This'd be better with the readline library and separate prompts...
> print ("Gimme two ints: ");
> ($int1, $int2) = split(m/\s+/, <>);
>
> print &euc_alg($int1, $int2), "\n";
>
> sub euc_alg {
>     my ($m, $n) = @_;
>     my $r;
>
>     while ($m % $n != 0) {
>         $r = $m % $n;
>         $m = $n;
>         $n = $r;
>     }
>     return $n;
> }


Of course, there's more than one way to do it.  I don't know whether
this is an agument for or against perl.. but:

# slight adaptation.. requires one more loop through, but will usually be 
# faster becuase comparison in each loop is simpler:  You only need to
# compute $m%$n once.

sub euc_alg {
	my ($m,n) = @_;

	($m,$n) = ($n,$m%$n) while $n;

	return $m;
}

  -- Mitch



More information about the talk mailing list