Member-only story
Just a typical problem
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: