首页 > 编程语言 > 详细

JavaScript生成斐波那契数列

时间:2018-08-05 01:05:26      阅读:205      评论:0      收藏:0      [点我收藏+]

常规写法

https://cn.bing.com/search?q=js+fibonacci+sequence&pc=MOZI&form=MOZSBR

//Fibonacci
function fibonacci(n) {
  var array = [0, 1];

  for (var i = 2; i <= n; i++) {
    array.push(array[i - 1] + array[i - 2]);
  }

  return array[n];
}
var n = 6;
var ans = fibonacci(n);
console.log(ans);

 

生成器

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator

function* idMaker() {
    var index = 0;
    while(true)
        yield index++;
}

var gen = idMaker(); // "Generator { }"

console.log(gen.next().value); // 0
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
// ...

 

 

生成器函数+斐波那契数列

http://cwestblog.com/2011/07/28/javascript-fibonacci-generator-function-and-alternative/

function* fib() {
  var temp, num1 = 0, num2 = 1;
  while (1) {
    yield num1;
    temp = num1;
    num1 = num2;
    num2 += temp;
  }
}
 
// fibonacci generator function
var genFib = fib();
 
// Print the first ten numbers in the fibonacci sequence.
for (var arr = [], i = 0; i < 10; i++) {
  arr.push(genFib.next());
}
alert("1st 10 fibonacci sequence numbers:\n" + arr.join("\n"));

 

JavaScript生成斐波那契数列

原文:https://www.cnblogs.com/lightsong/p/9420753.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!