Skip to content

Instantly share code, notes, and snippets.

@snluu
Created December 26, 2019 01:35
Show Gist options
  • Save snluu/7a95ead2ced436034eaf7270b4f4ed33 to your computer and use it in GitHub Desktop.
Save snluu/7a95ead2ced436034eaf7270b4f4ed33 to your computer and use it in GitHub Desktop.
def fib(i : Int32, ch : Channel(Int32) | Nil)
if i < 2
return i if ch.nil?
ch.send(i)
return 0
end
sub_ch = Channel(Int32).new
spawn fib(i - 1, sub_ch)
x = fib(i - 2, nil)
y = sub_ch.receive
if ch.nil?
return x + y
else
ch.send(x + y)
return 0
end
end
i = 0
while i == 0
puts "Enter the number of fibonacci number to calculate: "
input = gets
i = input.to_i if !input.nil?
end
puts "Result ", fib(i, nil)
Fiber.yield
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment