Order of complexity of fibonacci functions -
i have following 3 algorithms give fibonacci numbers. know how able find out each of order of complexity. know how might able determine this?
method 1 ------------------------------------------------------------------------ long long fibb(long long a, long long b, int n) { return (--n>0)?(fibb(b, a+b, n)):(a); } method 2 ------------------------------------------------------------------------ long long int fibb(int n) { int fnow = 0, fnext = 1, tempf; while(--n>0){ tempf = fnow + fnext; fnow = fnext; fnext = tempf; } return fnext; } method 3 ------------------------------------------------------------------------ long long unsigned fib(unsigned n) { return floor( (pow(phi, n) - pow(1 - phi, n))/sqrt(5) ); }
correct me if wrong, guess method 1 o(2^n)
since recursive, medtod 2 o(n)
, last 1 o(1)
.
methods 1 , 2 have complexity o(n)
. reasons straightforward:
- method 1 recurses
n-1
times, each recursion performs simple arithmetic operation. - method 2 iterates
n-1
times, each iteration has constant time, simple math again.
method 3 has indeed complexity of o(1), may not compute correct value, merely approximation.
Comments
Post a Comment