Fibonacci and Efficency

In this example below you will see how to do a Fibonacci and Efficency with some HTML / CSS and Javascript

Thumbnail
This awesome code was written by Ticolyle, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright Ticolyle ©
  • HTML
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>Fibonacci and Efficency</title>
  
  
  
  
  
</head>

<body>

  <h1>Fib.js</h1>
  
  

    <script  src="js/index.js"></script>




</body>

</html>

/*Downloaded from https://www.codeseek.co/Ticolyle/fibonacci-and-efficency-ZJpQBY */
function fibonacciRecursive(n) {
  if(n === 0 || n === 1) {
    return 1;
  }
  return fibonacciRecursive(n-1) + fibonacciRecursive(n-2);
}

document.write('<h2>Recursive</h2>');
document.write(fibonacciRecursive(5));

function fibIt(n) {
if(n === 0 || n === 1) {
          return 1;
      }
  
      var first = 1,
          second = 1,
          acc = 0;
  
      for(var i = 2; i <= n; i++) {
          acc = first + second;
          first = second;
          second = acc;
      }
  
      return acc;
}

document.write('<h2>Iterative</h2>')
document.write(fibIt(5));


function memoFib(num, memo) {
  memo = memo || {};

  if (memo[num]) return memo[num];
  if (num <= 1) return 1;

  return memo[num] = memoFib(num - 1, memo) + memoFib(num - 2, memo);
}

document.write('<h2>Memoization</h2>')
document.write(memoFib(5));

Comments