Reputation: 1143
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 !
Upvotes: 1
Views: 778
Reputation: 1143
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);
Upvotes: 2