There are two nested for loops. I'm not sure but I think that it's geometric series, but I cannot get well solution for it. It seems n + n/2 + n/4 + .. + n/n^2
, but how? What I tried is below up to now,
$$ \sum _{i=0}^{log\left(n-1\right)}\:\sum _{j=0}^{i-1}\:1 $$ $$ \sum _{i=0}^n\:\sum _{j=0}^n\:\left(\frac{1}{2}\right)^j $$
At first, I thought it's $O(nlogn)$ but instead as far as I research the right result is $O(n)$.
int try(int n) {
int sum = 0;
for (int i = n; i > 0; i /= 2) {
for (int j = 0; j < i; j++) {
sum += 1;
}
}
return sum;
}
Could you show its sigma notation with its complexity? I want to comprehend it with steps.
i
, but what values are they? The code says $n$, $n/2$, ..., $1$ – David Richerby Oct 15 '17 at 10:55sum += i
. – David Richerby Oct 15 '17 at 10:56sum
, which you can inspect by running your function on a few sample inputs. – Yuval Filmus Oct 15 '17 at 11:23