Skip to content

Instantly share code, notes, and snippets.

@yclim95
Forked from nextacademy-private/factorial.rb
Last active January 13, 2016 17:41
Show Gist options
  • Save yclim95/c1eea812cb5f82839efa to your computer and use it in GitHub Desktop.
Save yclim95/c1eea812cb5f82839efa to your computer and use it in GitHub Desktop.
# Implement an iterative version of the factorial function
def factorial_iterative(n)
total = n
until n == 1
total *= n-1 #if n=2, total=2*n(1)! elseif n=3, total=3*n(2)!
n -= 1
end
total
end
p factorial_iterative(1) == 1
p factorial_iterative(2) == 2
p factorial_iterative(3) == 6
p factorial_iterative(4) == 24
p factorial_recursive(9) == 362880
# Implement a recursive version of the factorial function
def factorial_recursive(n)
return 1 if n==1
n * factorial_recursive(n-1) # if n==2, e.g 2*(2-1)!
end
p factorial_recursive(1) == 1
p factorial_recursive(2) == 2
p factorial_recursive(3) == 6
p factorial_recursive(4) == 24
pfactorial_recursive(9) == 362880
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment