func(n){
if(n == 0){
//print sth
return;
}
for(i=1;i<=6;i++){
func(n-1)
}
}
Please help me understand time complexity of above pseudo code.
Your recursive code has the following properties:
Mathematically, we can model the total work done as a recurrence relation, letting T(n) denote the amount of work done when you call func(n)
:
Let's play around with this and see what we find.
It might not be obvious just by looking at this, the numbers here are actually given by the formula
T(n) = (6n+1 - 1) / 5
We can check this briefly as follows:
Asymptotically, this means that T(n) = Θ(6n), so the overall runtime is Θ(6n).
So... where did (6n+1 - 1) / 5 come from? Notice that
More generally, T(n) seems to have the form
6n + 6n-1 + ... + 61 + 60.
This is the sum of a geometric series, which simplifies to (6n+1 - 1) / 5.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With