DEV Community

Cover image for Project Euler - Problem 2 - Even Fibonacci Numbers
Jingles (Hong Jing)
Jingles (Hong Jing)

Posted on • Edited on • Originally published at jinglescode.github.io

Project Euler - Problem 2 - Even Fibonacci Numbers

The problem

This is problem 2 from the Project Euler.

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.


Let's begin

Initialise variables and common functions:

var test_values = [10, 18, 23, 43]; // list of numbers we wanna test

// this function execute the code and records the time to execute
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();
  }
}

Attempt #1: recursive functions

The recursive way...

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

The output:

Test value: 10
Output: 44
Took 0.13000000035390258 milliseconds.

Test value: 18
Output: 3382
Took 0.05999999848427251 milliseconds.

Test value: 23
Output: 60696
Took 0.1049999991664663 milliseconds.

Test value: 43
Output: 350704366
Took 0.08000000525498763 milliseconds.

Here's my solution, can it be any better?

This is my Project Euler Challenge journey; anyone wants to do this together? It will be fun and we can learn a thing or two by solving this problem in different ways.

Top comments (0)