JavaScript 中的斐波那契数列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51111870/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 09:25:12  来源:igfitidea点击:

Fibonacci series in JavaScript

javascriptfibonacci

提问by sumon

function fib(n) {

  const result = [0, 1];
  for (var i = 2; i <= n; i++) {
    const a = (i - 1);
    const b = (i - 2);
    result.push(a + b);
  }
  return result[n];

}

console.log(fib(8));

The output of the code above is 13. I don't understand the for loop part. In very first iteration i = 2, but after second iteration i = 3so a = 2and b = 1and third iteration i = 4so a = 3, b = 2, and so on... If it's going on final sequence will be : [0, 1, 1, 3, 5, 7, 9, 11], which is incorrect. The correct sequence will be [0, 1, 1, 2, 3, 5, 8, 13]

上面代码的输出是13. 我不明白 for 循环部分。在第一次迭代中i = 2,但在第二次迭代后i = 3如此a = 2b = 1第三次迭代i = 4如此a = 3b = 2......如果它继续进行,最终序列将是 : [0, 1, 1, 3, 5, 7, 9, 11],这是不正确的。正确的顺序是[0, 1, 1, 2, 3, 5, 8, 13]

回答by Saif Ur Rahman

You were not using the previous two numbers that are already in the array to > generate the new fibonacci number to be inserted into the array.

您没有使用数组中已有的前两个数字来 > 生成要插入到数组中的新斐波那契数。

https://www.mathsisfun.com/numbers/fibonacci-sequence.html

https://www.mathsisfun.com/numbers/fibonacci-sequence.html

Here I have used the sum of result[i-2]and result[i-1]to generate the new fibonacci number and pushed it into the array.

在这里,我已经使用的总和result[i-2]result[i-1]生成新的Fibonacci数与推到阵列。

Also to generate nnumber of terms you need the condition to be i < nand not i <= n.

此外,要生成n您需要的条件是i < n和不是的条款数i <= n

function fib(n) {

  const result = [0, 1];
  for (var i = 2; i < n; i++) {
    result.push(result[i-2] + result[i-1]);
  }
  return result; // or result[n-1] if you want to get the nth term

}

console.log(fib(8)); 

Return result[n-1]if you want to get the nth term.

返回result[n-1]如果你想获得的第n项。

回答by mojtaba ramezani

My solution for Fibonacci series:

我对斐波那契数列的解决方案:

 const fibonacci = n =>
      [...Array(n)].reduce(
        (acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i),
        []
      )

回答by Cerberus

This function is incorrect. It cat be checked by just adding the console.logcall just before the function return:

此功能不正确。console.log只需在函数返回之前添加调用即可检查它:

function fib(n) {

  const result = [0, 1];
  for (var i = 2; i <= n; i++) {
    const a = (i - 1);
    const b = (i - 2);
    result.push(a + b);
  }
  console.log(result);
  return result[n];

}

console.log(fib(7));

As you can see, the sequence is wrong and (for n = 7) the return value is too.

如您所见,序列是错误的,并且(对于n = 7)返回值也是错误的。

The possible change would be as following:

可能的变化如下:

function fib(n) {

  const result = [0, 1];
  for (var i = 2; i <= n; i++) {
    const a = result[i - 1];
    const b = result[i - 2];
    result.push(a + b);
  }
  console.log(result);
  return result[n];

}

console.log(fib(8));

This is the "classical" Fibonacci numbers; if you really want to use the first number of 0, not 1, then you should return result[n-1], since array indexes start from zero.

这是“经典”斐波那契数列;如果你真的想使用第一个数字0,而不是1,那么你应该return result[n-1],因为数组索引从零开始。

回答by Tom O.

One approach you could take for fibonacci sequence is recursion:

您可以对斐波那契数列采取的一种方法是递归:

var fibonacci = {
  getSequenceNumber: function(n) {
    //base case to end recursive calls
    if (n === 0 || n === 1) {
      return this.cache[n];
    }

    //if we already have it in the cache, use it
    if (this.cache[n]) {
      return this.cache[n];
    }
    //calculate and store in the cache for future use
    else {
      //since the function calls itself it's called 'recursive'
      this.cache[n] = this.getSequenceNumber(n - 2) + this.getSequenceNumber(n - 1);
    }

    return this.cache[n];
  },

  cache: {
    0: 0,
    1: 1
  }
}
//find the 7th number in the fibbonacci function
console.log(fibonacci.getSequenceNumber(7));

//see all the values we cached (preventing extra work)
console.log(fibonacci.cache);

//if you want to output the entire sequence as an array:
console.log(Object.values(fibonacci.cache));

The code above is also an example of a dynamic programmingapproach. You can see that I am storing each result in a cacheobject the first time it is calculated by the getSequenceNumbermethod. This way, the second time that getSequenceNumberis asked to find a given input, it doesn't have to do any actual work - just grab the value from cacheand return it! This is an optimization technique that can be applied to functions like this where you may have to find the value of a particular input multiple times.

上面的代码也是动态编程方法的一个例子。您可以看到我将每个结果在cache第一次由该getSequenceNumber方法计算时存储在一个对象中。这样,第二次getSequenceNumber被要求查找给定的输入时,它不需要做任何实际工作——只需从中获取值cache并返回它!这是一种优化技术,可以应用于这样的函数,您可能需要多次找到特定输入的值。

回答by patki

simple solution for Fibonacci series:

斐波那契数列的简单解决方案:

function fib(n){
    var arr = [];
    for(var i = 0; i <n; i++ ){
        if(i == 0 || i == 1){
            arr.push(i);
        } else {
            var a = arr[i - 1];
            var b = arr[i - 2];
            arr.push(a + b);
        }
    }
    return arr
}
console.log(fib(8))

回答by ShawnTG71

This is certainly one of those "more than one way to clean chicken" type situations, this JavaScript method below works for me.

这当然是“不止一种清洁鸡肉的方法”类型的情况之一,下面的这个 JavaScript 方法对我有用。

function fibCalc(n) {
    var myArr = [];

    for (var i = 0; i < n; i++) {
        if(i < 2) {
            myArr.push(i);
        } else {
            myArr.push(myArr[i-2] + myArr[i-1]);
        }
    } 

    return myArr;
}

fibCalc(8);

When called as above, this produces [0,1,1,2,3,5,8,13] It allows me to have a sequence of fib numbers based on n.

当如上所述调用时,这会产生 [0,1,1,2,3,5,8,13] 它允许我有一个基于 n 的 fib 数字序列。

回答by Adrian Brand

const fib = n => {
  const array = Array(n);
  for (i = 0; i < array.length; i++) {
    if (i > 1) {
      array[i] = array[i - 1] + array[i - 2];
    } else {
      array[i] = 1;
    }
  }
  return array;
}

console.log(fib(5))

回答by AYO O.

function fib(n) {
    const result = [0];

    if (n > 1) {
        result.push(1);

        for (var i = 2; i < n; i++) {
            const a = result[result.length - 1]
            const b = result[result.length - 2];
            result.push(a + b);
        }

    }
    console.log(result);
}

回答by Viraj

i came up with this solution to get the n index fibonacci value.

我想出了这个解决方案来获得 n 指数斐波那契值。

function findFac(n){
if (n===1) 
  {
   return [0, 1];
  } 
  else 
  {
    var s = findFac(n - 1);
    s.push(s[s.length - 1] + s[s.length - 2]);
    return s;
  }
}

function findFac0(n){
var vv1 = findFac(n);
return vv1[n-1];
}


console.log(findFac0(10));

回答by Kiran Racherla

Here, you have it, with few argument check, without using exception handling

在这里,您拥有它,只需很少的参数检查,无需使用异常处理

function fibonacci(limit){
    if(typeof limit != "number"){return "Please enter a natural number";}

    if(limit <=0){
        return "limit should be at least 1";
    }
    else if(limit == 1){
        return [0];
    }
    else{
        var series = [0, 1];
        for(var num=1; num<=limit-2; num++){
            series.push(series[series.length-1]+series[series.length-2]);
        }
        return series;
    }
}