Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

C#: The fastest Fibonacci range algorithm

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
The last one has shown itself absolutely outstanding in both simplicity and performance in selection entire range and certain element. Keeping this algorithm simple allows CLR optimizing it in a way much enough to come over others. This function is all the stuff needed:
public static IEnumerable<Int64> GetFibonacciRange(UInt32 steps)
{
for (Int64 i = 0, previous = -1, next = 1, sum = 0; i < steps; ++i)
{
sum = previous + next;
previous = next;
yield return next = sum;
}
}
And some samples of using it:
//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


This post first appeared on Ilya Tereschuk, please read the originial post: here

Share the post

C#: The fastest Fibonacci range algorithm

×

Subscribe to Ilya Tereschuk

Get updates delivered right to your inbox!

Thank you for your subscription

×