1
def foo(n):
    for i in range(n):
        for k in range(1,i):
            if k>n/k:
                return k

what is the time complexity of this program? answer says its O(n). any explanations for that would be welcome

edit: typo

0

1 Answer 1

3

answer says its O(n).

Yes, the complexity is O(N) because

for k in range(i,i)

for loop is never executed.

So, your code is equivalent to

def foo(n):
    for i in range(n):
       pass

UPDATE

def foo(n):
    for i in range(n):
        for k in range(1,i):
            if k>n/k:
                return k

k>n/k is equivalent to k^2 > n and it's k > sqrt(n)

The main loop is mainly executed sqrt(n) times and the inner loop is executed 0 times, then 1 times, then 2 times, ..... , sqrt(n) times before it returns from the function.

So, the total complexity is O(sqrt(n) * sqrt(n)) which is O(n)

Sign up to request clarification or add additional context in comments.

1 Comment

my bad. it was a typo. its (1,i) not (i,i)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.