+ 1

Fibonacci algorithm complexity. I have written a program that shows fibonacci numbers in a given range.

I would like to determine its complexity and I want to know if it is more efficient than recursive fibonacci algorithm swift code func fibonacci (a:Int) { var holder1: Int = 1 var holder 2: Int = 1 for i in 1...a { if i%2 ==0 { print(holder2) holder2 = holder1 + holder2 } else { print(holder1) holder1 = holder2 + holder 1 } } }

8th Apr 2018, 11:02 PM
Jhon
Jhon - avatar
4 ответов
+ 3
The recursive fibonacci works in ~O(1.6^n) time. It is very very very slow. Yours (dynamic) solution works in O(n) time (linear time) which is much better. The best possible way is in ~O(log(n)) time which is much better than linear time (it is possible using matrix multiplication). https://rob-bell.net/2009/06/a-beginners-guide-to-big-o-notation/
8th Apr 2018, 11:26 PM
Bartosz Pieszko
Bartosz Pieszko - avatar
+ 3
Jhon No. Just look, while you are doing each iteration of for statement, then you do 'if' or 'else'. Then it is one operation each time. Then one operation * n times gives you O(n) time.
8th Apr 2018, 11:35 PM
Bartosz Pieszko
Bartosz Pieszko - avatar
0
how did you calculate that mine is O(n) time? wouldn't it be quadratic time??
8th Apr 2018, 11:31 PM
Jhon
Jhon - avatar
0
Thank you. I got it
9th Apr 2018, 12:02 AM
Jhon
Jhon - avatar