Find the Nth Fibonacci Number

One of the earliest forms of interviewer/interviewee communication. I have placed the Rosetta stone of said language below. I found the Linq example in an ancient tome, I made up the recursive version.

Back to Code Samples

public static class Fibonacci
{
//===================================================================
/// <summary>
/// Find the Nth Fibonacci value using recursion.
/// </summary>
/// <remarks>This is slightly faster than Linq in debug code.</remarks>
/// <param name="nThValue">The value to return.</param>
//===================================================================
public static uint ViaRecursion(uint nThValue)
{
if (nThValue <= 1)
return nThValue;
else
return (ViaRecursion(nThValue - 1) + ViaRecursion(nThValue - 2));
}

//===================================================================
/// <summary>
/// Find the Nth Fibonacci value using Linq.
/// </summary>
/// <remarks>This is slightly slower than recursion in debug code. Not as readable either.</remarks>
/// <param name="nThValue">The value to return.</param>
//===================================================================
public static uint ViaLinq(uint nthValue)
{
Func<uint, uint> fib = null;
fib = n => n > 1 ? fib(n - 1) + fib(n - 2) : n;

return fib(nthValue);
}
}

Back to Code Samples