fibonacci number & fibonacci sequence
https://www.mathsisfun.com/numbers/fibonacci-sequence.html
http://www.shuxuele.com/numbers/fibonacci-sequence.html
fibonacci sequence with cache
"use strict";
/**
*
* @author xgqfrms
* @license MIT
* @copyright xgqfrms
* @created 2020-05-17
* @modified
*
* @description fibonacci 算法缓存优化 javascript
* @augments
* @example
* @link https://en.wikipedia.org/wiki/Fibonacci_number
*
*/
/*
for n = 0 and n = 1, Fn = F(n)
F0 = 0
F1 = 1
for n > 1, Fn = F(n - 1) + F(n - 2);
F2 = F1 + F0 = 1
F3 = F2 + F1 = 2
F4 = F3 + F2 = 3
F5 = F4 + F3 = 5
...
The beginning of the fibonacci sequence is thus:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ...
*/
const log = console.log;
const fib = (n) => {
const caches = [0, 1];
if(n > 1 && typeof caches[n] === "undefined") {
const temp = fib(n - 2) + fib(n - 1);
caches[n] = temp;
}
// log(`caches[n]`, n, caches[n])
return caches[n];
}
// const fib = (n) => {
// const caches = [0, 1];
// if(n === 0 || n === 1) {
// return caches[n];
// } else {
// if(typeof caches[n] === "undefined") {
// const temp = fib(n - 2) + fib(n - 1);
// caches[n] = temp;
// }
// // log(`caches[n]`, n, caches[n])
// return caches[n];
// }
// }
// const fib = (n) => {
// const caches = [0, 1];
// if(n === 0 || n === 1) {
// return caches[n];
// } else {
// // log(`caches[n]`, n, caches[n])
// if(typeof caches[n] !== "undefined") {
// return caches[n];
// } else {
// const temp = fib(n- 2) + fib(n- 1);
// caches[n] = temp;
// return temp;
// }
// }
// }
const v0 = fib(0)
log(`fib0`, v0)
const v1 = fib(1)
log(`fib1`, v1)
const v3 = fib(3)
log(`fib3`, v3)
const v5 = fib(5)
log(`fib5`, v5)
Fibonacci memory 缓存优化
// USING MEMOIZATION
function fibonacci(n,memo) {
memo = memo || {}
if (memo[n]) {
return memo[n]
}
if (n <= 1) {
return 1
}
return memo[n] = fibonacci(n - 1, memo) + fibonacci(n - 2, memo)
}
Fibonacci languages race rank sorter
hackster
https://www.hackster.io/users/preferences?show_welcome=true
©xgqfrms 2012-2020
www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!