1

What will be the time complexity of this code?

 for(int i = 1 ; i <= b ; ++i )
     for(int j = i ; j <= b ; j += i )
1
  • 2
    something like b x b x ln(b): see the harmonic series. Commented Oct 30, 2016 at 18:35

1 Answer 1

8

You can expand the loops to something like this:

i = 1 ——>   1,2,3,…,b     b
i = 2 ——>   1,3,5,…,b     (b/2)
i = 3 ——>   1,4,7,…,b     (b/3)
i = 4 ——>   1,5,9,…,b     (b/4)
  …
i = b ——>   1, b          (b/b = 1)

This expands into a sum of the form:

b + b/2 + b/3 + … + b/b = b * (1 + 1/2 + 1/3 + … + 1/b)

You might recognize the second factor as the Harmonic Series. Then, using the result from the following SO answer: Finding Big O of the Harmonic Series you can get the Big Oh of your nested loops:

O(b * log(b))
Sign up to request clarification or add additional context in comments.

Comments

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.