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
104 views
in Technique[技术] by (71.8m points)

java - For loop time complexity up to different "i" control value

Which is the time complexity of the for loop, when the control parameter inside the loop has an increasement by +2?

for(int i = 0 ; i < n ; i = i + 2){
 //something
}

I understand that a simple for loop time complexity is N * (operations inside the loop). For example this one

for(int i = 0 ; i < n ; i++){
     //something
    }

Also it can be written as MathSum (from i = start TO (end - start + 1)); in this case MathSum(i = 0 to n-1+1) * (something)

I guess the answear is also O(n).

question from:https://stackoverflow.com/questions/65874836/for-loop-time-complexity-up-to-different-i-control-value

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

1 Reply

0 votes
by (71.8m points)

for(int i = 0 ; i < n ; i = i + 2){ } Yes, The time complexity of the above for loop is also O(n) because it iterates n/2 times. So the complexity will be O(n/2), in Complexity analysis, we remove the constant. So it will be O(n).

In complexity analysis, we don't calculate the exact time.


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

...