- Read Tutorial
- Watch Guide Video
In this lesson, we are going to solve another fun math problem that asks us to solve the problem:
What is the index of the first term in the Fibonacci sequence to contain 1000 digits?
In case your college algebra is a little rusty: Fibonacci sequence is a series where you add the next number to the previous number in that series. These numbers can get massive quickly because of the addition to the previous value creates a mathematical snowball effect.
Though the problem sounds daunting, it can be solved easily in Ruby.
We are going to start by creating a method called fibonacci_digit_counter
and define some variables:
def fibonacci_digit_counter num1, num2, i = -1, 0, 1 end
Next, we will create a while
loop inside of the fibonacci_digit_counter
method and iterate over the digit value of i
.
while i.to_s.length < 1000 num1 += 1 i, num2 = num2, num2 + i end
In this code, we are converting the value of i
to string and calling the length method on it, and we want the loop to run as long as this length is less than 1000
. Inside the loop, num1
is the counter that will keep adding the count every time we iterate, and this value is also the final answer to the problem. However, this variable has nothing to do with the Fibonacci number, as that is managed by the variables i
and num2
.
Also note that we are setting the value of i
to num2
and num2
to the sum of num2 +1
. This is exactly how the Fibonacci series is calculated.
Finally, we are going to return the variable num1
and print the fibonacci_digit_counter
method.
If you run the program, the output is 4782
, which is the correct answer.
The full the code is:
def fibonacci_digit_counter num1, num2, i = -1, 0, 1 while i.to_s.length < 1000 num1 += 1 i, num2 = num2, num2 + i end num1 end p fibonacci_digit_counter