开发者

work around stack overflow error when going through recursive function 300+ times in groovy?

开发者 https://www.devze.com 2023-04-08 22:42 出处:网络
I have the following code, trying to find the first number of the Fibonacci sequence with over 1000 digits:

I have the following code, trying to find the first number of the Fibonacci sequence with over 1000 digits:

z = 0g
def fib
fib = {a,b-> 
    if(a <= 10g**1000){
        z++ 
        fib(b.toBigInteger(), (a+b).toBigInt开发者_运维技巧eger())
    }else{
        return z
    }
}

fib(1,2)

This function works when I change "1000" to ~300 or less, and it computes in well under a half a second.

However, when I raise the variable above that, I get a stack overflow. I saw another question about this and the answer was to use a function called "doall," but I don't see that in Groovy.

I figure the solution is pretty simple at this point, but I don't know where to look for it...

Can anyone help me out?

Thanks so much!


If you are using Groovy 1.8, this is what the trampoline() method was designed to handle on Closures.

http://mrhaki.blogspot.com/2011/04/groovy-goodness-recursion-with-closure.html

0

精彩评论

暂无评论...
验证码 换一张
取 消