int sum = 0;
for (int n = N; n > 0; n /= 2)
for (int i = 0; i < n; i++)
sum++;
I was pretty sure it grows in nlogn but was told it’s linear… Why is it linear and not linearithmic?
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 linear. Imagine for a second
nis 64. The inner loop runs 64 times, then 32 times, then 16 times, then 8 times, then 4 times, then 2 times, then 1 time. 64 + 32 + 16 + 8 + 4 + 2 + 1 = 127.So it requires
2n-1total operations (for a power of 2, but that doesn’t change the analysis), assuming the inner loop is not optimized away. That’s clearlyO(n)— linear.If the inner for loop is optimized away (to
sum += n;), it’s logarithmic.