In C# interview, you may be asked How To find the factorial of 999 in C#, you cannot use int, long, or even decimal because factorial values grow extremely fast.
Use BigInteger from System.Numerics.
Example:
using System;
using System.Numerics;
class Program
{
static BigInteger Factorial(int n)
{
BigInteger result = 1;
for (int i = 2; i <= n; i++)
{
result *= i;
}
return result;
}
static void Main()
{
int number = 999;
BigInteger factorial = Factorial(number);
Console.WriteLine(factorial);
}
}
Output
This prints the exact value of 999! (a huge number).
Why BigInteger?
Look at the approximate limits of different data types:
- int → up to ~2 billion → only enough for 12!
- long → up to ~9 quintillion → only enough for 20!
- BigInteger → arbitrary precision (limited mainly by memory)
Alternative Solution: Short version using LINQ
using System;
using System.Linq;
using System.Numerics;
BigInteger factorial =
Enumerable.Range(1, 999)
.Aggregate(BigInteger.One, (a, b) => a * b);
Console.WriteLine(factorial);
Count digits of 999!
Console.WriteLine(factorial.ToString().Length);
999! contains 2,565 digits.
No comments:
Post a Comment