Ruby factorial function

前端 未结 19 2167
刺人心
刺人心 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:40

    Why would the standard library require a factorial method, when there is a built-in iterator for this exact purpose? It is called upto.

    No you do not need to use recursion, like all these other answers show.

    def fact(n)
      n == 0 ? 1 : n * fact(n - 1)
    end  
    

    Rather, the built-in iterator upto can be used to calculate factorials:

    factorial = 1
    1.upto(10) {|x| factorial *= x }
    factorial
     => 3628800
    

提交回复
热议问题