Skip to content

Instantly share code, notes, and snippets.

@VladimirReshetnikov
Last active January 3, 2016 15:18
Show Gist options
  • Save VladimirReshetnikov/8481602 to your computer and use it in GitHub Desktop.
Save VladimirReshetnikov/8481602 to your computer and use it in GitHub Desktop.
using System;
using System.Numerics; // Add a reference to System.Numerics.dll
using System.Runtime.CompilerServices;
using System.Threading;
class Program
{
static void Main()
{
Console.WriteLine(Factorial(15000));
}
static BigInteger Factorial(BigInteger n)
{
BigInteger? result = null;
int stackSize = 0x40000;
while (true)
{
var worker = new Thread(
() => { try { result = FactorialRecursive(n); } catch (InsufficientExecutionStackException) { } },
stackSize);
worker.Start();
worker.Join();
if (result.HasValue)
{
return result.Value;
}
stackSize *= 2;
}
}
static BigInteger FactorialRecursive(BigInteger n)
{
RuntimeHelpers.EnsureSufficientExecutionStack();
return n == 0 ? 1 : n * FactorialRecursive(n - 1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment