Factorial in C#

Published on 28 December 2018 (Updated: 13 May 2026)

Welcome to the Factorial in C# page! Here, you'll find the source code for this program as well as a description of how the program works.

Current Solution

using System.Numerics;

if (args is not [var input] || !BigInteger.TryParse(input, out var n) || n < 0)
{
    Console.Error.WriteLine("Usage: please input a non-negative integer");
    return;
}

Console.WriteLine(Factorial(n));

static BigInteger Factorial(BigInteger n) => n < 2 ? BigInteger.One : MultiplyRange(2, n);

static BigInteger MultiplyRange(BigInteger lo, BigInteger hi)
{
    if (lo > hi)
        return BigInteger.One;
    if (lo == hi)
        return lo;
    if (hi - lo == 1)
        return lo * hi;

    BigInteger mid = (lo + hi) / 2;
    return MultiplyRange(lo, mid) * MultiplyRange(mid + 1, hi);
}

Factorial in C# was written by:

If you see anything you'd like to change or update, please consider contributing.

How to Implement the Solution

No 'How to Implement the Solution' section available. Please consider contributing.

How to Run the Solution

No 'How to Run the Solution' section available. Please consider contributing.