Groovy web console

subscribe to the feed Subscribe
to this
site
Fibonacci (via #groovywebconsole)
tweet this snippet Tweet
this
script

Fibonacci

Published 11 months ago by Ricardo
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
def number = 20
def DYNAMIC_PROGRAMMING = true

def fib(n) { n < 2 ? n : fib(n - 2) + fib(n - 1) }
def fastFib;
def fiboClosure = { BigInteger n -> n < 2 ? n : fastFib(n - 2) + fastFib(n - 1) }
if(DYNAMIC_PROGRAMMING){
fastFib = fiboClosure.memoize()
}else{
fastFib = fiboClosure
}


def measure = { closure ->
    start = System.currentTimeMillis()
    closure.call()
    now = System.currentTimeMillis()
    now - start
}


def duration = measure {
    println fiboClosure(number)
}
println "Calculo de fib(${number}) demoro ${duration}ms"