# iteration and recursion question

• 03-19-2008
Stonehambey
iteration and recursion question
Hi all, me again :)

I had someone ask me whether the sum of 1/n as n tends to infinity converges or not(that is 1+1/2+1/3+1/4+...+1/n). Now as a mathematician I can show that it doesn't quite easily. But I thought I would give it a go in c++. While it won't prove anything, it can demonstrate that for large numbers there doesn't seem to be an upper bound, plus I thought it would be fun!

So I created a couple of functions, one using recursion and the other using iteration. Here they are.

Code:

```long double sum(long double n) {       if(n==1.)       {               return 1.;              }             long double d = (1/n) + sum(n-1);       return d; }```
Code:

```long double sum2(long double n) {         long double d = 0;         for(double i=1;i<=n;i++)     {           d += 1/i;     }         return d; }```
I then wrote a simple main which checked to make sure n was greater than or equal to one and, if it was, would call one of these functions to show the sum.

Now both the functions seem to work except for one difference. When I set n to one million and the main calling the first function, the program simply closes. But when I tell the main to call the second (iterative) function, it works fine.

I thought it might be the variable types I was using (which is why I changed them to long double) but it didn't seem to make a difference, so I'm simply wondering what the difference is?

For completeness, here is the main

Code:

```int main() {     long double n;     long double ans;         cout << "Enter your value of n: ";     cin >> n;     if(n>=1)     {             ans = sum2(n);             cout << "The sum is " << ans << endl;     }else     {         cout << "Value of n makes no sense!";        }         getch();     return 0; }```
as you can see, this particular main calls the second function.

Kind Regards

Stonehambey
• 03-19-2008
laserlight
Quote:

When I set n to one million and the main calling the first function, the program simply closes.
There is a limit to the stack, and such a large number of recursive calls probably went beyond that limit.
• 03-19-2008
robatino
The sum from n == 1 to N of 1/n is going to be something on the order of ln(N) (since the integral of 1/x is ln(x)). By drawing diagrams it's pretty easy to put both lower and upper bounds on the sum. Since ln(N) goes to infinity so slowly you will have trouble reaching very large sums (but you probably know that already).
• 03-19-2008
Stonehambey
Thanks for the replies :)

There is actually no upper bound on the series, but since we're not talking about C++ really anymore, it's probably best I just link you to my site (for those who're interested in the maths :))

http://stonehambey.com/?p=62

Thanks once again,

Stonehambey