Last active
November 24, 2015 16:18
-
-
Save masak/38d295b2525c073ec352 to your computer and use it in GitHub Desktop.
Euclidean division: emulating infix:</> and infix:<%> with only addition, subtraction, multiplication, conditionals, comparison, and recursion
This file contains hidden or 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
multi MAIN { | |
my $a = prompt "a (bigger number): "; | |
my $b = prompt "b (smaller number): "; | |
my ($q, $r) = euclidean($a, $b); | |
say "q: $q"; | |
say "r: $r"; | |
} | |
multi MAIN("test") { | |
use Test; | |
is euclidean(22, 5), [4, 2], "22 // 5 = 4, 22 % 5 = 2"; | |
is euclidean(15, 3), [5, 0], "15 // 3 = 5, 15 % 3 = 0"; | |
is euclidean(501, 5), [100, 1], "501 // 5 = 100, 501 % 5 = 1"; | |
done-testing; | |
} | |
sub euclidean($a is copy, $b) { | |
my $q = 0; | |
sub subtract($d) { | |
if $d * $b * 2 <= $a { | |
subtract($d * 2); | |
} | |
if $a >= $d * $b { | |
$a -= $d * $b; | |
$q += $d; | |
} | |
}(1); | |
return $q, $a; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment