Home > database >  Zibonacci recursive, what's wrong with my solution?
Zibonacci recursive, what's wrong with my solution?

Time:10-10

I followed the rules but I still get stack-overflow for n>2.

This function borrows ideas from the Fibonacci series, but the calculated results appear to zig and zag, hence the name. A so-called 'Zibonacci' series would be defined by the following rules:

Zib(0) == 1;
Zib(1) == 1;
Zib(2) == 2;
Zib(2n 1) == Zib(n)   Zib(n-1) 1, if n>0 (i.e. odd values 3 and higher)
Zib(2n) == Zib(n)   Zib(n 1) 1, if n>1 (i.e. even values 4 and higher).

Create the Zibonacci(num) function.

My solution:

function Zibonacci(num){
    // Enter code below
    if(num == 0){
       return 1;
    }
    if(num == 1 || num == 2){
       return num;
    }
    if(num>0 && num%2 != 0){
       return Zibonacci(num)   Zibonacci(num-1) 1;
    }
    if(num>1 && num%2 == 0){
       return Zibonacci(num)   Zibonacci(num 1) 1;
    }
}

enter image description here

CodePudding user response:

You'll first need to reformulate the recursive equations to derive Z(n) instead of Z(2n 1) and Z(2n):

  • Zib(n) == Zib((n - 1) / 2) Zib((n - 1) / 2 - 1) 1, if n>0 (i.e. odd values 3 and higher)
  • Zib(n) == Zib(n / 2) Zib(n / 2 1) 1, if n>1 (i.e. even values 4 and higher).

This leads to code like this:

function Zibonacci(num){
    if (num == 0) {
       return 1;
    }
    if (num == 1 || num == 2) {
       return num;
    }
    if (num > 0 && num % 2 != 0){
       return Zibonacci((num - 1) / 2)   Zibonacci((num - 3) / 2)   1;
    }
    if (num > 1 && num % 2 == 0) {
       return Zibonacci(num / 2)   Zibonacci((num   2) / 2)   1;
    }
}

for (let i = 0; i < 10; i  ) {
    console.log(i, Zibonacci(i));
}

CodePudding user response:

Here is the code

  function Zibonacci(num){
  if(num <= 1) return num;
  return Zibonacci(num -1)   Zibonacci(num-2);
}
console.log(Zibonacci(6));
  • Related