Last active
June 22, 2017 11:41
-
-
Save Demonstrandum/4fef6acc9ae3522fea96aeea45ce0cb6 to your computer and use it in GitHub Desktop.
Fibonacci calculator, ARGV[0] is the nth Fibonacci number.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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