当前位置:网站首页>js实现斐波那契数列
js实现斐波那契数列
2022-06-21 20:37:00 【samscat】
斐波那契数列:0、1、1、2、3、5、8、13、21、34、……在数学上,斐波那契数列以如下被以递推的方法定义:F(0)=0,F(1)=1, F(n)=F(n - 1)+F(n - 2)(n ≥ 2,n ∈ N*)
// 使用for循环
function fibonacci(n) {
let fibo = [1,1]
let a = 1;
let b = 1;
for (let index = 0; index < n; index++) {
[b, a] = [a, a+b]
fibo.push(a)
}
return fibo.toString()
}
console.log(fibonacci(6))
// 1,1,2,3,5,8,13,21
// 使用while循环
function fibonacci2 (n) {
let nums = [1]
let count = 1;
let prev = 0;
let curr = 1;
if (n == 1) {
return [0]
}
while (count < n - 1) {
curr += prev;
prev = curr - prev;
nums.push(curr);
count ++;
}
nums.unshift(0);
return nums
}
console.log(fibonacci2(6));
// [0, 1, 1, 2, 3, 5]
// 使用递归
function fibonacci3(n) {
if (n < 2) return n
return fibonacci2(n-1) + fibonacci2(n-2)
}
let ff = []
for (let index = 0; index < 6; index++) {
ff.push(fibonacci3(index))
}
console.log(ff)
// [0,1,1,2,3,5]
边栏推荐
- 【深入理解TcaplusDB技术】Tmonitor系统升级
- 联系五心红娘脱单
- 技术分享 | MySQL中一个聚类增量统计 SQL 的需求
- Luogu p1535 [usaco08mar]cow traveling s problem solution
- 迅为iTOP-3568开发板安装 RKNN Toolkit Lite2
- Install RkNN toolkit Lite2 for itop-3568 development board
- 【深入理解TcaplusDB技术】单据受理之表管理
- Pal2Nal|如何在命令行下运行Pal2Nal
- Use the do while loop to calculate the odd and even sums in 1-100 [method 2]
- TRNA analysis using trnascan se
猜你喜欢
![[in depth understanding of tcapulusdb technology] tcapulusdb business data backup](/img/7f/6d42dc96348001dd6ebd724a44a123.png)
[in depth understanding of tcapulusdb technology] tcapulusdb business data backup

安超云入选《CIOReview》2022年亚太区“十大云计算解决方案提供商”

技术分享 | kubernetes pod 简介

Notes on topic brushing (16) -- binary tree: modification and construction
![[deeply understand tcapulusdb technology] tmonitor background one click installation](/img/f6/d2a287aac4ef3dfa8c75f7130202a4.png)
[deeply understand tcapulusdb technology] tmonitor background one click installation

Introduction to software architecture

Implement a middleware from -1

Sampler collection

Nacos安装指南
![[deeply understand tcapulusdb technology] transaction execution of document acceptance](/img/7c/25a88f46e02cebd2e003b9590b9c13.png)
[deeply understand tcapulusdb technology] transaction execution of document acceptance
随机推荐
Luogu p5440 [XR-2] miracle solution
Lifting method (I) AdaBoost
[deeply understand tcapulusdb technology] tmonitor module architecture
【深入理解TcaplusDB技术】TcaplusDB业务数据备份
mafft|多序列比对工具
【深入理解TcaplusDB技术】Tmonitor系统升级
弗吉尼亚大学:Ingy ElSayed-Aly | 多智能体强化学习中的基于逻辑的奖励形成
Iqtree| software for constructing evolutionary tree
利用do while循环,分别计算1-100中奇数的和、偶数的和【方法二】
利用tRNAscan-SE做tRNA分析
File i/o
从-1开始实现一个中间件
Instadeep ltd:arthur flajolet | group based rapid reinforcement learning on a single machine
ES7 create index template
技术分享 | kubernetes pod 简介
Worthington deoxyribonuclease I solution
TRNA analysis using trnascan se
Specificity and application of Worthington Papain
关于eureka启动成功但是访问404问题
InstaDeep Ltd:Arthur Flajolet | 单机上基于群体的快速强化学习