Sums of terms from Fibonacci
Find the sum of all the even-valued terms in the Fibonacci sequence which do not exceed four million.
I would like to use this puzzle as an excuse to explore the Fibonacci sequence. For instance, we know from the definition that each term is the sum of the previous two: and the first two terms of the sequence are given by and . A simple python function that computes the n-th term of this sequence can be then written (in a very naïve way) as follows:
def fib(n): counter,a,b=0,0,1 if n==0: return 0 elif n==1: return 1 else: while counter<n: a,b,counter=b,a+b,counter+1 return a
And a python script using this function that performs the task at hand could be something like this:
contador,sum=0,0 while fib(contador)<4000000: contador+=1 if fib(contador)%2==0: print [contador,fib(contador)] sum+=fib(contador)
A much faster way to compute the same values can be done by exploiting some ideas from linear algebra: Notice that each two successive terms of the sequence satisfy
And tracing back to the first two terms of the sequence (, ), we have
We have turned the code into linear (meaning that we need to do as many computations as a multiple of the input value ), as opposed as the previous code, in which we made a multiple of computations to obtain the n-th term of the sequence, This is a great advantage, but we still need to compute the powers of the matrix each time. Again, to aid in this task we employ some more machinery from linear algebra:
The matrix above is diagonalizable, which means that we can find an invertible matrix and two real numbers such that
In order to compute the matrix and the eigenvalues , we use the characteristic polynomial of the matrix:
which has two different roots The corresponding eigenvectors give us the entries of the matrix : I will leave to the reader as an exercise the verification that, if we denote and then Being this the case, we have
It only remains to put all this information together to be able to write a compact code that computes the n-th term of the Fibonacci sequence in constant time (that is, it takes exactly the same time for any value of ):
We can then write an explicit formula for each term of the Fibonacci sequence:
We are now ready to tackle the puzzle with more sophisticated tools. Notice first that the parity of the Fibonacci numbers has the periodic pattern even, odd, odd, even, odd, odd, even, odd, odd, This helps us identify the even-valued terms of the Fibonacci sequence as for all The answer to our puzzle can then be written as follows: Let such that , then the sum of all even-valued terms of the Fibonacci sequence up to is given by
A nice compact formula: The only missing piece of data is the value of How would the reader find its value?