Ruby factorial function

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

    Just another way to do it, although it really isn't necessary.

    class Factorial
       attr_reader :num
       def initialize(num)
          @num = num
       end
    
       def find_factorial
          (1..num).inject(:*) || 1
       end
    end
    
    number = Factorial.new(8).find_factorial
    puts number
    
    0 讨论(0)
  • 2020-12-02 10:48

    You will probably find a Ruby feature request useful. It contains a nontrivial patch that includes a demo Bash script. The speed difference between a naive loop and the solution presented in the batch can be literally 100x (hundred fold). Written all in pure Ruby.

    0 讨论(0)
  • 2020-12-02 10:49

    Using Math.gamma.floor is an easy way to produce an approximation and then round it back down to the correct integer result. Should work for all Integers, include an input check if necessary.

    0 讨论(0)
  • 2020-12-02 10:49

    Just one more way to do it:

    # fact(n) => Computes the Factorial of "n" = n!
    
    def fact(n) (1..n).inject(1) {|r,i| r*i }end
    
    fact(6) => 720
    
    0 讨论(0)
  • 2020-12-02 10:51
    class Integer
      def !
        (1..self).inject(:*)
      end
    end
    

    examples

    !3  # => 6
    !4  # => 24
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题