Skip to content

Instantly share code, notes, and snippets.

@flakyfilibuster
Created December 14, 2012 07:36
Show Gist options
  • Save flakyfilibuster/4283440 to your computer and use it in GitHub Desktop.
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
# 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