美文网首页
斐波那契数列实现的几种方式以及优略

斐波那契数列实现的几种方式以及优略

作者: 多年0以后 | 来源:发表于2021-03-26 10:50 被阅读0次
let arr = []

  function fb(n) {
    if(n < 1) {
      return 0
    } else if(n == 1 || n == 2) {
      return 1
    }
    let first = 1
    let second = 1
    let next = first + second
    for (let i = 3; i < n; i++) {
      first = second
      second = next
      next = first + next
    }
    return next
  }
  function fb2(n) {
    if(n < 1) {
      return 0
    } else if(n == 1 || n == 2) {
      return 1
    } else {
      return fb2(n-2) + fb2(n-1)
    }
  }
  let firstTimeStart = new Date().getTime()
  for (let i=1; i<=40; i++) {
    arr.push(fb(i))
  }
  console.log('the first way used time', new Date().getTime() - firstTimeStart)

  let secondTimeStart = new Date().getTime()
  for (let i=1; i<=40; i++) {
    arr.push(fb2(i))
  }
  console.log( 'the second way used time', new Date().getTime() - secondTimeStart)

相关文章

网友评论

      本文标题:斐波那契数列实现的几种方式以及优略

      本文链接:https://www.haomeiwen.com/subject/rvhpohtx.html