ChrisWilson
ChrisWilson

Reputation: 459

Can't get factorial function to work

Factorial 1 and 2 works but 3 and 4 do not. I've worked the steps out on paper and do not see why they do not work. Any help is much appreciated.

def factorial(n)
  x = 1
  y = n

  while x < n
    n = n * (y-x)
    x = x + 1
  end
  return n
end

puts("factorial(1) == 1: #{factorial(1) == 1}")
puts("factorial(2) == 2: #{factorial(2) == 2}")
puts("factorial(3) == 6: #{factorial(3) == 6}")
puts("factorial(4) == 24: #{factorial(4) == 24}")

Upvotes: 1

Views: 78

Answers (2)

Alireza
Alireza

Reputation: 2691

The reason it's not working is that after each loop the value of n gets bigger and the condition x < n keeps executing until it hits a point where n becomes zero. If you pass 3 to the function on the third loop you will have:

while x(3) < n(6)
  n(6) = n(6) * (y(3) - x(3))
end

therefore n becomes 0 causing the loop to exit on the next round and the return value is obviously 0. To fix it you just need to replace n with y in the while condition:

while x < y   

As a side note just another interesting way you could solve the factorial problem using recursion is:

def factorial(n)
  n <= 1 ? 1 : n * factorial(n - 1)
end

Upvotes: 1

Joel
Joel

Reputation: 4593

Try this:

   def factorial(n)
      if n < 0
        return nil
      end

      x = 1
      while n > 0
        x = x * n

        n -= 1
      end

      return x
    end

Upvotes: 1

Related Questions