1

I need a recursive function which can get me the index of a Fibonacci number passed to it.

For example, the mentioned function should return 6 when we pass 8; or it should return 8 when we pass 21.

Any help would be appreciated. Thanks !

HoseinGhanbari
  • 1,058
  • 1
  • 11
  • 23

1 Answers1

2

This is my solution !
It works fine and return what I expect.
Make sure that a and b have their own default value in function declaration.

int getTermIndex(int, int&, int=1, int=1);

function implementation:

int getTermIndex(int number, int& i, int a, int b) {

    if(number==0) return i;
    else if(number==1){
        i++;
        return i;
    }

    int nextFib = a+b;

    if(nextFib==number || nextFib>number) {
        i += 3;
        return i;
    }
    else {
        i++;
        getTermIndex(number, i, b, nextFib);
    }

}

function usage:

int number;
cin >> number;

int nth=0;
getTermIndex(number, nth);
HoseinGhanbari
  • 1,058
  • 1
  • 11
  • 23
  • Well done! I've retracted my vote-to-close. If you're interested in further reading, there is a (non-recursive) version [here on SO](https://stackoverflow.com/q/5162780/812149). – S.L. Barth is on codidact.com Nov 23 '17 at 19:14
  • though syntactically recursive, semantically this is an iterative procedure. Indeed in languages with tail-call optimization is *is* just a loop. Your code even depends on this, as there's no `return` statement in the final `else` clause. – Will Ness Dec 16 '17 at 17:39