This sequence is composed of numbers. Each number is equal to the previous two numbers added together. Fibonacci sequences occur in nature and have many uses.
With iteration, we can quickly compute a Fibonacci number. In Ruby we use iterators, like "times," for the most elegant code. This makes programs simpler to understand.
In the Fibonacci sequence, each number if the sum of the previous 2 numbers. We can see this clearly by reviewing the sequence itself.
Numbers: 0, 1, 1, 2, 3, 5, 8, 13...
def
Let us begin. We introduce a fibonacci()
method. This receives an integer and returns another one. It receives the position of the Fibonacci sequence we want to compute.
def fibonacci(n) a = 0 b = 1 # Compute Fibonacci number in the desired position. n.times do temp = a a = b # Add up previous two numbers in sequence. b = temp + b end return a end # Write first 15 Fibonacci numbers in sequence. 15.times do |n| result = fibonacci(n) puts result end0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
One of my major goals is not to post incorrect code. I tested the results of this def
against other Fibonacci methods, and it yields the correct results.
This method is slow for repeated computations. We can instead memoize (or cache) Fibonacci numbers, as in a hash or array in Ruby.
This Fibonacci method uses local variables, an iterator, and a method to compute Fibonacci numbers. Its core algorithm is simple. It helps us learn how this sequence is computed.