Last active
August 29, 2015 14:20
-
-
Save rattrayalex/5a632db7f35ac7cab4ac to your computer and use it in GitHub Desktop.
recursive multiplication without (-)
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
# Finds product of two positive int's | |
# using only if, (+), and (===). | |
# Usage: mult(x, y) | |
mult = (n1, n2, top=null, orig=null) -> | |
# sanity check (still assuming positive int's) | |
if (n1 is 0) or (n2 is 0) | |
return 0 | |
# on first call | |
if top is null | |
throw new Error() if not (orig is null) | |
orig = n1 | |
top = n2 | |
n2 = 1 | |
# recursion over | |
if n2 is top | |
return n1 | |
# recurse! | |
return mult(orig + n1, n2 + 1, top=top, orig=orig) | |
console.log mult 5, 0 | |
console.log mult 0, 5 | |
console.log mult 1, 30 | |
console.log mult 1, 1 | |
console.log mult 2, 10 | |
console.log mult 10, 5 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment