How to compute the factorial of a number greater than 20 in C#

1 Answer

0 votes
using System;
using System.Numerics;

/*
    This program computes the factorial of numbers greater than 20.
    C# provides the BigInteger type, which supports arbitrary‑precision
    arithmetic and is ideal for very large factorials.
*/

class BigFactorialProgram
{
    /*
        Compute factorial using BigInteger.
        The algorithm multiplies numbers from 2 to n.
        BigInteger handles overflow internally and grows as needed.
    */
    static BigInteger FactorialBig(int n)
    {
        BigInteger result = BigInteger.One;

        for (int i = 2; i <= n; i++) {
            result *= i;
        }

        return result;
    }

    /*
        Main entry point: read input, compute factorial, print result.
    */
    static void Main()
    {
        Console.Write("Enter a number greater than 20: ");
        int n = int.Parse(Console.ReadLine());

        BigInteger result = FactorialBig(n);

        Console.WriteLine();
        Console.WriteLine($"Factorial of {n} is:");
        Console.WriteLine();
        Console.WriteLine(result);
    }
}



/*
run:

Enter a number greater than 20: 25

Factorial of 25 is:

15511210043330985984000000

*/

 



answered Sep 13 by avibootz
...