What is the Big O analysis of this algorithm? (Stackoverflow ),

Source: Internet
Author: User

What is the Big O analysis of this algorithm? (Stackoverflow ),

Question:

I'm working on a data structures course and I'm not sure how to proceed w/this Big O analysis:

sum = 0;for(i = 1; i < n; i++)     for(j = 1; j < i*i; j++)         if(j % i == 0)             for(k = 0; k < j; k++)                   sum++;

My initial idea is that this is O (n ^ 3) after ction, because the innermost loop will only run whenj/iHas no remainder and the multiplication rule is inapplicable. Is my reasoning correct here?


Answer:

Let's ignore the outer loop for a second here, and let's analyze it in termsi.

The mid loop runsi^2Times, and is invoking the inner loop wheneverj%i == 0, That means you run it oni, 2i, 3i, ...,i^2, And at each time you run until the relevantj, This means that the inner loop summation of running time is:

i + 2i + 3i + ... + (i-1)*i  = i(1 + 2 + ... + i-1) = i* [i*(i-1)/2] 

The last priority ity comes from sum of arithmetic progression.
The above is inO(i^3).

Repeat this to the outer loop which runs from1TonAnd you will get running timeO(n^4), Since you actually have:

C*1^3 + C*2^3 + ... + C*(n-1)^3 = C*(1^3 + 2^3 + ... + (n-1)^3) = = C/4 * (n^4 - 2n^3 + n^2)

The last equation comes from sum of cubes
And the above is inO(n^4), Which is your complexity.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.