How can you calculate large factorials using C#? Windows calculator in Win 7 overflows at Factorial (3500). As a programming and mathematical question I am interested in kno
This answer covers limits for basic .Net types to compute and represent n!
Basic code to calculate factorial for "SomeType" that supports multiplication:
SomeType factorial = 1;
int n = 35;
for (int i = 1; i <= n; i++)
{
factorial *= i;
}
Limits for built in number types:
short
- correct results up to 7!, incorrect results afterwards, code returns 0 starting 18 (similar to int)int
- correct results up to 12!, incorrect results afterwards, code returns 0 starting at 34 (Why computing factorial of realtively small numbers (34+) returns 0)float
- precise results up to 14!, correct but not precise afterwards, returns infinity starting at 35long
- correct results up to 20!, incorrect results afterwards, code returns 0 starting at 66 (similar to int
)double
- precise results up to 22!, correct but not precise afterwards, returns infinity starting at 171BigInteger
- precise and upper limit is set by memory usage only.Note: integer types overflow pretty quickly and start producing incorrect results. Realistically if you need factorials for any practical usage long
is the type to go (up to 20!), if you can't expect limited numbers - BigInteger
is the only type provided in .Net Framework to provide precise results (albeit slow for large numbers as there is no built-in optimized n! method)