Ruby factorial function

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

    I would do

    (1..n).inject(1, :*)
    
    0 讨论(0)
  • 2020-12-02 10:58

    Here is my version seems to be clear to me even though it's not as clean.

    def factorial(num)
        step = 0
        (num - 1).times do (step += 1 ;num *= step) end
        return num
    end
    

    This was my irb testing line that showed each step.

    num = 8;step = 0;(num - 1).times do (step += 1 ;num *= step; puts num) end;num
    
    0 讨论(0)
  • 2020-12-02 11:00

    There is no factorial function in the standard library.

    0 讨论(0)
  • 2020-12-02 11:00

    Like this is better

    (1..n).inject(:*) || 1
    
    0 讨论(0)
  • 2020-12-02 11:00

    You could also use Math.gamma function which boils down to factorial for integer parameters.

    0 讨论(0)
  • 2020-12-02 11:03

    And yet another way (=

    def factorial(number)
      number = number.to_i
      number_range = (number).downto(1).to_a
      factorial = number_range.inject(:*)
      puts "The factorial of #{number} is #{factorial}"
    end
    factorial(#number)
    
    0 讨论(0)
提交回复
热议问题