# Recursion

Printable View

• 03-21-2011, 07:05 PM
fam2315
Recursion
I need some help writing a recursive method to add the first n terms of the series

1+(1/2)+(1/3)+(1/4)+.....+(1/n)

I'm thinking I would have to isolate the 1 because that is independent of the other terms(?) and keep passing in a number 1 higher than the previous time, but im not sure.
• 03-21-2011, 07:53 PM
JosAH
Quote:

Originally Posted by fam2315
I need some help writing a recursive method to add the first n terms of the series

1+(1/2)+(1/3)+(1/4)+.....+(1/n)

I'm thinking I would have to isolate the 1 because that is independent of the other terms(?) and keep passing in a number 1 higher than the previous time, but im not sure.

Write down your series as: 1/1+1/2+1/3+1/i+1/(i+1)+1/(i+2) ... 1/n. I hope see can see that i is the loop variable in the range from 1 to n, so:

Code:

```double sum= 0; for (int i= 1; i <= n; i++)   sum+= 1.0/i;```
This is an iterative solution, but imagine that a (recursive) method F(i) can calculate the sum 1/i+1/(i+1)+1/(i+2)+ ... +1/n. F can be written as:

Code:

```double F(int i, int n) {   if (i > n) return 0;   return 1.0/i+F(i+1, n); }```

kind regards,

Jos
• 03-21-2011, 07:55 PM
FlipPoker@gmail.com
I think this should do it:

Code:

```        public static double addSeries(double n) {                         if (n == 1)                         return 1;                                 return (1/n) + addSeries(n-1);                                 }```
• 03-21-2011, 11:34 PM
sunde887
That looks correct, did you test it? Also, if you are done, please mark your thread solved with the thread tools at the top.
• 03-22-2011, 12:22 AM
FlipPoker@gmail.com
I tested my method. It seems to work fine. Who should mark this solved? I'm sorry, I'm new. Thanks.
• 03-22-2011, 01:02 AM
sunde887
You can, at the top there should be something that says thread tools, click it and it will open a drop down menu, the last item on it should be mark the thread solved.
• 03-22-2011, 01:10 AM
Junky
pssst, sunde, you are not talking to the OP.
• 03-22-2011, 01:23 AM
sunde887
>< oops. Thanks for pointing that out junky.