How can I get the sum of all odd fibonacci vales in javaScript?

好久不见. 提交于 2019-12-12 03:48:06

问题


I am working through this Free Code Camp exercise.

Return the sum of all odd Fibonacci numbers up to and including the passed number if it is a Fibonacci number. The first few numbers of the Fibonacci sequence are 1, 1, 2, 3, 5 and 8, and each subsequent number is the sum of the previous two numbers.

And here is what I have so far...

Any suggestions?

function sumFibs(num) {
    var arr, isFibVal, isEvenVal, sum, i = 0, fibonacci = function (num){
      var a, b, result, fibArr = [1];
        a=0;
        b=1;
        result=b;

        for(var j = 0; j < num; j++){
            result = a + b;
            a = b;
            b = result;
            fibArr.push(result);

       }
      return fibArr;
    },

     isFib = function (val){
     var prev = 0;
     var curr = 1;
     while(prev<=val){
       if(prev == val){
         return true;
       } else {
         return false;
       }
       curr = prev + curr;
       prev = curr - prev;
     }
    },

   isEven = function(someNumber){
         return (someNumber % 2 === 0) ? true : false;
   };

    function sumArray(array) {
      for (
        var
          index = 0,              // The iterator
          length = array.length,  // Cache the array length
          sum = 0;                // The total amount
          index < length;         // The "for"-loop condition
          sum += array[index++]   // Add number on each iteration
      );
      return sum;
    }


      arr = fibonacci(num);
      isFibVal = isFib(num);
      isEvenVal = isEven(num);


    if (isFibVal && !isEvenVal){
        sum  += sumArray(arr);  
}
   return sum;
}

All I get back is undefined which seems to be weird because i thought this part of my code was pretty cool—using the function values to check vs. in the if statement.

  arr = fibonacci(num);
          isFibVal = isFib(num);
          isEvenVal = isEven(num);


    if (isFibVal && !isEvenVal){
        sum  += sumArray(arr);  
}

回答1:


I won't give you the answer outright since you're going through FCC, but I'll provide you with some hints as to where to look:

See this segment:

for(var j = 0; j < num; j++){
    result = a + b;
    a = b;
    b = result;
    fibArr.push(result);
}

And this one:

function sumArray(array) {
  for (
    var
      index = 0,              // The iterator
      length = array.length,  // Cache the array length
      sum = 0;                // The total amount
      index < length;         // The "for"-loop condition
      sum += array[index++]   // Add number on each iteration
  );
  return sum;
}

Also, you probably don't need this segment at all:

isFibVal = isFib(num);
  isEvenVal = isEven(num);


if (isFibVal && !isEvenVal){
    sum  += sumArray(arr);  

Good luck. As someone who has finished a good chunk of the curriculum, I can say that Free Code Camp is the real deal.




回答2:


You're pretty close and the other answer is good for pushing you in the right direction, I'll post a different way that does this using native JS functions:

Example of the code below in JSBin

function fibs(n) {
  var f = [0, 1];
  var extraNumber = 0;
  for (var i = 0; i < n; i++) {
    f.push(f[f.length - 1] + f[f.length - 2]);
  }
  // lets check if the passed in number is a fib:
  if (f.indexOf(n) > -1) {
    extraNumber = n;
  }
  console.log(f); // just to check we can cut all the logs later...

  var filtered = f.filter(function(num) {
    // filter out the even numbers
    return num % 2 === 1;
  });
  console.log(filtered);

  var sum = filtered.reduce(function(a, b) {
    // add up whats left
    return a + b;
  });
  console.log(sum);
  return sum + extraNumber;
}



回答3:


heres my solution, and i find it to be pretty readable:

function sumOddFibs(num) {
  // initialize with 2 because 
  // fib sequence starts with 1 and 1
  var sum = 2;

  var prev = 1;
  var curr = 1;
  var next = 2;

  while (next <= num) {
    prev = curr;
    curr = next;
    next = prev + curr;

    if (curr % 2 !== 0) {
      sum += curr;
    }
  }
  return sum;
}



回答4:


  1. You could start by defining variables for the previous number, current number, and total Fibonacci

  2. To check for odd numbers, you could use an if statement and use %:

    if (currNum % 2 !== 0){ }

  3. If current number is odd, then you add it to the total

    fibTotal += currNumber;

  4. To determine the next Fibonacci number you, you will need to add the previous and current number:

    var nextNumber = prevNumber + currNumber;

  5. You will need to update the previous number to the current one

    prevNumber = currNumber;

  6. Set the current number to the next Fibonacci number in the sequence

    currNumber = nextNumber;

Hope this helps.



来源:https://stackoverflow.com/questions/36705648/how-can-i-get-the-sum-of-all-odd-fibonacci-vales-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!