首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >当计算n= ~11000 +带记忆的斐波那契递归方法时发生堆栈溢出

当计算n= ~11000 +带记忆的斐波那契递归方法时发生堆栈溢出
EN

Stack Overflow用户
提问于 2017-09-09 03:11:01
回答 1查看 149关注 0票数 1

我有一个程序,可以用递归方法计算第n个斐波那契数,同时使用记忆法。

当我达到n= 11000左右时,我得到了一个堆栈溢出异常。有人能帮我解决这个问题吗?

下面是我的代码:

代码语言:javascript
复制
public class BigInt {

static BigInteger[] fval;

public static void main(String[] args) {
    int index;
    Scanner input = new Scanner(System.in);
    index = input.nextInt();
    fval = new BigInteger[index + 1];

    System.out.println(fib_rec(index));
}

public static BigInteger fib_rec(int index) {
    BigInteger result = BigInteger.ONE;
    if (index <= 2) {
        return result;
    } else {
        if (fval[index] != null) {
            result = fval[index];
        } else {
            result = fib_rec(index - 1).add(fib_rec(index - 2));
            fval[index] = result;
        }
        return result;
    }
}
EN

回答 1

Stack Overflow用户

发布于 2017-09-09 03:28:44

你的记忆不会改变递归的深度...在对fib_rec(n)的调用中,它调用fib_rec(n-1),后者调用fib_rec(n-2)等。如果你颠倒了调用的顺序(所以你做了fib_rec(index - 2).add(fib_rec(index - 1)),这应该允许你把堆栈深度减少大约一半,因为你会一直工作到根目录,然后根据你的记忆,从下往上填入堆栈深度为1的空白。

然而,如果不对算法进行更戏剧性的重写,就无法避免堆栈深度问题。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46123150

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档