Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect the root recursive call?

Tags:

c

stack

recursion

Say we're writing a simple recursive function fib(n) that calculates the nth Fibonacci number. Now, we want the function to print that nth number. As the same function is being called repeatedly, there has to be a condition that allows only the root call to print. The question is: how to write this condition without passing any additional arguments, or using global/static variables.

So, we're dealing with something like this:

int fib(int n) {
    if(n <= 0) return 0;
    int fn = 1;
    if(n > 2) fn = fib(n-2) + fib(n-1);
    if(???) cout << fn << endl;
    return fn;
}

int main() {
    fib(5);
    return 0;
}

I thought that the root call differs from all children by returning to a different caller, namely the main method in this example. I wanted to know whether it is possible to use this property to write the condition and how.

Update: please note that this is a contrived example that only serves to present the idea. This should be clear from the tags. I'm not looking for standard solutions. Thanks.

like image 642
Ahmed Abdelkader Avatar asked Apr 22 '10 16:04

Ahmed Abdelkader


People also ask

How do you find the number of recursive calls?

Thus in our case, the number of recursive calls is n0 +n2 = 2n0 −1, which means that the total number of recursive calls is equal to 2Fn+1 − 1. This way, we have reached the same result with [2], however, in a much simpler way from the mathematical and pedagogical point of view.

What are the recursive calls?

A recursive call is one where procedure A calls itself or calls procedure B which then calls procedure A again. Each recursive call causes a new invocation of the procedure to be placed on the call stack.

Can we use call by reference in recursion?

Yes, it has to be pass by reference.


1 Answers

The way I would do this is with a helper function:

int _fib(int n) {
    if(n <= 0) return 0;
    int fn = 1;
    if(n > 2) fn = _fib(n-2) + _fib(n-1);
    return fn;
}

int fib(int n) {
    int fn=_fib(n);
    cout << fn << endl;
    return fn;
}

Alternatively, you could write it like this (c++):

int fib(int n, bool f=true) {
    if(n <= 0) return 0;
    int fn = 1;
    if(n > 2) fn = fib(n-2, false) + fib(n-1, false);
    if(f) cout << fn << endl;
    return fn;
}
like image 182
Blindy Avatar answered Nov 15 '22 08:11

Blindy