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.
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.