当前位置:网站首页>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]
边栏推荐
- 使用StreamAPI 断言组合,结合本地缓存做模糊查询(比mysql效率提升近1000倍)
- IP guard printing control to prevent information disclosure of printing channels
- C#的DataGridView中字体大小
- Lifting method (Part 2) lifting tree
- IP-guard打印管控,防止打印渠道信息泄露
- 联系五心红娘脱单
- Leetcode question brushing: SF Technology Smart logistics Campus Technology Challenge
- 利用do while循环,分别计算1-100中奇数的和、偶数的和【方法一】
- Paml| Shengxin software for calculating dn/ds value
- InstaDeep Ltd:Arthur Flajolet | 单机上基于群体的快速强化学习
猜你喜欢

Lifting method (I) AdaBoost

【深入理解TcaplusDB技术】单据受理之事务执行

IP guard printing control to prevent information disclosure of printing channels

Using streamapi assertion combination and local cache for fuzzy query (nearly 1000 times more efficient than MySQL)

MitoZ|Multi-Kmer mode

University of Virginia: ingy Elsayed aly | logic based reward formation in Multi-Agent Reinforcement Learning

刷题笔记(十六)--二叉树:修改与构造

【深入理解TcaplusDB技术】一键安装Tmonitor后台

Sampler collection

HiC-Pro | HiC数据处理工具
随机推荐
cpu指令重排导致错误的一个例子
Use the for loop to calculate the odd and even sums in 1-100 [method 1]
TRNA analysis using trnascan se
British teddy bear joins the pubg mobile game
实验二 栈和队列
A callback was made to a garbage collected delegate of type "xxx:: invoke". This can cause application crashes, corruption, and data loss. When passing delegates to unmanaged code, the managed applica
使用StreamAPI 斷言組合,結合本地緩存做模糊查詢(比mysql效率提昇近1000倍)
Characteristics and experimental suggestions of abbkine cell cycle Staining Kit
I2C [2] - why does IIC need to use open drain output and pull-up resistor bug
[deeply understand tcapulusdb technology] tmonitor system upgrade
GDB debugging skills (0) getting started with GDB
[deeply understand tcapulusdb technology] transaction execution of document acceptance
class path resource [classpath*:mapper/*.xml] cannot be opened because it does not exist
Introduction to software architecture
【深入理解TcaplusDB技术】单据受理之事务执行
技术分享 | MySQL中一个聚类增量统计 SQL 的需求
浅学Vector---如何使用常见的接口
Use the while loop to calculate the odd and even sums in 1-100 [method 2]
五分钟带你了解云原生
Technology sharing | mysql:caching_ sha2_ Password quick Q & A