Javascript 生成斐波那契数列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7944239/
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
Generating Fibonacci Sequence
提问by methuselah
var x = 0;
var y = 1;
var z;
fib[0] = 0;
fib[1] = 1;
for (i = 2; i <= 10; i++) {
alert(x + y);
fib[i] = x + y;
x = y;
z = y;
}
I'm trying to get to generate a simple Fibonacci Sequence but there no output.
我试图生成一个简单的斐波那契数列,但没有输出。
Can anybody let me know what's wrong?
任何人都可以让我知道出了什么问题吗?
回答by Alex Cory
According to the Interview Cakequestion, the sequence goes 0,1,1,2,3,5,8,13,21. If this is the case, this solution works and is recursive without the use of arrays.
根据面试蛋糕问题,序列为0,1,1,2,3,5,8,13,21。如果是这种情况,则此解决方案有效并且无需使用数组即可递归。
function fibonacci(n) {
return n < 1 ? 0
: n <= 2 ? 1
: fibonacci(n - 1) + fibonacci(n - 2);
}
console.log(fibonacci(4));
Think of it like this.
像这样想。
fibonacci(4) .--------> 2 + 1 = 3
| / |
'--> fibonacci(3) + fibonacci(2)
| ^
| '----------- 2 = 1 + 1 <----------.
1st step -> | ^ |
| | |
'----> fibonacci(2) -' + fibonacci(1)-'
Take note, this solution is not very efficient though.
请注意,尽管此解决方案效率不高。
回答by Rob W
You have never declared fib
to be an array. Use var fib = [];
to solve this.
您从未声明fib
为数组。使用var fib = [];
来解决这个问题。
Also, you're never modifying the y
variable, neither using it.
此外,您永远不会修改y
变量,也不会使用它。
The code below makes more sense, plus, it doesn't create unused variables:
下面的代码更有意义,此外,它不会创建未使用的变量:
var i;
var fib = []; // Initialize array!
fib[0] = 0;
fib[1] = 1;
for (i = 2; i <= 10; i++) {
// Next fibonacci number = previous + one before previous
// Translated to JavaScript:
fib[i] = fib[i - 2] + fib[i - 1];
console.log(fib[i]);
}
回答by irth
Here's a simple function to iterate the Fibonacci sequence into an array using arguments in the for
function more than the body of the loop:
这是一个简单的函数,它使用函数中的参数而for
不是循环体将斐波那契数列迭代到数组中:
fib = function(numMax){
for(var fibArray = [0,1], i=0,j=1,k=0; k<numMax;i=j,j=x,k++ ){
x=i+j;
fibArray.push(x);
}
console.log(fibArray);
}
fib(10)
[ 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 ]
[ 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 ]
回答by gion_13
You should've declared the fib
variable to be an array in the first place (such as var fib = []
or var fib = new Array()
) and I think you're a bit confused about the algorithm.
If you use an array to store the fibonacci sequence, you do not need the other auxiliar variables (x,y,z
) :
您应该首先将fib
变量声明为数组(例如var fib = []
or var fib = new Array()
),我认为您对算法有点困惑。
如果使用数组存储斐波那契数列,则不需要其他辅助变量 ( x,y,z
) :
var fib = [0, 1];
for(var i=fib.length; i<10; i++) {
fib[i] = fib[i-2] + fib[i-1];
}
console.log(fib);
Click for the demo
点击演示
You should consider the recursive method too (note that this is an optimised version) :
您也应该考虑递归方法(请注意,这是一个优化版本):
function fib(n, undefined){
if(fib.cache[n] === undefined){
fib.cache[n] = fib(n-1) + fib(n-2);
}
return fib.cache[n];
}
fib.cache = [0, 1, 1];
and then, after you call the fibonacci function, you have all the sequence in the fib.cache
field :
然后,在您调用 fibonacci 函数后,您将拥有fib.cache
字段中的所有序列:
fib(1000);
console.log(fib.cache);
回答by Dimitris Zorbas
Yet another answer would be to use es6 generator functions.
另一个答案是使用 es6生成器函数。
function* fib() {
var current = a = b = 1;
yield 1;
while (true) {
current = b;
yield current;
b = a + b;
a = current;
}
}
sequence = fib();
sequence.next(); // 1
sequence.next(); // 1
sequence.next(); // 2
// ...
回答by Jon Skeet
You're not assigning a value to z
, so what do you expect y=z;
to do? Likewise you're never actually readingfrom the array. It looks like you're trying a combination of two different approaches here... try getting rid of the array entirely, and just use:
您没有为 赋值z
,那么您希望y=z;
做什么?同样,你从来没有真正从数组中读取。看起来你在这里尝试结合两种不同的方法......尝试完全摆脱数组,然后使用:
// Initialization of x and y as before
for (i = 2; i <= 10; i++)
{
alert(x + y);
z = x + y;
x = y;
y = z;
}
EDIT: The OP changed the code after I'd added this answer. Originally the last line of the loop wasy = z;
- and that makes sense ifyou've initialized z
as per my code.
编辑:在我添加这个答案后,OP 更改了代码。最初循环的最后一行是y = z;
-如果您z
按照我的代码进行了初始化,那是有道理的。
If the array is required later, then obviously that needs to be populated still - but otherwise, the code I've given should be fine.
如果稍后需要该数组,那么显然仍然需要填充它 - 但否则,我给出的代码应该没问题。
回答by Kodejuice
The golden ration "phi" ^ n / sqrt(5) is asymptotic to the fibonacci of n, if we round that value up, we indeed get the fibonacci value.
黄金比例 "phi" ^ n / sqrt(5) 渐近于 n 的斐波那契,如果我们将该值向上取整,我们确实得到了斐波那契值。
function fib(n) {
let phi = (1 + Math.sqrt(5))/2;
let asymp = Math.pow(phi, n) / Math.sqrt(5);
return Math.round(asymp);
}
fib(1000); // 4.346655768693734e+208 in just 0.62s
This runs faster on large numbers compared to the recursion based solutions.
与基于递归的解决方案相比,这在大量数据上运行得更快。
回答by Mikhail
function fib(n) {
if (n <= 1) {
return n;
} else {
return fib(n - 1) + fib(n - 2);
}
}
fib(10); // returns 55
回答by Redu
I just would like to contribute with a tail call optimized version by ES6. It's quite simple;
我只想贡献一个 ES6 的尾调用优化版本。这很简单;
var fibonacci = (n, f = 0, s = 1) => n === 0 ? f : fibonacci(--n, s, f + s);
console.log(fibonacci(12));
回答by AKHIL
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>fibonacci series</title>
<script type="text/javascript">
function generateseries(){
var fno = document.getElementById("firstno").value;
var sno = document.getElementById("secondno").value;
var a = parseInt(fno);
var result = new Array();
result[0] = a;
var b = ++fno;
var c = b;
while (b <= sno) {
result.push(c);
document.getElementById("maindiv").innerHTML = "Fibonacci Series between "+fno+ " and " +sno+ " is " +result;
c = a + b;
a = b;
b = c;
}
}
function numeric(evt){
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
var regex = /[0-9]|\./;
if (!regex.test(key)) {
theEvent.returnValue = false;
if (theEvent.preventDefault)
theEvent.preventDefault();
}
}
</script>
<h1 align="center">Fibonacci Series</h1>
</head>
<body>
<div id="resultdiv" align="center">
<input type="text" name="firstno" id="firstno" onkeypress="numeric(event)"><br>
<input type="text" name="secondno" id="secondno" onkeypress="numeric(event)"><br>
<input type="button" id="result" value="Result" onclick="generateseries();">
<div id="maindiv"></div>
</div>
</body>
</html>