首页 > 代码库 > JS求斐波那契数列的N项

JS求斐波那契数列的N项

第一种求法:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
  <script>

    var num = [0,1];

    function figure(){

      if(num.length < N){

        var newNum = num[num.length - 1] + num[num.length - 2];

        num.push(newNum);

        figure();

      }else{

        return false;

      }

    }

    figure();

    console.log(num)

  </script>
</body>
</html>

 

 

第二种求法:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
  var num1 = 1;
  var num2 = 1;

  for(var i = 3; i < N; i++){
  var temp = num2;
  num2 = num1 + num2;
  num1 = temp;
  }
  console.log(num2);
</script>
</body>
</html>

JS求斐波那契数列的N项