Search code examples
rubyrecursionlispfactorial

How to write a recursive factorial function in Ruby?


I just want some help with how to write a recursive factorial function in Ruby. I have the following code which is lisp, but I want to do the same thing in Ruby.

(defun factorial (N)
    (if (= N 1) 1
        (* N (factorial (- N 1)))))

Solution

  • Here's how to write the your code in ruby:

    def factorial(n)
      return 1 if n == 1
      n * factorial(n - 1)
    end
    
    factorial(5)
    #=> 120
    factorial(7)
    #=> 5040
    

    Edit for Stefan's comment:

    To avoid a SystemStackError error with large values of n, use the tail-recursive method. Also Ruby's tailcall optimization must be enabled.

    # before edit
    factorial(100_000).to_s.size
    #=> stack level too deep (SystemStackError)
    

    To avoid SystemStackError

    RubyVM::InstructionSequence.compile_option = {
      tailcall_optimization: true,
      trace_instruction: false
    }
    
    RubyVM::InstructionSequence.new(<<-CODE).eval
      def factorial(n, acc = 1)
        return acc if n == 1
        factorial(n - 1, n * acc)
      end
    CODE
    
    puts factorial(100_000).to_s.size
    #=> 456574
    

    Resource 1 Resource 2