I wanted to find fibonacci of a large number for one of the Hacking challenges that i was doing,
The number was larger than 1000 so the online calculators were crashing.
If you are writing a recursive function for this task,it will take ages to complete.
So just wrote this stuff in ruby with Matrix.
I know no-one gives a fuck about fibonacci,but it will be useful for someone who is in real need as i were that time.
require 'matrix'
FIBONACCI_MATRIX = Matrix[[1,1],[1,0]]
def fibonacci(n)
(FIBONACCI_MATRIX**(n-1)) [0,0]
end
31337.times do |j|
puts "n=#{j} => #{fibonacci(j)}"
end
No comments:
Post a Comment