I was asked this question in interview. Output of below algorithm is perfectly fine, but it's very slow for larger input parameters. How can we improve it's performance without changing calculation logic?
public static int SomeAlgo(int n)
{
if ((n == 0) || (n == 1))
{
return n;
}
else
{
return SomeAlgo(n - 1) + SomeAlgo(n - 2);
}
}
It become very slow starting from parameter value 40. I'm using below code to check time taken to execute:
static void Main(string[] args)
{
var watch = System.Diagnostics.Stopwatch.StartNew();
Console.WriteLine("Algo Output: " + SomeAlgo(40));
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;
Console.WriteLine("Time taken in ms: " + elapsedMs);
Console.ReadLine();
}