Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Add Fibonacci number calculation

  • Loading branch information...
commit d43543cdbd88d138a32d281ce585996f2601e805 1 parent 1e11245
@ckdake ckdake authored
Showing with 31 additions and 0 deletions.
  1. +31 −0 src/scripts/fibonacci.coffee
View
31 src/scripts/fibonacci.coffee
@@ -0,0 +1,31 @@
+# Calculate the nth fibonacci number. #webscale.
+#
+# From https://gist.github.com/1032685
+#
+# fibonacci me <integer> - 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()

3 comments on commit d43543c

Please sign in to comment.
Something went wrong with that request. Please try again.