This article is right for those who are searching for the most elegant way to implement Fibonacci Range Algorithm in C#.
Several days I was trying following variations:
- Recursive
- Recursive with TPL
- Matrices exponential
- Matrices exponential with TPL
- Clean LINQ
- Complicated formulas
- Parallelized LINQ
- Iterative
- Iterative with TPL
- Iterative with yield return
public static IEnumerable<Int64> GetFibonacciRange(UInt32 steps)And some samples of using it:
{
for (Int64 i = 0, previous = -1, next = 1, sum = 0; i < steps; ++i)
{
sum = previous + next;
previous = next;
yield return next = sum;
}
}
//Get first 5 numbers of sequence
GetFibonacciRange(5); //0 1 1 2 3
//Get first 8 numbers of sequence beginning from 1
GetFibonacciRange(9).Skip(1).Take(8); // 1 1 2 3 5 8 13 21
//Get the 15th number of sequence
GetFibonacciRange(15).Last(); //377
//OR
GetFibonacciRange(20).ElementAt(15 - 1); //377