Project Euler problem 2:

*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.

### Like this:

Like Loading...

*Related*

[…] maths, prime number, prime numbers, primes, project euler Problem 1 took a couple of minutes, Problem 2 not much longer than that. Problem 3 took me several hours over a few days to work out! Hopefully […]

Pingback by Project Euler: problem 3 « Duncan’s blog — October 22, 2008 @ 8:05 pm |

[…] In Python, reusing most of the logic from way back in Problem 2: […]

Pingback by Project Euler: problem 25 « Duncan’s blog — January 27, 2009 @ 11:58 pm |

[…] previously blogged about this Project Euler puzzle 6 years ago, using ColdFusion. This is my approach using PHP as a simple practical exercise for myself, and […]

Pingback by Project Euler: problem 2 (PHP) | Duncan's blog — September 20, 2014 @ 8:08 am |