Created
December 14, 2012 07:36
-
-
Save flakyfilibuster/4283440 to your computer and use it in GitHub Desktop.
Sweet ass factorials in Ruby! #1 - Iterative long
#2 - Iterative short
#3 - Recursive long
#4 - Recursive short
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
# Factorial Recursive # | |
####################### | |
# Long Version: | |
def factorial(n) | |
if n == 0 | |
return 1 | |
else | |
return n*factorial(n-1) | |
end | |
end | |
# Short Version (with ternary operator :D): | |
def factorial(n) | |
n == 0 ? 1 : n*factorial(n-1) | |
end | |
# Factorial Iterative # | |
####################### | |
# Long Version: | |
def factorial(n) | |
sum = 1 | |
until n == 0 | |
sum *= n | |
n -= 1 | |
end | |
sum | |
end | |
# Oh so sweet short version: | |
def factorial(n) | |
(1..n).inject(:*) || 1 | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment