fibonacci number & fibonacci sequence


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

https://9wlnh.csb.app/

hackster

https://www.hackster.io/users/preferences?show_welcome=true



Flag Counter

©xgqfrms 2012-2020

www.cnblogs.com 發布文章使用:只允許注冊用戶才可以訪問!



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM