Skip to content

Instantly share code, notes, and snippets.

@bitwalker
Last active Aug 29, 2015
Embed
What would you like to do?
.NET Newsletter #1 - Challenge
using System;
using System.Numerics;
public class Program
{
public void Main(params string[] args)
{
foreach (var n in Maths.Fib().Take(100))
{
Console.WriteLine(n);
}
}
}
public static class Maths
{
/// <summary>
/// Produces an infinite stream of numbers following the Fibonacci sequence.
/// CAUTION: Do not try and consume the entire stream with ToList or ToArray, etc.,
/// without first calling Take to restrict the number of elements produced,
/// otherwise it will never return. This kills the program.
/// </summary>
public static IEnumerable<BigInteger> Fib()
{
var a = BigInteger.Zero; // F0
var b = BigInteger.One; // F1
var c = a + b; // F2 / first step
// The sequence always starts with F0, F1
yield return a;
yield return b;
// Values are produced by shifting b -> a, c -> b, then
// adding a + b to get the next value in the sequence
while (true)
{
yield return c;
a = b; b = c; c = a + b;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment