Created
June 29, 2015 02:20
-
-
Save gabteles/ea2b3dafe0d4d1877837 to your computer and use it in GitHub Desktop.
Implementação da sequência de Fibonacci em Ruby como enumerável e utilizando a fórmula com a razão áurea.
This file contains hidden or 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
# Implementação pela fórmula | |
class << Math | |
FiveSquareRoot = Math.sqrt(5) | |
GoldenRatio = (1 + FiveSquareRoot) / 2 | |
def fibonacci(n) | |
((GoldenRatio ** n - ((-GoldenRatio) ** (-n))) / FiveSquareRoot).round | |
end | |
end | |
# Implementação como enumerável | |
module Fibonacci | |
extend Enumerable | |
module_function | |
def each | |
a, b, c = 0, 1, 0 | |
loop do | |
c, a, b = a, b, a + b | |
yield a | |
end | |
end | |
end | |
if (__FILE__ == $0) | |
n = rand(20) + 1 | |
x = Math.fibonacci(n) | |
y = Fibonacci.take(n) | |
puts (x == y[n - 1]) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment