I'm trying to represent the following mathematical expression in C:
P(n) = (n!)(6^n)
The program should compute the answer to expression when n
= 156. I have attempted to create the program in C and it fails to produce an answer. The answer is approximately 10^397. The program utilises 2 logarithmic identities. It also utilises Stirling's approximation to calculate the large factorial.
How can I make it produce the correct answer and do you have any suggestions as to how I could improve the code? (I'm fairly new to programming):
#include <math.h>
typedef unsigned int uint;
int main()
{
uint n=156; // Declare variables
double F,pi=3.14159265359,L,e=exp(1),P;
F = sqrt(2*pi*n) * pow((n/e),n); // Stirling's Approximation Formula
L = log(F) + n*log(6); // Transform P(n) using logarithms - log(xy) = log(x) + log(y) and log(y^n) = n*log(y)
P = pow(e,L); // Transform the resultant logarithm back to a normal numbers
}
Thank you! :)
Loosely speaking, in C a double is represented as a base number raised to a power. As already mentioned, the maximum is roughly 1E308, but as you get to larger and larger numbers (or smaller and smaller), you lose precision because the base number has a finite number of digits and cannot always be accurately represented in this way.
See http://en.wikipedia.org/wiki/Double-precision_floating-point_format for more information