在 JavaScript 中使用循环查找第 n 项斐波那契数列

finding the nth term fibonacci sequence using loop in javascript

本文关键字:数列 JavaScript 查找 循环      更新时间:2023-09-26

我只是Javascript的新手,我想问你一个关于如何制作一个简单的斐波那契生成器的问题,当用户输入任何数字时,它将找到斐波那契数列的第n项。给出了示例代码。

<html>
<body>
the number inserted in this textbox will find the nth term of the fibonacci sequence. The sample is 4 where the 4th term is 5. 
<script type="text/javascript">
function myFunction() {
var x = document.f1.n1.value;
if(x=4) {
document.write(5);
}
}
</script>
<form name="f1" onsubmit="return false">
First no. <input type="text"name="n1" value=3 disabled>
<input type="submit" value=GO onClick="myFunction()">
</form>
</body>
</html>

下面是一个使用递归调用的工作示例:

function myFunction(getLucas) {
  var x = document.f1.n1.value;
  if (getLucas) {
      alert(lucas(x));
  }
  else {
      alert(fib(x));
  }
}
function fib(n) {
  if (n < 2) {
      return n;
  }
  else {
      return fib(n - 1) + fib(n - 2);
  }
}
function lucas(n) {
  if (n < 2) {
      return 2-n;
  }
  else {
      return lucas(n - 1) + lucas(n - 2);
  }
}
<form name="f1" onsubmit="return false">
  First no.
  <input type="text" name="n1" value="3">
  <input type="submit" value="Fibonacci" onClick="myFunction()">
  <input type="submit" value="Lucas" onClick="myFunction(true)">
</form>

document.write(getAmount(x));
function getAmount(x) {
    if(x < 3) {
        return 1;
    } else { 
        return getAmount(x - 1) + getAmount(x - 2);
    }
}

不确定是否所有正确的符号/语言,但这是您需要的逻辑。