freeCodeCamp/curriculum/challenges/english/08-coding-interview-prep/project-euler/problem-2-even-fibonacci-nu...

2.0 KiB

id challengeType title
5900f36e1000cf542c50fe81 5 Problem 2: Even Fibonacci Numbers

Description

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 nth term, find the sum of the even-valued terms.

Instructions

Tests

tests:
  - text: <code>fiboEvenSum(10)</code> should return 188.
    testString: assert.strictEqual(fiboEvenSum(10), 188, '<code>fiboEvenSum(10)</code> should return 188.');
  - text: <code>fiboEvenSum(23)</code> should return 60696.
    testString: assert.strictEqual(fiboEvenSum(23), 60696, '<code>fiboEvenSum(23)</code> should return 60696.');
  - text: <code>fiboEvenSum(43)</code> should return 1485607536.
    testString: assert.strictEqual(fiboEvenSum(43), 1485607536, '<code>fiboEvenSum(43)</code> should return 1485607536.');
  - text: Your function is not returning the correct result using our tests values.
    testString: assert.strictEqual(fiboEvenSum(18), 3382, 'Your function is not returning the correct result using our tests values.');
  - text: Your function should return an <code>even</code> value.
    testString: assert.equal(fiboEvenSum(31) % 2 === 0, true, 'Your function should return an <code>even</code> value.');

Challenge Seed

function fiboEvenSum(n) {
  // You can do it!
  return true;
}

fiboEvenSum(10);

Solution

const fiboEvenSum = (number) => {
  let temp, sum = 0, a = 0, b = 1;
    while (number >= 0) {
      temp = a;
      a = b;
      b += temp;
      number --;
      if ((b % 2) === 0) {
        sum += b;
      }
    }

  return sum;
}