Project Euler 002 – JavaScript

11 02 2011

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, …

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ""&gt;

<html xmlns=""&gt;



    <title>Project Euler 002</title>


<body >

    <script type="text/javascript">

            answer = 0;

            fib0 = 1;

            fib1 = 1;

            fib2 = 2;

            while (fib2 < 4000000)


                answer += fib2;


                fib0 = fib1 + fib2;

                fib1 = fib0 + fib2;

                fib2 = fib0 + fib1;


            document.write("<b>" + answer + "</b>");





C based languages have such similar syntax that this is a copy from the C# solution.  Of course, I had to remove the type declarations because it’s not strongly typed.  Oh, and I guess I do output to HTML.

If you have questions, leave a comment or please find me on Twitter (@azzlsoft) or email (



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: