Mathematical Induction for a C++ loop

944 Views Asked by At
unsigned long long int H(unsigned long long int n){
    unsigned long long int res = 1;
    for (unsigned int i = 1; i < n; i++){
        res += n / i;
    }
    return res;
}

I'm trying to convert this simple loop into a mathematical equation, I did a couple of attempts based on the example given here and failed miserably.

What I reached so far: H(n) = (n / 1) + (n / 2) ... (n / n-1)

So if n = 3 then H(3) = 3 + 3/2 = 5 (Because the result of each division is always an int).

and at n = 5 the result would be H(5) = 5 + 5/2 + 5/3 + 5/4 = 10.

But I can't convert this into an equation.. A little explanation would really be appreciated so I can convert other loops later on.

2

There are 2 best solutions below

1
On

You are effectively asking for a closed form of the series:

$\sum_{i=1}^{n-1}\frac{n}{i}$

As far as I know, there is no "solution" to this problem; the series itself diverges as $n$ tends to infinity...

0
On

The value of res is $n$ times the $n-1$st harmonic number. See https://en.m.wikipedia.org/wiki/Harmonic_number for alternative formulas.