Even Fibonacci numbers under 4,000,000 (Project Euler #2)

Prompt:

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.

• 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;

while(num2<value){
temp=num1+num2;
num1=num2;
num2=temp;
if(num2%2==0){
sum+=temp;
}
}

//document.getElementById("output").value=sum;
}

• For mathematical solutions, I suggest reading this answer of mine to a different question. (Skip to the $\LaTeX$.) – Veedrac Jun 25 '15 at 16:22

Naming

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?

Scope

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

Algorithm

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.

• OK, so should I delete this answer? – user34073 Jun 25 '15 at 16:36
• @Hosch250 Can you give me a reference to equation that you have mention. – menaka Jun 25 '15 at 18:17
• @menaka It is in the link provided, just lower down. – user34073 Jun 25 '15 at 18:17
• 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  – 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 =[]
fib.append(1);fib.append(2)
for i in range(2,50):
fib.append(fib[i-1]+fib[i-2])
N=input()
i=1;sum=0
while(fib[i]<=N):
sum+=fib[i]
i+=3
print sum

• What is the point of creating an array ? – bhathiya-perera Jul 4 '15 at 14:14
• @Bhathiya Because if there are multiple queries we don't need to compute them again and again. – Lakshman Jul 13 '15 at 16:37