Each Fibonacci number is the sum of the two before it, starting from 0 and 1:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, ...
Written as a formula, F(0) = 0, F(1) = 1 and F(n) = F(n − 1) + F(n − 2). Below are the two classic ways to compute it in C#, why one of them is a trap, and what to do when the numbers outgrow long.
Iterative version
for (int i = 0; i < 15; i++)
Console.Write($"{Fibonacci(i)} ");
// 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
static long Fibonacci(int n)
{
ArgumentOutOfRangeException.ThrowIfNegative(n);
long previous = 1, current = 0; // F(-1) and F(0)
for (int i = 0; i < n; i++)
(previous, current) = (current, checked(previous + current));
return current;
}
The loop keeps only the last two values, so it runs in O(n) time and O(1) memory. Starting from previous = 1 (the value F(−1) would have) lets the loop handle n = 0 and n = 1 without special cases. ThrowIfNegative needs .NET 8; on older versions, throw ArgumentOutOfRangeException yourself.
Recursive version
static long FibonacciRecursive(int n)
=> n < 2 ? n : FibonacciRecursive(n - 1) + FibonacciRecursive(n - 2);
This is the formula translated directly, and it is the version most tutorials show. It returns the same numbers as the loop, but it is slow in a way that is easy to miss on small inputs.
Each call makes two more calls, and they repeat the same work over and over: FibonacciRecursive(5) computes F(3) twice and F(2) three times. The total number of calls for F(n) is 2·F(n + 1) − 1, so the run time grows as fast as the Fibonacci numbers themselves, roughly 1.6ⁿ. F(20) takes 21,891 calls, which is instant. F(40) takes 331,160,281 calls, which takes a noticeable fraction of a second. Each extra step of n multiplies the work by about 1.6, and F(50) needs about 40 billion calls.
It also returns n itself for negative input instead of throwing, so add the same guard if callers can pass a negative value.
Recursion with memoization
If you want to keep the recursive shape, store each result the first time it is computed:
static long FibonacciMemo(int n)
{
ArgumentOutOfRangeException.ThrowIfNegative(n);
return Fib(n, new long[n + 1]);
static long Fib(int n, long[] memo)
{
if (n < 2) return n;
if (memo[n] != 0) return memo[n];
return memo[n] = checked(Fib(n - 1, memo) + Fib(n - 2, memo));
}
}
Now every value is computed once, which brings the cost down to O(n). It still uses O(n) memory and O(n) stack depth, so the loop remains the better choice. Memoization is worth knowing because the same idea, “remember results of overlapping subproblems”, is the basis of dynamic programming.
Overflow: F(47) and F(93)
Fibonacci numbers grow fast. F(46) = 1,836,311,903 is the largest that fits in an int; F(47) = 2,971,215,073 does not. The original version of this post returned int, so it silently produced negative numbers from F(47) onward.
With long the limit moves to F(92) = 7,540,113,804,746,346,429. F(93) exceeds long.MaxValue. C# integer arithmetic is unchecked by default, so without the checked(...) in the examples above you would again get a wrong answer instead of an error. With it, Fibonacci(93) throws an OverflowException.
Past that, use BigInteger from System.Numerics, which has no fixed upper limit:
using System.Numerics;
Console.WriteLine(FibonacciBig(100));
// 354224848179261915075
static BigInteger FibonacciBig(int n)
{
ArgumentOutOfRangeException.ThrowIfNegative(n);
BigInteger previous = 1, current = 0;
for (int i = 0; i < n; i++)
(previous, current) = (current, previous + current);
return current;
}
BigInteger additions get slower as the numbers grow, but F(10,000), a number with 2,090 digits, still takes only milliseconds.
Generating the sequence
When you want the numbers in order rather than one specific F(n), an iterator avoids recomputing from zero each time:
Console.WriteLine(string.Join(" ", FibonacciSequence().Take(15)));
// 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
static IEnumerable<long> FibonacciSequence()
{
long previous = 1, current = 0;
while (true)
{
yield return current;
(previous, current) = (current, checked(previous + current));
}
}
The sequence is infinite, so always limit it with Take or TakeWhile. The calling loop in the first example called Fibonacci(i) fifteen times, redoing all earlier steps on each call; the iterator does each addition once.