What is sum of the finite series $1+\frac12+\frac13+\frac14+\frac15+\cdots +\frac1n,$ for finite value of $n\in \mathbb{N}.$
The above question arose in finding the worst-case time-complexity for the below C- code:
int fun(int n)
{
int count = 0;
for (int i = n; i > 0; i /= 2)
for (int j = 0; j < i; j++)
count += 1;
return count;
}
Here, the outer loop executes $\log_2n$ times, and need to sum up the number of times, the step for 'count += 1' executes.
Edit:
Am equally concerned about the correct series being derived.
My reasoning is:
For an input integer $n,$ the outermost loop of fun() is executed $log_2 (n)$ times.
For each run of outer loop, the inner loop statement of fun() is executed the same number of times, as the value of $i:$
First run of the outer loop: $i = \frac{n}{log_2(2)} : n$ times,
Second run of the outer loop:$i = \frac{n}{log_2(4)} : \frac n2$ times,
Third run of the outer loop: $i = \frac{n}{log_2(8)} : \frac n3$ times,
Fourth run of the outer loop: $i = \frac{n}{log_2(16)} : \frac n4$ times,
$\cdots$
Last run of the outer loop:$i = \frac{n}{log_2(2^n)} : 1$ times.
So, need to sum up all the number of times, to get the worst case time complexity
$n + \frac n2 + \frac n3 + \frac n4 +... + 1 $
$= n(1 + \frac12 + \frac13 + \frac14 + \frac15 + \frac16 + \cdots+ \frac1n)$
Edit #2:
Yes am wrong, in getting a wrong series, and the one suggested by @RossMillikan is correct. Mine would have been correct, if the outer loop had $i$ divided by a different quantity than $2,$ in each successive run. Though am unable to find that value.
Request to provide that value.