Member-only story

Just a typical problem

Gunnar Stahl
3 min readFeb 18, 2021

--

The first task of week four, devslopes academy, was rather simple. “Write a method in swift that prints the first 100 numbers of the fibonacci algorithm”.

In my head the code was almost done even before I started to type the first letter in xcode. As usual for the experienced developer. Do a oneliner of recursive magic, and voilá, task done.

So, the very first version was:

But hang on, what is that! Ok, here we go. Arithmetic overflow. I never had done the fibonacci algorithm before, so the fact that the numbers more or less grow exponentially and go into math overdrive pretty soon wasn’t that clear to me. It stopped at

Ok, take the next bigger version of a numeric field, which is UInt64. That will surely be enough…

Ok, here we go again. The result is just a little bit less worse. It stopped at exactly one round later:

So, what is the solution for the task at hand? The biggest data type Swift has to offer is Double. So, replace UInt64 with Double, and all should be fine:

--

--

Gunnar Stahl
Gunnar Stahl

Written by Gunnar Stahl

Born in 1971, finished school after 13 years in 1990. Professional developer sind 1992. Freelancer since 2009. Maried, father of two sons. Autistic.

No responses yet