Fibonacci Sequence Algorithm
The Fibonacci Sequence Algorithm is a mathematical concept that has been widely used in various fields such as computer science, mathematics, and finance, among others. It is a sequence of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1. This means that the sequence starts with 0, 1, 1, 2, 3, 5, 8, 13, and so on, with each number being the result of adding the previous two numbers together. The Fibonacci Sequence was first introduced by the Italian mathematician Leonardo Fibonacci in his 1202 book Liber Abaci, where he used the sequence to explain the growth of rabbit populations. Since then, the Fibonacci sequence has become an essential concept in various disciplines, including number theory, algorithm optimization, and even art and music.
There are several algorithms for generating Fibonacci numbers, with the two most common methods being the iterative and recursive approaches. The iterative method, which is a more efficient approach, involves initializing two variables with the first two numbers in the sequence (0 and 1) and then repeatedly adding them together to generate the following numbers, updating the variables as needed. In contrast, the recursive method involves using a function that calls itself with smaller arguments, breaking the problem down into smaller instances until the base cases (0 and 1) are reached. However, the recursive approach can be inefficient due to the overhead of function calls and redundant calculations, especially for larger numbers in the sequence. To overcome this limitation, various optimization techniques, such as memoization or dynamic programming, can be used to improve the performance of the recursive Fibonacci algorithm.
using System.Collections.Generic;
using System.Numerics;
namespace Algorithms.Sequences
{
/// <summary>
/// <para>
/// Fibonacci sequence.
/// </para>
/// <para>
/// Wikipedia: https://wikipedia.org/wiki/Fibonacci_number.
/// </para>
/// <para>
/// OEIS: https://oeis.org/A000045.
/// </para>
/// </summary>
public class FibonacciSequence : ISequence
{
/// <summary>
/// Gets Fibonacci sequence.
/// </summary>
public IEnumerable<BigInteger> Sequence
{
get
{
yield return 0;
yield return 1;
BigInteger previous = 0;
BigInteger current = 1;
while (true)
{
var next = previous + current;
previous = current;
current = next;
yield return next;
}
}
}
}
}