Skip to content

Instantly share code, notes, and snippets.

@Demonstrandum
Last active June 22, 2017 11:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Demonstrandum/4fef6acc9ae3522fea96aeea45ce0cb6 to your computer and use it in GitHub Desktop.
Save Demonstrandum/4fef6acc9ae3522fea96aeea45ce0cb6 to your computer and use it in GitHub Desktop.
Fibonacci calculator, ARGV[0] is the nth Fibonacci number.
require "./matrix.cr" # from https://github.com/Exilor/matrix.git the src.matrix.cr file -> https://github.com/Exilor/matrix/blob/master/src/matrix.cr
require "big_int"
require "benchmark"
def fib(n : BigInt)
return 0 if n == 0
return 1 if n <= 2
number = Matrix.rows([[BigInt.new(1), BigInt.new(1)], [BigInt.new(1), BigInt.new(0)]])
final = Matrix.rows([[BigInt.new(1), BigInt.new(1)], [BigInt.new(1), BigInt.new(0)]])
while n > 0
final = final * number if n % 2 == 1
number = number * number
n /= BigInt.new(2)
end
return final[1, 1]
end
number = BigInt.new(0)
firstArg = BigInt.new(ARGV[0])
puts Benchmark.measure { number = fib(firstArg) }
puts "\n#{firstArg}th fibonacci number is:\n#{number}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment