Javascript Number isEven()

Description

Javascript Number isEven()


Number.prototype.isEven = function(){
  return this % 2 === 0;
}

Javascript Number isEven()

/**/*from   www  . j  a va 2s  .  c  o  m*/
 * Problem #2 - Even Fibonacci numbers
 *
 * 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.
 *
 * Answer: 
 */
 
window.log = console.log;
 
function fib(num) {
  return (num < 3) ? num : fib(num - 1) + fib(num - 2);
}

Number.prototype.isEven = function() {
  return (this % 2 === 0) ? true : false;
};

function fibSum() {
  var i = 1,
      sum = 0,
      fibValue = fib(i),
      limit = 4000000; // 4 million
      
  while (fibValue < limit) {
    if (fibValue.isEven()) {
      sum += fibValue;
    }
    i++;
    fibValue = fib(i);  
  }
  return sum;
}

var evenFibSum = fibSum();

log(evenFibSum);

Javascript Number isEven()

Number.prototype.isEven = function () {
    if (this % 2 === 0) {
        return true;
    } else return false;
};

function sumFibs(num) {

    //generate the Fib sequence up to the num

    var sumFibArr;
    var fibArray = fibArrayGenerator(num);

    fibArray = fibArray.filter(function (value) {
        if (value.isEven()) return false;
        else return true;
    });/*from   w w  w . j a  v  a2  s .c  o  m*/

    sumFibArr = fibArray.reduce(function(total, num) {return total + num;});

    return sumFibArr;
}

console.log(sumFibs(3978423455));

function fibArrayGenerator(num) {

    var fibArray = [1];
    var currentFibValue = 1;
    var fibPointer = 0;

    while (currentFibValue <= num) {

        fibArray.push(currentFibValue);
        currentFibValue += fibArray[fibPointer];
        fibPointer++;
    }

    return fibArray;

}



PreviousNext

Related