def fib(n)
if n <= 1
1
else
fib(n - 1) + fib(n - 2)
end
end
puts fib(49)
---------------
Unhandled exception: Arithmetic overflow (OverflowError)
from fib.cr:5:16 in 'fib'
from fib.cr:5:5 in 'fib'
from fib.cr:5:5 in 'fib'
from fib.cr:5:5 in 'fib'
from fib.cr:9:6 in '__crystal_main'
from /usr/share/crystal/src/crystal/main.cr:129:5 in 'main_user_code'
from /usr/share/crystal/src/crystal/main.cr:115:7 in 'main'
from /usr/share/crystal/src/crystal/main.cr:141:3 in 'main'
from /lib/x86_64-linux-gnu/libc.so.6 in '__libc_start_main'
from ./fib in '_start'
from ???
Crystal auto reduce the return value as Int32, but fib(49) is far far large than a 32 bit integer.
you have to specify the correct type manually, as following:
require "big"
def fib(n) : BigInt
if n <= 1
1.to_big_i
else
(fib(n - 1) + fib(n - 2)).to_big_i
end
end
puts fib(49)
# => 12586269025
But, use BigInt has a side effect, it is far far slow than Int32, please always specify exact limit type instead of the arbitrarily large integers.