1. Member
Join Date
Feb 2011
Posts
78
Rep Power
0

## 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.

2. 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:

Java 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:

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

kind regards,

Jos

3. Member
Join Date
Mar 2011
Posts
94
Rep Power
0
I think this should do it:

Java Code:
```
public static double addSeries(double n) {

if (n == 1)
return 1;

}```

4. That looks correct, did you test it? Also, if you are done, please mark your thread solved with the thread tools at the top.

5. Member
Join Date
Mar 2011
Posts
94
Rep Power
0
I tested my method. It seems to work fine. Who should mark this solved? I'm sorry, I'm new. Thanks.

6. 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.

7. pssst, sunde, you are not talking to the OP.

8. >< oops. Thanks for pointing that out junky.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•