Skip to content

Instantly share code, notes, and snippets.

@rattrayalex
Last active August 29, 2015 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rattrayalex/5a632db7f35ac7cab4ac to your computer and use it in GitHub Desktop.
Save rattrayalex/5a632db7f35ac7cab4ac to your computer and use it in GitHub Desktop.
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