Analyze the time complexity of this Code:
Int CAL (int n ){
Int sum = 0;
Int I = 1;
For (; I <= N; ++ I ){
Sum = sum + I;
}
Return sum;
}
The execution time of each line of code is 1, and the for loop is executed n times. So it is 2 + n times, and the removal constant is O (n)
Int CAL (int n ){
Int sum = 0;
Int I = 1;
Int J = 1;
For (; I <= N; ++ I ){
J = 1;
For (; j <= N; ++ J ){
Sum = sum + I * J;
}
}
}
This Code contains two for loops. So it's O (n2)
Int CAL (int n ){
Int sum_1 = 0;
Int p = 1;
For (; P <100; ++ p ){
Sum_1 = sum_1 + P;
}
Int sum_2 = 0;
Int q = 1;
For (; q <n; ++ q ){
Sum_2 = sum_2 + q;
}
Int sum_3 = 0;
Int I = 1;
Int J = 1;
For (; I <= N; ++ I ){
J = 1;
For (; j <= N; ++ J ){
Sum_3 = sum_3 + I * J;
}
}
Return sum_1 + sum_2 + sum_3;
}
The greatest complexity.
Int CAL (int n ){
Int ret = 0;
Int I = 1;
For (; I <n; ++ I ){
Ret = RET + f (I );
}
}
Int F (int n ){
Int sum = 0;
Int I = 1;
For (; I <n; ++ I ){
Sum = sum + I;
}
Return sum;
}
The time complexity of multiplication is O (N3)
I = 1;
While (I <= N ){
I = I * 2;
}
I = 1;
While (I <= N ){
I = I * 3;
}
The time complexity is O (logn)
Int CAL (INT m, int N ){
Int sum_1 = 0;
Int I = 1;
For (; I <m; ++ I ){
Sum_1 = sum_1 + I;
}
Int sum_2 = 0;
Int J = 1;
For (; j <n; ++ J ){
Sum_2 = sum_2 + J;
}
Return sum_1 + sum_2;
}
The time complexity is O (n) + O (N)
Complex read Analysis