fracSeries

im suppose to make a recursive function that accepts an integer as a parameter and returns the value of 1/2 + 1/3 + 1/4 + ... + 1/n

For example, in the function call fracSeries(6);
the function computes 1/2 + 1/3 + 1/4 + 1/5 + 1/6 and returns the value 1.45

i cant seem to get the math right, and I dont know what to do.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  #include <iostream>
using namespace std;

double fracSeries(int n){
    if(n == 1)
        return 1;
    
    else
        return (1/fracSeries(n-1)) + n;
    
}

int main() {
    
    cout << fracSeries(6) << endl;
    
}
1
2
3
4
5
double fracSeries(double n)
{
    if(n != 1) {return (fracSeries(n-1)) + 1.0/n;}
    return 0; 
}
@Ryoka117 -- your two big errors are this:
1. In the case of n=1, since you don't consider "1/1" this value should be 0, not 1 as you have. This is the base case.
2. Otherwise (obviously expecting input >=1), we decrement our way down to the base case, recursively. Your second error is your return of the whole number n (e.g. 6). Instead you want 1.0/6 (decimal guaranteeing double result instead of integer division), plus a recursive call to n-1.

For clarity, I think having base case(s) first helps. Logic of Frac is same as Repeater's, though keeping the parameter an int. Here also is one possible iterative solution (Frac2).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>

using namespace std;

double Frac(int n)
{
    if (n==1)
        return 0;
    return 1.0/n + Frac(n-1);
}

double Frac2(int n)
{
    double sum = 0.0;
    while (n >= 2)
        sum += 1.0/n--;
    return sum;
}

int main() 
{
    cout << Frac(6) << endl << Frac2(6) << endl;
}
Last edited on
thanks guys, that did the trick
Topic archived. No new replies allowed.