Fibonacci numbers iterator with C# yield statements
Here’s a C# iterator for generating the sequence of Fibonacci numbers. It uses the yield return statement to pass back each number in turn. By default, the arithmetic addition won’t throw an exception when previous + current is greater than UInt64.MaxValue, so I’m using a checked expression to enable overflow checking.
public static IEnumerable<ulong> FibonacciNumbers()
{
yield return 0;
yield return 1;
ulong previous = 0, current = 1;
while (true)
{
ulong next = checked(previous + current);
yield return next;
previous = current;
current = next;
}
}
We can use the iterator with a foreach loop until it throws an OverflowException.
try
{
foreach (ulong i in FibonacciNumbers())
{
Console.WriteLine("{0:0,0}", i);
}
}
catch (OverflowException)
{
Console.WriteLine("Sorry, the next number is too big.");
}
Sunday, 14 February 2010
blog comments powered by Disqus