Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
recursive multiplication without (-)
# 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