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

來源:互聯網
上載者: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 reduction, because the innermost loop will only run when j/i has 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 terms of i.

The mid loop runs i^2 times, and is invoking the inner loop whenever j%i == 0, that means you run it on i, 2i, 3i, ...,i^2, and at each time you run until the relevant j, 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 equality comes from sum of arithmetic progression. 
The above is in O(i^3).

repeat this to the outer loop which runs from 1 to n and you will get running time of O(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 in O(n^4), which is your complexity.


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.