简体   繁体   中英

why is this n(square) complexity?

why is this code n^2 complexity when there are three for loops? and how do u tell the different complexity of the code? here is the code:

    int size1= sc.nextInt();
    int size2 = sc.nextInt();

    int value=0;
    for(int k=0;k<size1;k++)
    {
        value++;
        //5 times
        for(int x=0;x<size2;x++)
        {
            value++;
            //15 times
            for(int i=0;i<x;i++)
            {
                value++;
                //15 times
            }
        }
    }


    System.out.println(value);

}

The complexity of your code is O(n^3) if we assume that n=size1=size2. \\sum_{k=0}^{size_1-1} \\sum_{x=0}^{size_2-1} \\sum_{i=0}^{x-1} 1=\\sum_{k=0}^{ size_1-1} \\sum_{x=0}^{size_2-1}x=\\sum_{k=0}^{size_1-1}\\frac{(size_2-1)(size_2)}{2}=\\frac {(size_1)(size_2)(size_2-1)}{2}=O(n^3)

If only size2=n and size1=k (small constant), the complexity is O(kn^2), which is O(n^2) if we only consider the variable n to be large.

I think you mean complexity not efficiency. The reason this is O(nˆ2) is that it has quadratic complexity because the third loop uses the second variable.

More info here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM