In his dream, Chris wrote a function in Python, which takes a positive integer as the parameter.
1 2 3 4 5 6 7 |
|
Assume that the square root function takes constant time. What is the time complexity of this recursive function?
This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try
refreshing the page, (b) enabling javascript if it is disabled on your browser and,
finally, (c)
loading the
non-javascript version of this page
. We're sorry about the hassle.
Let's make it rigorous.
Put f ( n ) = n T ( n )
Then, f ( n ) = f ( n ) ⟹ f ( n ) = f ( n 2 k 1 ) ∀ k ∈ N
Now, assuming that f is continuous (which is a fairly good approximation), we take k → ∞ to get that f ( n ) = f ( 1 ) ⟹ f ( n ) ∈ O ( 1 ) ⟹ T ( n ) ∈ O ( n )
Log in to reply
Wow, that is pretty cool.
Log in to reply
Hey, just realised that the actual functional equation is T ( n ) = ⌊ n ⌋ T ( ⌊ n ⌋ ) ⟹ T ( n ) ≤ n T ( n )
The rest of the derivation remains same except that = is replaced by ≤ .
Problem Loading...
Note Loading...
Set Loading...
[Nonrigorous Partial Solution]
Let T ( n ) be the time required to evaluate
func(
n)
.From line 2 and 3, we infer that T ( 1 ) = 1
Each time line 5 executes, it takes T ( n ) time. And line 4 tells us that happens n times. That means T ( n ) = n T ( n )
It is easy to verify that a solution would be T ( n ) ∈ O ( n )