Ruby factorial function

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

    I just wrote my own:

    def fact(n)
      if n<= 1
        1
      else
        n * fact( n - 1 )
      end
    end
    

    Also, you can define a falling factorial:

    def fall_fact(n,k)
      if k <= 0
        1
      else
        n*fall_fact(n - 1, k - 1)
      end
    end
    

提交回复
热议问题