简体   繁体   中英

Fibonacci using a recursive method gives me stack overflow

public static int rFib(int n) {

    if(n == 0) {
        return 0;
    }

    if(n == 1) {
        return 1;
    }  

    return n + rFib(n-1);
}

I am trying to find the largest number that will compute in under 60 seconds. Then I will use an iterative method to compare. Any number greater than 10,000 gives a stack-overflow error. How do I avoid this?

One solution to this recursion problem is to break the recursion using dynamic programming. For example, memoization can be applied and allow you to implement it like

private static Map<Integer, Integer> memo = new HashMap<>();
static {
    memo.put(0, 0);
    memo.put(1, 1);
}

public static int rFib(int n) {
    if (memo.containsKey(n)) {
        return memo.get(n);
    }
    int r = rFib(n - 2) + rFib(n - 1);
    memo.put(n, r);
    return r;
}

Unfortunately, you have come across the problem which is both the single most-used example for understanding recursion and almost the single worst application to apply recursion to.

It's really simple to understand recursion from the fibonacci because it's a really trivial recursive algorithm for you to explain to somebody and understand... Which means it's great for programming recursion, right? Unfortunately, no.

I apologize if I'm going to tell you things you already know, but I know that fibonacci is one of the first examples in introductory programming so I'm assuming that's where you're coming from.

There's a thing in programming called a stack. It's literally called this because it's like a stack of papers. When you call a function, it puts onto the stack all the information needed to call the function, pass the arguments, and know how to return from the function (and some other administrative stuff). When that function recursively calls itself, it puts another sheet on top of the stack . Then that function puts another sheet. These sheets aren't removed until the function finishes... But since one function can't finish before the other one finishes, it just grows and grows and grows.

And the stack is only so big. Purposely. To avoid this problem.

Normally, recursion isn't used for such deep problems. (Tail-call-recursive people: ignore this; if you don't know what tail-call-recusion is: also ignore this.)

The way to fix this is to not do it. It's generally recognized that in nearly every arbitrarily-recursive function application, a for loop will work better (and faster).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM