Can anyone guide me to find the time complexity? Does the time complexity change over operating systems?
int fn(int n){
if(n==1){
return 1;
}
else{
return(fn(n-1)+ fn(n-1));
}
}
You can make a recurrence relation T which represents the time it would take to compute and input of size N and then use the method of telescoping to help find the Big-O like so:
T(N) = T(N-1) + T(N-1) + c = 2*T(N-1) + c
Here, we can see that the time it will take to compute T(N)
will be 2*T(N-1)
plus a constant amount of time c
. We can also see by your function that:
T(1) = b
Here, we can see by your base case that there are no recursive calls when N=1, so, it will take a constant time b
to compute T(1)
.
If we take a look at T(N)
, we need to find out what T(N-1)
is, so computing that we get:
T(N-1) = 2*T(N-2) + c
Computing T(N-2)
we get:
T(N-2) = 2*T(N-3) + c
Thus, we can sub these back into each other...
T(N-1) = 2*(2*T(N-3) + c) + c = 4*T(N-3) + 3c
T(N) = 2*(4*T(N-3) + 3c) + c = 8*T(N-3) + 7c
By looking at the pattern produced by stepping down into our equation, we can generalize it in terms of k
:
T(N) = 2^k * T(N-k) + ((2^k)-1 * c)
We know that our recursive calls will stop when T(N-k) = T(1)
, so we want to find when N-k = 1
, which is when k = N-1
, so subbing in our value of k
and removing the constant-variable times, we can find our Big-O:
T(N) = (2^N) * T(1) + (2^N)-1 * c
= (2^N) * b + (2^N)-1*c
= O(2^N) (-1, b & c are constants, so they can be removed, giving 2*(2^N), where 2* is a constant, giving 2^N)
Time complexity is a measurement of how well an algorithm will scale in terms of input size, not necessarily a measure of how fast it will run. Thus, time-complexity is not dependent on your operating system.