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
精彩评论