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.

I'd like advice on:

  • Using mathematical formulas instead of loops to calculate this
  • Making the code more efficient

This is my solution:

   function EvenFibonacciNumbers(){
            var value=parseInt(document.getElementById("input").value);
            var sum=0;
            var temp=0;
            var num2=1;
            var num1=1;


            alert("result ="+sum);
  • 2
    \$\begingroup\$ For mathematical solutions, I suggest reading this answer of mine to a different question. (Skip to the \$\LaTeX\$.) \$\endgroup\$ – Veedrac Jun 25 '15 at 16:22


var num1

That doesn't tell me what the variable is and does. Is it the smallest Fibonacci number in the two needed to calculate the next?


Using spaces around your operators helps readability, which helps prevent bugs.


temp is only used in the while() loop, so you can reduce its scope.


The Fibonacci numbers go even/odd/odd/even/odd/odd... There is a good reason for this - they start with an even number (0), and an odd number (1). Even numbers plus odd numbers are odd numbers, so we get another odd number (1). Odd numbers plus odd numbers are even numbers, so we know this pattern will continue. With this knowledge, we only need to calculate every 3rd number.

| improve this answer | |
  • \$\begingroup\$ OK, so should I delete this answer? \$\endgroup\$ – user34073 Jun 25 '15 at 16:36
  • \$\begingroup\$ @Hosch250 Can you give me a reference to equation that you have mention. \$\endgroup\$ – menaka Jun 25 '15 at 18:17
  • \$\begingroup\$ @menaka It is in the link provided, just lower down. \$\endgroup\$ – user34073 Jun 25 '15 at 18:17
  • \$\begingroup\$ You can also do a much less expensive check for integer oddness with the bitwise & operator. This will evaluate to true: if (num2 & 1) // if num2 is odd \$\endgroup\$ – jperl Jun 25 '15 at 20:38

You don't need to check for even fibonacci , because in fibonacci sequence every third number is even(previous two odd numbers sum is even). Below is simple Python implementation.

fib =[]
for i in range(2,50):
print sum
| improve this answer | |
  • \$\begingroup\$ What is the point of creating an array ? \$\endgroup\$ – bhathiya-perera Jul 4 '15 at 14:14
  • \$\begingroup\$ @Bhathiya Because if there are multiple queries we don't need to compute them again and again. \$\endgroup\$ – Lakshman Jul 13 '15 at 16:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.