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.
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;
while(num2<value){
temp=num1+num2;
num1=num2;
num2=temp;
if(num2%2==0){
sum+=temp;
}
}
//document.getElementById("output").value=sum;
alert("result ="+sum);
}