Skip to content

Instantly share code, notes, and snippets.

@gavinsykes
Created April 29, 2020 21:26
Show Gist options
  • Save gavinsykes/0ed8c84ef8d860866c6ce43fc6a4ea42 to your computer and use it in GitHub Desktop.
Save gavinsykes/0ed8c84ef8d860866c6ce43fc6a4ea42 to your computer and use it in GitHub Desktop.
/*
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.
O,E,O,O,E,O,O,E,O,O,
A number in the Fibonacci sequence can only be even if its 2 preceding terms are either both even or both odd, as it turns out, every 3rd term is even.
As it also turns out, there isn't really a whole lot I can do with this information.
*/
const euler_2 = n => {
let result = 0,
i = 1;
while (fibonacci(i) < n) {
i++;
let f = fibonacci(i);
if(!(f & 1)) {
result += f;
}
}
return result;
}
// Function to work out the fibonacci numbers. Done as an array because it is much much faster than using a recursive function.
const fibonacci = n => {
if (!Number.isInteger(n) || n < 1) {
return undefined;
}
if (n === 1 || n === 2) {
return n;
}
let fibarray = [1,2];
for (let i = 2; i < n; i++) {
fibarray[i] = fibarray[i-1] + fibarray[i-2];
}
return fibarray[n-1];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment