Skip to content

Instantly share code, notes, and snippets.

@afromankenobi
Created August 23, 2017 03:41
Show Gist options
  • Save afromankenobi/b38b058e1b13b20f6eb642a5cca5f49f to your computer and use it in GitHub Desktop.
Save afromankenobi/b38b058e1b13b20f6eb642a5cca5f49f to your computer and use it in GitHub Desktop.
Factorial things
# 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