Fibonnaci Sequence
Counts even numbers up to 4000000 in the fibonacci sequence e.g. 1+2 = 3, 3+2 = 5
by LyndseyB
HTML
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.
JavaScript
/*var i = 0,
arr = [1,2],
num1 = arr[arr.length-1], //2
num2 = arr[arr.length-2], //1
evenSum = 0;
function fib(num1,num2) {
if((num1+num2)<4000000) {
arr.push(num1+num2); // push next item
fib(arr[arr.length-1], arr[arr.length-2]);
}
}
fib(num1,num2); // start recursion
console.log(arr); // output array
// find sum of even numbers
for(x in arr) {
if(arr[x] % 2 === 0) {
evenSum+=arr[x];
//console.log(arr[x]);
}
}
// sum of even items
console.log(evenSum);*/
var arr = [],
totalEven = 0;
function fib(n,n2) {
var sum = n+n2;
if(sum<4000000) {
arr.push(sum); // push new item
if(sum % 2 === 0) {
totalEven+=sum; // get total even sum
}
num1 = arr[arr.length-1];
num2 = arr[arr.length-2] || 1; // if theres no n-1 value, assume 1
fib(num1,num2);
}
}
fib(0,1);
console.log(totalEven);