JavaScript 计算斐波那切数列

斐波那切数列是:1, 1,2,3,5,8,13,21,34......(当前数等于前两个数之和)

这里我们将使用递归函数,递归函数就是函数调用自身的函数。

function feibo(a) {
  for (var i = 1; i <= a; i++){
      if(a == 1 || a == 2) {
        return 1;        
      }
      else  {
        return feibo(a-1) +feibo (a-2);
        }
    }  
}
console.log(feibo(1)); //result: 1
console.log(feibo(2)); //result: 1
console.log(feibo(3)); //result: 2
console.log(feibo(4)); //result: 3
console.log(feibo(5)); //result: 5
console.log(feibo(6)); //result: 8
console.log(feibo(10)); //result: 55

 

Updata

const fibonacci = num => {
  // store the Fibonacci sequence you're going to generate inside an array and initialize the array with the first two numbers of the sequence
  const result = [0, 1]
  for (let i = 2; i <= num; i++) {
    // push the sum of the two numbers preceding the position of i in the result array at the end of the result array
    const prevNum1 = result[i - 1]
    const prevNum2 = result[i - 2]
    result.push(prevNum1 + prevNum2)
  }
  console.log(result)
  console.log(result[num])
}
fibonacci(15)

 

posted @ 2018-12-12 14:12  鑫仔Alan  阅读(215)  评论(0编辑  收藏  举报