Created
January 6, 2014 02:23
-
-
Save notbenh/8277250 to your computer and use it in GitHub Desktop.
Just playing along with: http://rebekahgolden.com/2014/01/04/art-of-computer-programming-euclids-algorithm/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl | |
use strict; | |
use warnings; | |
print qq{Euclid's Algorithm 1.1E\n\n}; | |
sub littleEuclid { | |
my ($m,$n) = @_; | |
my $remainder = $m % $n; | |
my $reply = $remainder | |
? q{Nope. Reduce. (Here Knuth says in mathematical notation set m to what n is and n to what the remainder is.)} | |
: qq{Yes! The remainder is zero! n is the answer! The answer is $n}; | |
# use a single heredoc to do all of the printing | |
print <<END; | |
Given two numbers m = $m and n = $n, find the greatist common divisor. | |
Find the remainder using the modulus function (%). | |
The remainder is $remainder | |
Is the remainder zero? | |
$reply | |
END | |
# recurse unless the remainder is zero | |
littleEuclid($n,$remainder) if $remainder; | |
} | |
sub microEuclid { | |
my ($m,$n) = @_; | |
return $m % $n | |
? microEuclid($n, $m % $n) | |
: $n | |
} | |
push @ARGV, 125, 15; | |
# pass the first two elements from @ARGV to our function | |
printf qq{The largest remainder of %d and %d is %d.\n} | |
, $ARGV[0] | |
, $ARGV[1] | |
, microEuclid(splice @ARGV, 0, 2); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment