Complex read Analysis

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.