Overflow. The number of bytes used to represent the number is fixed
(sizeof(long) will give you the number of bytes, numeric_limits<long>::max() the max number that can be stored)
You will need to use a bignum library for such computation (or change the data type to double if you don't care about precision).
Compare the value of 14! to the value produced by solving Stirlings Approximation formula:
n approximately equal to e^-14 * n^n * sqrt(2(PI)n)
I understand that the value of 14! exceeds the data type I used. But it seems no matter which data type I use i cannot generate the proper result
using this formula:
14*13*12*11*10*9*8*7*6*5*4*3*2*1
I can however generate the correct answer usings stirlings formula...
#include <iostream>
#include <string>
#include <iomanip>
#include <cmath>
usingnamespace std;
int main()
{
constdouble PI = 3.14159265;
double stirlingsFormula = (1 / (pow(2.71828, 14.00))) * (pow(14.00, 14.00)) * (sqrt(2*PI*14.00));
double stirlingsFormulaExp = (exp(-14.00)) * (pow(14.00, 14.00)) * (sqrt(2*PI*14.00)); // just using exponential function here to simplify code later on
long exactFact = 14*13*12*11*10*9*8*7*6*5*4*3*2*1;
cout << stirlingsFormula << endl;
cout << stirlingsFormulaExp << endl;
cout << float(exactFact) << endl;
cout << exactFact;
cin.get();
}
as you see the two are very different. I can work out the correct answer with paper and pencil and on a calculator.. but something i just cannot seem to figure out how to store 14! properly, which data type to use to display it either as a decimal value, integer or in scientific notation!