Ruby factorial function

前端 未结 19 1985
刺人心
刺人心 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 11:05

    With high respect to all who participated and spent their time to help us, I would like to share my benchmarks of the solutions listed here. Params:

    iterations = 1000

    n = 6

                                         user     system      total        real
    Math.gamma(n+1)                   0.000383   0.000106   0.000489 (  0.000487)
    (1..n).inject(:*) || 1            0.003986   0.000000   0.003986 (  0.003987)
    (1..n).reduce(1, :*)              0.003926   0.000000   0.003926 (  0.004023)
    1.upto(n) {|x| factorial *= x }   0.003748   0.011734   0.015482 (  0.022795)
    

    For n = 10

      user     system      total        real
    0.000378   0.000102   0.000480 (  0.000477)
    0.004469   0.000007   0.004476 (  0.004491)
    0.004532   0.000024   0.004556 (  0.005119)
    0.027720   0.011211   0.038931 (  0.058309)
    
    0 讨论(0)
提交回复
热议问题