Help with Count loop

I need help calculating a sequence of numbers

this is the equation & iteration i am trying to solve
http://i63.tinypic.com/xdys2c.png



where f(n) = (1+(n-1)/(2*(n-1)+1)(1+(n/(2*n+1)
i.e.
n = 1, f(1) = 1+ (1/3)
n=2, f(2) = 1+(1/3)*(1+(2/5))
n = 3, f(3) = 1+ (1/3) * (1+(2/5)*(1+(3/7))

the program uses an inputted n and outputs the values of f(n)
** to clear up some things; i want it to output the value of the function and each function before it i.e. f(1), f(2), f(3)

so far i have this but it just outputs the same number n amount of times, please help! :
--------------------------
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <string>
#include <cmath>

using namespace std;

int main()
{
    double i = 0, n,p, P;
    cout << "enter n value";
    cin>> n;

    if (n>0){

        while(n>i){
          i++;
          p = 1+((n-1)/(2*(n-1)+1));
         P = p*(1+(n/(2*n+1)));
         cout<<P<<endl;
        }


    }
}
Last edited on
Please use code tags.

While not wrong, using p and P without any descriptions is probably not the wisest thing to do.

As far as your problem, The only value in your code that changes is i since you increase it.
You can loop the program a billion times and the values for p and P are never going to change.

I'd recommend showing your values to test your code and learn how to troubleshoot what you write. Making variables with useful names would help and adding comments sure wouldn't hurt either.

Replace
cout<<P<<endl;
with
cout << "n=" << n << " i=" << i << " p" << p << " P=" << P << endl;
Last edited on
Sorry bout that I'm new to the forum & C++ in general, I updated the format of my post.
How would I create descriptions for p and P?
Thanks for your help!
You want it to output the value, like f(1) should return 1.33333333333 ? Or should it print out the text "1+ (1/3)" ?

The major error is you dont have an end to the while loop.

** to clear up some things; i want it to output the value of the function and each function before it i.e. f(1), f(2), f(3)

Are you saying that the input is a positive integer, and if asked for f(5) , you want it to calculate everything from f(5) down to f(1) and stop there?
Last edited on
Also, are you sure your formula is correct? I entered it into Wolfram Alpha and got this image https://i.imgur.com/HBMx3mj.png

Just want to confirm that the last term is not under the divisor
Here's some palooka code for you.

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

double prod( int n )
{
   double p = 1.0;
   for ( int r = n; r > 0; r-- ) p = 1 + p * r / ( 2 * r + 1.0 );
   return p;
}

int main()
{
   int n;
   cout << "Input n ( > 0 ):";   cin >> n;
   for ( int i = 1; i <= n; i++ ) cout << "p(" << i << ") = " << prod( i ) << '\n';
}
Topic archived. No new replies allowed.