Here I got a function like this and I want to find the recursive relation of that and after that calculate time complexity of that recursive relation.
public static void f(int n) {
if (n == 1) {
//" Do sth "
} else {
for (int i = 1; i < n; i++) {
f(i - 1);
//" Do sth "
}
}
}
actually I tried a lot for that and I got T(n) = n * f( n-1) for this function as the relation but I am not sure about that . could you help me find the correct relation and solve it ?
Assuming T(1) = "Do sth" is constant work i.e. it doesn't depend on the input size n
, you could write the recursive time function as :
T(n) = T(1) + T(2) + ... + T(n-1)
= { T(1) } + { T(1) } + { T(1) + T(2) } + { T(1) + T(2) + T(3) } + { T(1) + T(2) + T(3) + T(4) } +....
[let T(1) = x]
= x + x + {x + x} + {x + x + (x + x)} + {x + x + (x + x) + x + x + (x + x)} +....
= x + x + 2x + 4x + 8x + ...
~ x.2^(n-2)
~ O(2^n)
Here is a python program to demonstrate the sequence of coefficients for the summation:
t = [0 for i in range(10)]
for i in range(1,10):
if i == 1:
t[i] = 1
else:
val = 0
for j in range(1,i):
val += t[j]
t[i] = val
print(t[1:])
prints : [1, 1, 2, 4, 8, 16, 32, 64, 128]
You can see that 2(n-2) for n >= 2 holds good at each 'n' and complexity is O(2n)