1

the task is to create a recursion, displaying Fibonacci numbers. I need to display the number chain of Fibonacci numbers in the console, without (for) loop.

I have optimised the recursion and displayed the numbers with a (for) loop.

        "use strict";
        var arr = []
        let skkak = function(n)
        {
          if (n <= 1)
          {
            return n;
          }
          if(!isNaN(arr[n])){
            return arr[n];
          }

          else
          {
            let result = skkak(n - 1) + skkak(n - 2)
            arr[n] = result;
            return result;
          }
        }

        for(let i=12; i > 0; i--)
        {
        console.log(skkak(i));
        }

no errors

  • So you don't want to use all kind of loops at all inside and outside your function? – Abozanona Jun 11 '19 at 08:30
  • Maybe [this](https://stackoverflow.com/questions/36016580/javascript-fibonacci-using-recursion) or [this](https://stackoverflow.com/questions/46161784/generate-fibonacci-number-without-any-looping-recursion) or [this](https://stackoverflow.com/questions/55657978/how-to-implement-fibonacci-number-using-recursion-in-javascript) or [this](https://stackoverflow.com/questions/18980531/javascript-fibonacci-breakdown) or… :-) – RobG Jun 11 '19 at 08:41

1 Answers1

3

This version is using while (not recursive)

        "use strict";
        var arr = []
        let skkak = function(n)
        {
          if (n <= 1)
          {
            return n;
          }
          if(!isNaN(arr[n])){
            return arr[n];
          }

          else
          {
            let result = skkak(n - 1) + skkak(n - 2)
            arr[n] = result;
            return result;
          }
        }
       let i = 12;
       while(i > 0)
        {
          console.log(skkak(i));
          i--;
        }

Recursive approach

fibonacci = (n) =>
{
  if (n===1) 
  {
    return [0, 1];
  } 
  else 
  {
    let s = fibonacci(n - 1);
    s.push(s[s.length - 1] + s[s.length - 2]);
    return s;
  }
};

console.log(fibonacci(5)); // [0,1,1,2,3,5]
Mosè Raguzzini
  • 15,399
  • 1
  • 31
  • 43