Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the time complexity of the following function

Calculate time complexity of:

void func(int n)
{
    int sum=0;
    for (int i=1;i<=n;i++)
    {
        for (int j=1;j<=i*i;j+=i)
        {
            sum+=i;
        }
    }
}

I think the time complexity is O(n^2) because the outer loop runs n times, and the inner loop runs approximately i times for each value of i, that means the inner loop will run 1+2+3+…+n times, which is O(n^2), however, Google Bard says that the complexity is O(n^3) because the nesting has a multiplicative effect on the time complexity, meaning the actual amount of iterations is

n*(1+2+3+…+n) which is O(n^3)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

But how is that possible?

>Solution :

Your calculations are correct – it is O(n^2). The inner loop has step of i so it will run for ~ i*i/i iterations giving O(n) for inner loop too.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading