Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, …
Find the sum of all the even-valued terms in the sequence which do not exceed four million.
Again, it’s important to read the spec carefully. “do not exceed four million“, i.e. up to and including 4,000,000.
Here’s my code:
<cfset sum = 0> <cfset fibonacci = 1> <cfset old1 = 0> <cfset old2 = 1> <cfloop condition="fibonacci LTE 4000000"> <cfset fibonacci = old1 + old2> <cfset old1 = old2> <cfset old2 = fibonacci> <cfif NOT fibonacci MOD 2> <cfset sum = sum + fibonacci> </cfif> </cfloop> <cfoutput> <p><strong>#sum#</strong></p> </cfoutput>
This time we’re using a While loop, not something I do that often. Using NOT fibonacci MOD 2 gives us all the even values. The only tricky part was working out that I had to use two variables to store the progression of the Fibonacci series. So basically we loop through the entire Fibonacci series up to 4,000,000, keeping a sum of the even values in a separate variable.