sub GCD { # The greatest common denominator (GCD) is the largest positive integer # that divides into both numbers without a remainder. # Examples: GCD(256,64)=64, GCD(12,8)=4, GCD(5,3)=1 local($x, $y) = ($_[0], $_[1]); # Work with absolute values (positive integers) $x = -$x if $x < 0; $y = -$y if $y < 0; if (($x+$y) == 0) { # Error, both parameters zero return 0; } local($g) = ($y); # Iterate until x = 0 while($x > 0) { $g = $x; $x = $y % $x; $y = $g; } return $g; }
Hide code
Visustin flow chart for Perl