-
-
Save yclim95/c1eea812cb5f82839efa to your computer and use it in GitHub Desktop.
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
# 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