How to Calculate Factorial and Apply Stirling's Approximation in C++?

Join the discussion
Registration is free. Start your own thread to ask a follow-up.
1 reply · 5K views
stevenviney
Messages
3
Reaction score
0
I need to write a program that prompts me to enter a positive integer N, after doing so it calculates the factorial of that integer and prints it. I am able to do this with the following code.

#include <iostream>
using namespace std;
int main()
{
double I, N, Factorial = 1; // Do not forget to initialize Factorial
count << "Enter a positive integer:" << endl;
cin >> N;
I = 1; // This initialization step has to be done. And it must be done before the while loop.
while (I <= N) // Notice there is no semicolon here.
{
Factorial = Factorial * I; // The body of the loop begins here.
I = I + 1; // You must increment I. The body of the loop ends here.
}
count << Factorial << endl;
return 0;
}


I now however need to create the condition that IF the integer is greater than 50, I need to apply Stirling's approximation which is = N (NaturalLog(N)) - N. I also need the program to initially check whether or not the integer is positive, and if not to prompt to re-enter.

Can anyone help??
 
Physics news on Phys.org
The first is just a simple if statement. You'll need to include a math library to get the log. For the second, you should loop until the integer is positive. That is, you input the integer the first time, and then enter a loop so that while the integer is not positive, you tell them so and ask them for it again.