Home > Blockchain >  Does Ruby already know the Fibonacci Sequence?
Does Ruby already know the Fibonacci Sequence?

Time:10-25

The following method is used to find the nth number in the Fibonacci Sequence:

def fibonacci(number)
  if number < 2
    number
  else
    fibonacci(number - 1)   fibonacci(number - 2)
  end
end

puts fibonacci(6)

The answer is 8 (the sixth number in the sequence if you start counting from 1 and not 0 (0, 1, 1, 2, 3, 5, 8...)

The above code simply deals with the position of numbers in the sequence, right? So how does Ruby already know what the value of a number is at a given position? In the words, how does Ruby know that fibonacci(4) has the value 3 ? Is the Fibonacci sequence already built in to Ruby?

CodePudding user response:

No, the sequence is not built in.

fibonacci is a recursive function. It will be called nine times (!) to compute fibonacci(4) to get 3. (By the way, this is a terrible approach to calculating Fibonacci numbers. 25 calls for fibonacci(6)! It should at least memoize previous calculations.)

CodePudding user response:

So how does Ruby already know what the value of a number is at a given position?

It doesn't already know. It finds out, as part of this method. To find out the value at this position, it first calculates all the values of all the numbers at all the previous positions.

how does Ruby know that fibonacci(4) has the value 3

Because the first thing it does in order to calculate fibonacci(4) is to call fibonacci(3). The algorithm is recursive.

  • Related