解决递归函数 300+ 时的堆栈溢出错误时代在常规?
我有以下代码,试图找到超过 1000 位的斐波那契数列的第一个数字:
z = 0g
def fib
fib = {a,b->
if(a <= 10g**1000){
z++
fib(b.toBigInteger(), (a+b).toBigInteger())
}else{
return z
}
}
fib(1,2)
当我将“1000”更改为 ~300 或更少时,此函数起作用,并且计算时间远低于半秒。
但是,当我将变量提高到该值以上时,就会出现堆栈溢出。我看到了另一个与此相关的问题,答案是使用一个名为“doall”的函数,但我在 Groovy 中没有看到这一点。
我认为此时解决方案非常简单,但我不知道在哪里寻找它......
任何人都可以帮助我吗?
非常感谢!
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).toBigInteger())
}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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您使用的是 Groovy 1.8,这就是
trampoline()
方法旨在处理闭包的方法。http://mrhaki.blogspot.com/2011/04 /groovy-goodness-recursion-with-closure.html
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