Ruby factorial function

前端 未结 19 2132
刺人心
刺人心 2020-12-02 10:31

I\'m going crazy: Where is the Ruby function for factorial? No, I don\'t need tutorial implementations, I just want the function from the library. It\'s not in Math!

19条回答
  •  悲哀的现实
    2020-12-02 10:45

    It's not in the standard library but you can extend the Integer class.

    class Integer
      def factorial_recursive
        self <= 1 ? 1 : self * (self - 1).factorial
      end
      def factorial_iterative
        f = 1; for i in 1..self; f *= i; end; f
      end
      alias :factorial :factorial_iterative
    end
    

    N.B. Iterative factorial is a better choice for obvious performance reasons.

提交回复
热议问题