For any integer n 0 n is defined as the product n times n

For any integer n > 0, n! is defined as the product n times n - 1 times n - 2 ... times 2 times 1.0! is defined to be 1. It is sometimes useful to have a closed-form definition instead; for this purpose, an approximation can be used. R.W. Gosper proposed the following such approximation formula: n! n^n e^-n Squareroot (2n + 1/3) pi Create a program that prompts the user to enter an integer n, uses Gosper\'s formula to approximate n!, and then displays the result. The message displaying the result should look something like this: 5! equals approximately 119.97003 Your program will be easier to debug if you use some intermediate values instead of trying to compute the result in a single expression. If you are not getting the correct results, then you can compare the results of your intermediate values to what you get when you do the calculations by hand. Use at least two intermediate variables one for 2n + 1/3 and one for Squareroot (2n + 1/3) pi. Display each of these intermediate values to simplify debugging. Be sure to use a named constant for PI, and use the approximation 3.14159265. Test the program on nonnegative integers less than 8.

Solution

// C++ code approximate n factorial

#include <iostream>
#include <string.h>
#include <fstream>
#include <limits.h>
#include <stdlib.h>
#include <math.h>
#include <iomanip>

using namespace std;


#define M_PI 3.14159265358979323846 /* pi */
#define e 2.70938182845904523536

int main ()
{
int n;

cout << \"Enter n:\";
cin >> n;

float result = pow(n,n)*pow(e,-1*n)*sqrt((2*n+1/3)*M_PI);

cout << n << \"! equals approximaltely \"<< result << endl;
return 0;
}


/*
output:

Enter n:5
5! equals approximaltely 119.97

*/

 For any integer n > 0, n! is defined as the product n times n - 1 times n - 2 ... times 2 times 1.0! is defined to be 1. It is sometimes useful to have a cl

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site