Fibonacci LINQ Sequence Generator Revisited

by Ian Davis on May 4, 2010

in Programming

It was pointed out that the sequence generator could be written as an infinite sequence to allow .Skip(), .Take(), .ElementAt(), etc. Here is the infinite sequence version.

public static class Fibonacci
{
	public static IEnumerable<BigInteger> Generate()
	{
		yield return 1;
		yield return 1;

		BigInteger n1 = 1, n2 = 1;
		while(true)
		{
			BigInteger n3 = n1 + n2;
			n1 = n2;
			n2 = n3;
			yield return n3;
		}
	}
}

Previous post:

Next post: