in reply to Finding the greatest common divisor

This is an inelegant brute force approach:

my $num1 = 150; my $num2 = 1000; # set which is biggest and which smallest my $max = ($num1 > $num2)? $num1 : $num2; my $min = ($num1 < $num2)? $num1 : $num2; for $divisor (reverse 0 .. $min) { # fail unless our divisor divides evenly into $min next if $min % $divisor; # fail unless our divisor divides evenly into $max next if $max % $divisor; print "Largest common divisor is $divisor\n"; last; }

This is O(n) in that the bigger the smaller number the longer this will take to run. For a more elegant approach use Euclid's recursive algorithm as suggested by larsen it is O(log $a * log $b) - ie so much more efficient it is not funny!:

print euclid(15000,1260); sub euclid { my( $a, $b ) = @_; return ($b) ? euclid( $b, $a % $b ) : $a; }

cheers

tachyon

s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print