Created
July 7, 2015 17:25
-
-
Save wagnerjgoncalves/b355630a2c9a928cfde0 to your computer and use it in GitHub Desktop.
Factorial using Hash
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 = Hash.new do |hash, key| | |
if key > 1 | |
hash[key] = hash[key - 1] * key | |
else | |
hash[key] = 1 | |
end | |
end | |
factorial[1] # 1 | |
factorial[2] # 2 | |
factorial[3] # 6 | |
factorial[4] # 24 | |
factorial[5] # 120 | |
factorial # { 1 => 1, 2 => 2, 3 => 6, 4 => 24, 5 => 120 } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment