Square Root Time Complexity

In his dream, Chris wrote a function in Python, which takes a positive integer as the parameter.

1
2
3
4
5
6
7
def func(n):
    if n == 1:
        return 1
    val = 0
    for i in range(int(sqrt(n))):
        val += func(int(sqrt(n)))
    return val

Assume that the square root function takes constant time. What is the time complexity of this recursive function?

O ( n n ) O(\sqrt{n}^{\sqrt{n}}) O ( n ) O(\sqrt{n}) O ( n n ) O(n\sqrt{n}) O ( n ) O(n)

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.

1 solution

[Nonrigorous Partial Solution]

Let T ( n ) T(n) be the time required to evaluate func( n n ) .

From line 2 and 3, we infer that T ( 1 ) = 1 T(1) = 1

Each time line 5 executes, it takes T ( n T (\sqrt{n} ) time. And line 4 tells us that happens n \sqrt{n} times. That means T ( n ) = n T ( n ) T(n) = \sqrt{n} T(\sqrt{n})

It is easy to verify that a solution would be T ( n ) O ( n ) T(n) \in O(n)

Let's make it rigorous.

Put f ( n ) = T ( n ) n f(n) = \dfrac{T(n)}{n}

Then, f ( n ) = f ( n ) f ( n ) = f ( n 1 2 k ) k N f(n) = f(\sqrt{n}) \\\implies f(n) = f(n^{\frac{1}{2^k}}) \quad \forall k \in \mathbb{N}

Now, assuming that f f is continuous (which is a fairly good approximation), we take k k \to \infty to get that f ( n ) = f ( 1 ) f ( n ) O ( 1 ) T ( n ) O ( n ) f(n) = f(1) \\\implies f(n) \in \mathcal{O}(1) \\\implies T(n) \in \mathcal{O}(n)

A Former Brilliant Member - 4 years, 10 months ago

Log in to reply

Wow, that is pretty cool.

Agnishom Chattopadhyay - 4 years, 10 months ago

Log in to reply

Hey, just realised that the actual functional equation is T ( n ) = n T ( n ) T ( n ) n T ( n ) T(n) = \lfloor \sqrt{n} \rfloor T(\lfloor \sqrt{n} \rfloor) \\ \implies T(n) \leq \sqrt{n} T(\sqrt{n})

The rest of the derivation remains same except that = = is replaced by \leq .

A Former Brilliant Member - 4 years, 10 months ago

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...