简体   繁体   English

如何在javaScript中获得所有奇数斐波那契值的总和?

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

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. 斐波那契数列的前几个数字是1、1、2、3、5和8,每个后续数字是前两个数字的总和。

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. 我得到的所有信息都是undefined ,这似乎很奇怪,因为我认为代码的这一部分非常酷-使用函数值检查if语句中的vs。

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


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

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: 由于您正在接受FCC认证,因此我不会直接为您提供答案,但我会为您提供一些提示,以帮助您查找:

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. 作为完成了大部分课程的人,我可以说Free Code Camp是真正的交易。

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: 您的位置非常接近,其他答案也很适合将您推向正确的方向,我将发布使用本地JS函数执行此操作的另一种方法:

Example of the code below in JSBin 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;
}

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;
}
  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语句并使用%:

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

  3. If current number is odd, then you add it to the total 如果当前数字为奇数,则将其添加到总数中

    fibTotal += currNumber; fibTotal + = currNumber;

  4. To determine the next Fibonacci number you, you will need to add the previous and current number: 要确定您的下一个斐波那契编号,您需要添加上一个和当前编号:

    var nextNumber = prevNumber + currNumber; var nextNumber = prevNumber + currNumber;

  5. You will need to update the previous number to the current one 您需要将之前的号码更新为当前号码

    prevNumber = currNumber; prevNumber = currNumber;

  6. Set the current number to the next Fibonacci number in the sequence 将当前编号设置为序列中的下一个斐波那契编号

    currNumber = nextNumber; currNumber = nextNumber;

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM