Created
August 23, 2017 03:41
-
-
Save afromankenobi/b38b058e1b13b20f6eb642a5cca5f49f to your computer and use it in GitHub Desktop.
Factorial things
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
# Extend Integer class to add factorial related methods | |
class Integer | |
# Iterative factorial | |
def factorial | |
# fail if this is called by negative numbers | |
raise ArgumentError, 'Not valid for negative numbers' if self < 0 | |
return 1 if zero? | |
# iterates backwards and inject * to the acumulator | |
downto(1).inject(:*) | |
end | |
def count_end_zeros | |
return 1 if zero? | |
(self % 5).zero? ? 1 + (self / 5).count_end_zeros : 0 | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment