Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If I divide a recursive call by another, would I get an infinite loop?

Tags:

java

recursion

I'm experimenting with recursion in Java and I have this method:

public static int recursion(int n) {
    if(n==1) {
        return 2;
    } else {
        int test = (recursion(n-1))/(recursion(n-1));
        return test;
    }
}

If I run it with n = 50, it never prints anything, so I'm guessing the recursive calls are infinite? Could anybody explain why?

like image 653
SebastianSrvn Avatar asked Oct 11 '20 04:10

SebastianSrvn


2 Answers

Here, recursion() is called like a binary tree

recursion(50) -> recursion(49) -> recursion(48) ...
                                  recursion(48) ...
                 recursion(49) -> recursion(48) ...
                                  recursion(48) ...

So the binary tree height is 49.
Then recursion() is called: total number of nodes of the tree times. This equates to 2^(h+1)-1 = 2^(49+1)-1 = 2^(50)-1 times.
That's huge, which takes a very long time to execute. This is the problem, but it's not infinite.

You can instead do the following, which is not a problem because recursion(n) to recursion(n-1) is called only once:

public static int recursion(int n) {
    if(n==1) {
        return 2;
    } else {
        int test = recursion(n-1);
        test = test/test
        return test;
    }
}
like image 140
Eklavya Avatar answered Sep 23 '22 15:09

Eklavya


It is not infinite, just huge. You will do roughly 2^50 recursive calls. Even if each call takes just one nanosecond (which is much too low) this means a total run time of about two weeks.

like image 32
Henry Avatar answered Sep 21 '22 15:09

Henry