Recursive computation of a factorial should be slow due to high problem complexity. Why is not my basic implementation painfully slow? I am curious, since this should be textbook example of a bad approach.
Is it because some internal optimization or caching results in C# program?
using System;
using System.Diagnostics;
using System.Numerics;
namespace FactorialRecursion
{
class Program
{
static void Main(string[] args)
{
Stopwatch stopwatch = new Stopwatch();
for (int i = 0; i < 4000; i++)
{
stopwatch.Reset();
stopwatch.Start();
Factorial(i);
stopwatch.Stop();
Console.WriteLine($"{i}! = ({stopwatch.Elapsed})");
}
Console.ReadKey();
}
static BigInteger Factorial(BigInteger number)
{
if (number <= 1)
return 1;
return number * Factorial(number - 1);
}
}
}
The results are here:
3990! = (00:00:00.0144319)
3991! = (00:00:00.0149198)
3992! = (00:00:00.0159502)
3993! = (00:00:00.0116784)
3994! = (00:00:00.0104608)
3995! = (00:00:00.0122931)
3996! = (00:00:00.0128695)
3997! = (00:00:00.0131792)
3998! = (00:00:00.0142510)
3999! = (00:00:00.0145544)