seamus
seamus

Reputation: 2901

Find the x amount of factorials starting from 0 using recursion. 5 == [1,1,2,6,24]

I am trying to get the first num factorials.

For example if num is 6 then we would want the first 6 factorials: 1,1,2,6,24,120

Below is my current solution. It always returns an extra factorial. So if num is 6 it returns 7 factorials.

def factorials_rec(num)  
  return [1] if num == 1
  arr = factorials_rec(num-1) 
  arr << num * arr.last
end

Result [1, 1, 2, 6, 24, 120, 720]

Desired result [1, 1, 2, 6, 24, 120]

I only want 6 factorials but 7 are being returned.

Using recursion, how can I adjust this function to return the desired number of factorials.

I have tried

base case = return [1,1] if num == 2, etc..
arr << num * arr.last unless arr.length >= num, etc...

Upvotes: 0

Views: 68

Answers (1)

wWw
wWw

Reputation: 192

Try fixing the last line to:

arr << (num-1) * arr.last

Upvotes: 2

Related Questions