Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
839 views
in Technique[技术] by (71.8m points)

c++ - i want to calculate the T(n) for the two algorithms

i want to know the time complexity for the following two algorithms

void main (){-----------------------------------------T(n)
for(int a=1 ; a<=20 ; a++) {------------?
if(a%2==0)  -------------?
    cout<<"value is Even"; --------?
   else 
     cout<<"value is Odd";--------?
}

}

void main (){-----------------------------------------T(n)
int x=1; {------------?
int a=1;  -------------?
   while(a<=n){--------?
   x=x*a; -------------?
   a=a+2; -------------? 

}
cout<<x;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The idea is to calculate how the execution time for a piece of code - typically some algorithm, depends on the input. If a function takes N as input how long will it take to execute if N=5 or N=10. Will it take double as long? Will it take the same time? Or will it take more than double?

In your case:

The first program doesn't depend on any input so it is O(n)=1.

Your second program depends on n. It will do the same stuff n/2 times due to the a = a + 2. So it is O(n)=n/2. However constants are typically skipped and one would write O(n) = n.

If you had code like this:

for (a=0; a < n; a++)
{
     // n times here
     for (b=0; b<n; b++)
     {
        // n times here

        // do something
     }
 }

the execution time will change to n^2 because both loops will iterate n times. Each time the outer loop executes, the inner loop executes n times. Since the outer loop executes n times, you have n*n. So O(n) = n^2


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...