Skip to content

Instantly share code, notes, and snippets.

@nodech
Created November 1, 2015 15:45
Show Gist options
  • Save nodech/1c15551c326d54efc2e1 to your computer and use it in GitHub Desktop.
Save nodech/1c15551c326d54efc2e1 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
# Factorials
def fact(n)
return 1 if n == 1
fact(n - 1) * n
end
def factReduce(n)
(1..n).reduce(:*)
end
def factInject(n)
(1..n).inject { |sum, c| sum * c }
end
def factIter(n)
fact = 1
n.times { |c| fact = fact * (c + 1) }
fact
end
# Factorials
puts fact 2
puts fact 3
puts fact 4
puts fact 5
puts fact 6
puts fact 7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment