Skip to content

Instantly share code, notes, and snippets.

@jinglescode
Created May 1, 2020 11:39
Show Gist options
  • Save jinglescode/16491fa1b84117cc3e5c58ee5366aa68 to your computer and use it in GitHub Desktop.
Save jinglescode/16491fa1b84117cc3e5c58ee5366aa68 to your computer and use it in GitHub Desktop.
/*
Project Euler: Problem 2: Even Fibonacci NumbersPassed
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 that do not exceed the nth term, find the sum of the even-valued terms.
*/
var test_values = [10, 18, 23, 43];
function run_function(func, test_values) {
for(var i in test_values){
console.log('Test value:', test_values[i]);
var t0 = performance.now();
console.log('Output:', func(test_values[i]));
var t1 = performance.now();
console.log("Took " + (t1 - t0) + " milliseconds.");
console.log();
}
}
function fiboEvenSum(n) {
var fib_nums = [1, 2];
fib_nums = add(n, fib_nums);
var sum = 0;
for(var i in fib_nums){
if(fib_nums[i]%2===0){
sum = sum + fib_nums[i]
}
}
return sum;
}
function add(n, fib_nums){
var c = fib_nums[fib_nums.length-1] + fib_nums[fib_nums.length-2];
fib_nums.push(c);
if(fib_nums.length<n){
return add(n, fib_nums);
}else{
return fib_nums;
}
}
run_function(fiboEvenSum, test_values);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment