This repository has been archived by the owner. It is now read-only.

# github/hubot-scripts

ckdake committed Oct 31, 2011
1 parent 1e11245 commit d43543cdbd88d138a32d281ce585996f2601e805
Showing with 31 additions and 0 deletions.
1. +31 −0 src/scripts/fibonacci.coffee
 @@ -0,0 +1,31 @@ +# Calculate the nth fibonacci number. #webscale. +# +# From https://gist.github.com/1032685 +# +# fibonacci me - Calculate Nth Fibonacci number + +fib_bits = (n) -> + # Represent an integer as an array of binary digits. + bits = [] + while n > 0 + [n, bit] = divmodBasic(n, 2) + bits.push(bit) + return bits.reverse() + +fibFast = (n) -> + [a, b, c] = [1, 0, 1] + + for bit in fib_bits(n) + if bit + [a, b] = [(a+c)*b, b*b + c*c] + else + [a, b] = [a*a + b*b, (a+c)*b] + c = a + b + return b + +divmodBasic = (x, y) -> + return [(q = Math.floor(x/y)), (r = if x < y then x else x % y)] + +module.exports = (robot) -> + robot.hear /fibonacci me (\d+)/i, (msg) -> + msg.send fibFast(msg.match[1]).toString()

Contributor