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!
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
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.
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.
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
class Integer
def !
(1..self).inject(:*)
end
end
!3 # => 6
!4 # => 24
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