Sha256: a5f69f188e562854092a5890d6412b02b6b4e7d35ebc6c1d9c788b58cfc405b9

Contents?: true

Size: 1.14 KB

Versions: 10

Compression:

Stored size: 1.14 KB

Contents

# = FILE
#
#   interger/factorial.rb
#
# = DESCRIPTION
#
#   Factorial extension for Integer class.
#
# = AUTHORS
#
#   CREDIT Malte Milatz

#

class Integer

  # Calculate the factorial of an integer.
  #
  #   2.factorial  #=> 2
  #   3.factorial  #=> 6
  #   3.factorial  #=> 24
  #

  def factorial
    return 1 if zero?
    f = 1
    2.upto(self) { |n| f *= n }
    f
  end

  #--
  # TODO Pick one of these and deprecate the other. But which?
  #++
  alias_method( :fac, :factorial )
  alias_method( :fact, :factorial )

  #-- OLD CODE
  #def factorial
  #  return 1 if self == 0
  #  #self == 0 ? 1 : ( self * (self-1).factorial )
  #  f = (1..self.abs).inject { |state, item| state * item }
  #  return self < 0 ? -f : f
  #end
  #++

end



#  _____         _
# |_   _|__  ___| |_
#   | |/ _ \/ __| __|
#   | |  __/\__ \ |_
#   |_|\___||___/\__|
#
=begin test

  require 'test/unit'

  class TCInteger < Test::Unit::TestCase

    def test_factorial
      assert_equal(  1, 0.factorial )
      assert_equal(  1, 1.factorial )
      assert_equal(  2, 2.factorial )
      assert_equal(  6, 3.factorial )
      assert_equal( 24, 4.factorial )
    end

  end

=end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
facets-2.0.1 lib/core/facets/integer/factorial.rb
facets-2.0.0 lib/core/facets/integer/factorial.rb
facets-2.0.2 lib/core/facets/integer/factorial.rb
facets-2.1.0 lib/core/facets/integer/factorial.rb
facets-2.1.1 lib/core/facets/integer/factorial.rb
facets-2.1.2 lib/core/facets/integer/factorial.rb
facets-2.0.4 lib/core/facets/integer/factorial.rb
facets-2.0.5 lib/core/facets/integer/factorial.rb
facets-2.0.3 lib/core/facets/integer/factorial.rb
facets-2.1.3 lib/core/facets/integer/factorial.rb