Is the Big-O for the following code O(n) or O(log n)?
for (int i = 1; i < n; i*=2)
sum++;
It looks like O(n) or am I missing this completely?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It is
O(logn), sinceiis doubled each time. So at overall you need to iteratektimes, until2^k = n, and in this case it happens whenk = logn(since2^logn = n).Simple example: Assume
n = 100– then:It is easy to see that an iteration will be added when
nis doubled, which is logarithmic behavior, while linear behavior is adding iterations for a constant increase ofn.P.S. (EDIT): mathematically speaking, the algorithm is indeed
O(n)– since big-O notation gives asymptotic upper bound, and your algorithm runs asymptotically “faster” thenO(n)– so it is indeedO(n)– but it is not a tight bound (It is notTheta(n)) and I doubt that is actually what you are looking for.