This is an integer overflow problem when the next Fibonacci number (num2
) becomes too large to represent as a signed 64-but integer. The crash seems random because the output from the program is buffered and not all the messages that have been printed will be visible yet. I tried adding a delay to try and remove the buffering and force output to appear:
var num1 = 0, num2 = 1
for i in 0..<100{
print(i, num1)
usleep(250_000)
var temp = num2
num2 += num1
num1 = temp
}
In swift playgrounds on the iPad this reliably shows me up to number 91:
89 1779979416004714189
90 2880067194370816120
91 4660046610375530309
Since Int.Max
is 9223372036854775807
and the code is printing num1
, this means that num2
has already been set to 7540113804746346429
in the i==90
iteration. Before the code can print num1
for i==92
it will need to add 4660046610375530309
to num2
(in the i==91
iteration) and that will be too large for a signed 64-bit integer (12200160415121876738
)